summaryrefslogtreecommitdiff
path: root/_dbus_bindings/message-append-impl.h
blob: d20caa52cdf5ba2e9d1c67269e076565b9656267 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
/* D-Bus Message serialization. This contains all the logic to map from
 * Python objects to D-Bus types.
 *
 * Copyright (C) 2006 Collabora Ltd.
 *
 * Licensed under the Academic Free License version 2.1
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

PyDoc_STRVAR(Message_append__doc__,
"set_args(*args[, **kwargs])\n\n"
"Set the message's arguments from the positional parameter, according to\n"
"the signature given by the ``signature`` keyword parameter.\n"
"\n"
"The following type conversions are supported:\n\n"
"=============================== ===========================\n"
"D-Bus (in signature)            Python\n"
"=============================== ===========================\n"
"boolean (b)                     any object (via bool())\n"
"byte (y)                        string of length 1\n"
"                                any integer\n"
"any integer type                any integer\n"
"double (d)                      any float\n"
"variant                         Variant\n"
"                                any object (guess type as below)\n"
"string, signature, object path  str (must be UTF-8) or unicode\n"
"dict (a{...})                   any mapping\n"
"array (a...)                    any iterable over appropriate objects\n"
"struct ((...))                  any iterable over appropriate objects\n"
"=============================== ===========================\n"
"\n"
"Here 'any integer' means anything on which int() or long()\n"
"(as appropriate) will work, except for basestring subclasses.\n"
"'Any float' means anything on which float() will work, except\n"
"for basestring subclasses.\n"
"\n"
"If there is no signature, guess from the arguments using\n"
"the static method `Message.guess_signature`.\n"
);

PyDoc_STRVAR(Message_guess_signature__doc__,
"guess_signature(*args) -> Signature [static method]\n\n"
"Guess a D-Bus signature which should be used to encode the given\n"
"Python objects.\n"
"\n"
"The signature is constructed as follows:\n\n"
"=============================== ===========================\n"
"Python                          D-Bus\n"
"=============================== ===========================\n"
"bool                            boolean (y)\n"
"dbus.Int16, etc.                the corresponding type\n"
"any other int subclass          int32 (i) (FIXME: make this error?)\n"
"long or a subclass              int64 (x) (FIXME: make this error?)\n"
"float or a subclass             double (d)\n"
"dbus.ObjectPath, dbus.Signature the corresponding type (o, g)\n"
"dbus.ByteArray or subclass      array of byte (ay)\n"
"dbus.Byte or subclass           byte (y)\n"
"str or any other subclass       string (s)\n"
"unicode or a subclass           string (s)\n"
"dbus.Variant or subclass        variant (v), guess contents' type\n"
"tuple or a subclass             struct ((...)), guess contents' types\n"
"list or a subclass              array (a...), guess contents' type\n"
"                                according to type of first item\n"
"dict or a subclass              dict (a{...}), guess key, value type\n"
"                                according to types for an arbitrary item\n"
"anything else                   raise TypeError\n"
"=============================== ===========================\n"
);

/* Return a new reference. */
static PyObject *
_signature_string_from_pyobject(PyObject *obj)
{
    /* Ordering is important: some of these are subclasses of each other. */
    if (obj == Py_True || obj == Py_False)
      return PyString_FromString(DBUS_TYPE_BOOLEAN_AS_STRING);
    else if (PyInt_Check(obj)) {
        if (Int16_Check(obj))
            return PyString_FromString(DBUS_TYPE_INT16_AS_STRING);
        else if (Int32_Check(obj))
            return PyString_FromString(DBUS_TYPE_INT32_AS_STRING);
        else if (UInt16_Check(obj))
            return PyString_FromString(DBUS_TYPE_UINT16_AS_STRING);
        else
            return PyString_FromString(DBUS_TYPE_INT32_AS_STRING);
    }
    else if (PyLong_Check(obj)) {
        if (Int64_Check(obj))
            return PyString_FromString(DBUS_TYPE_INT64_AS_STRING);
        else if (UInt32_Check (obj))
            return PyString_FromString(DBUS_TYPE_UINT32_AS_STRING);
        else if (UInt64_Check (obj))
            return PyString_FromString(DBUS_TYPE_UINT64_AS_STRING);
        else
            return PyString_FromString(DBUS_TYPE_INT64_AS_STRING);
    }
    else if (PyUnicode_Check(obj))
        return PyString_FromString(DBUS_TYPE_STRING_AS_STRING);
    else if (PyFloat_Check(obj))
        return PyString_FromString(DBUS_TYPE_DOUBLE_AS_STRING);
    else if (Variant_Check(obj)) {
        return PyString_FromString(DBUS_TYPE_VARIANT_AS_STRING);
    }
    else if (PyString_Check(obj)) {
        if (Byte_Check(obj))
            return PyString_FromString(DBUS_TYPE_BYTE_AS_STRING);
        else if (ObjectPath_Check(obj))
            return PyString_FromString(DBUS_TYPE_OBJECT_PATH_AS_STRING);
        else if (Signature_Check(obj))
            return PyString_FromString(DBUS_TYPE_SIGNATURE_AS_STRING);
        else if (ByteArray_Check(obj))
            return PyString_FromString(DBUS_TYPE_ARRAY_AS_STRING
                                       DBUS_TYPE_BYTE_AS_STRING);
        else
            return PyString_FromString(DBUS_TYPE_STRING_AS_STRING);
    }
    else if (PyTuple_Check (obj)) {
        int len = PyTuple_GET_SIZE(obj);
        PyObject *list = PyList_New(len + 2);   /* new ref */
        PyObject *item;                         /* temporary new ref */
        PyObject *empty_str;                    /* temporary new ref */
        PyObject *ret;
        int i;

        if (!list) return NULL;
        if (len == 0) {
            PyErr_SetString(PyExc_ValueError, "D-Bus structs cannot be empty");
            Py_DECREF (list);
            return NULL;
        }
        /* Set the first and last elements of list to be the parentheses */
        item = PyString_FromString(DBUS_STRUCT_BEGIN_CHAR_AS_STRING);
        if (PyList_SetItem(list, 0, item) < 0) {
            Py_DECREF(list);
            return NULL;
        }
        item = PyString_FromString(DBUS_STRUCT_END_CHAR_AS_STRING);
        if (PyList_SetItem(list, len + 1, item) < 0) {
            Py_DECREF(list);
            return NULL;
        }
        if (!item || !PyList_GET_ITEM(list, 0)) {
            Py_DECREF(list);
            return NULL;
        }
        item = NULL;

        for (i = 0; i < len; i++) {
            item = PyTuple_GetItem(obj, i);
            if (!item) {
                Py_DECREF(list);
                return NULL;
            }
            item = _signature_string_from_pyobject(item);
            if (!item) {
                Py_DECREF(list);
                return NULL;
            }
            if (PyList_SetItem(list, i + 1, item) < 0) {
                Py_DECREF(list);
                return NULL;
            }
            item = NULL;
        }
        empty_str = PyString_FromString("");
        if (!empty_str) {
            /* really shouldn't happen */
            Py_DECREF(list);
            return NULL;
        }
        ret = PyObject_CallMethod(empty_str, "join", "(O)", list); /* new ref */
        /* whether ret is NULL or not, */
        Py_DECREF(empty_str);
        Py_DECREF(list);
        return ret;
    }
    else if (PyList_Check(obj)) {
        PyObject *tmp;
        PyObject *ret = PyString_FromString(DBUS_TYPE_ARRAY_AS_STRING);
        if (!ret) return NULL;
        if (PyList_GET_SIZE(obj) == 0) {
            /* No items, so fail. Or should we guess "av"? */
            PyErr_SetString (PyExc_ValueError, "Unable to guess signature "
                             "from an empty list");
            return NULL;
        }
        tmp = PyList_GetItem(obj, 0);
        tmp = _signature_string_from_pyobject(tmp);
        if (!tmp) return NULL;
        PyString_ConcatAndDel (&ret, tmp);
        return ret;
    }
    else if (PyDict_Check(obj)) {
        PyObject *key, *value, *keysig, *valuesig;
        int pos = 0;
        PyObject *ret = NULL;

        if (!PyDict_Next(obj, &pos, &key, &value)) {
            /* No items, so fail. Or should we guess "a{vv}"? */
            PyErr_SetString(PyExc_ValueError, "Unable to guess signature "
                             "from an empty dict");
            return NULL;
        }
        keysig = _signature_string_from_pyobject(key);
        valuesig = _signature_string_from_pyobject(value);
        if (keysig && valuesig) {
            ret = PyString_FromFormat ((DBUS_TYPE_ARRAY_AS_STRING
                                        DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
                                        "%s%s"
                                        DBUS_DICT_ENTRY_END_CHAR_AS_STRING),
                                       PyString_AS_STRING(keysig),
                                       PyString_AS_STRING(valuesig));
        }
        Py_XDECREF(keysig);
        Py_XDECREF(valuesig);
        return ret;
    }
    else {
        PyErr_Format(PyExc_TypeError, "Don't know how which D-Bus type "
                     "to use to encode type \"%s\"",
                     obj->ob_type->tp_name);
        return NULL;
    }
}

static PyObject *
Message_guess_signature(PyObject *unused, PyObject *args)
{
    PyObject *tmp, *ret = NULL;

    if (!args) {
        if (!PyErr_Occurred()) {
            PyErr_BadInternalCall();
        }
        return NULL;
    }

#ifdef USING_DBG
    fprintf(stderr, "DBG/%ld: called Message_guess_signature(*", (long)getpid());
    PyObject_Print(args, stderr, 0);
    fprintf(stderr, ")\n");
#endif

    if (!PyTuple_Check(args)) {
        DBG("%s", "Message_guess_signature: args not a tuple");
        PyErr_BadInternalCall();
        return NULL;
    }

    /* if there were no args, easy */
    if (PyTuple_GET_SIZE(args) == 0) {
        DBG("%s", "Message_guess_signature: no args, so return Signature('')");
        return PyObject_CallFunction((PyObject *)&SignatureType, "(s)", "");
    }

    /* if there were args, the signature we want is, by construction,
     * exactly the signature we get for the tuple args, except that we don't
     * want the parentheses. */
    tmp = _signature_string_from_pyobject(args);
    if (!tmp) {
        DBG("%s", "Message_guess_signature: failed");
        return NULL;
    }
    if (!PyString_Check(tmp) || PyString_GET_SIZE(tmp) < 2) {
        PyErr_SetString(PyExc_RuntimeError, "Internal error: "
                        "_signature_string_from_pyobject returned "
                        "a bad result");
        Py_DECREF(tmp);
        return NULL;
    }
    ret = PyObject_CallFunction((PyObject *)&SignatureType, "(s#)",
                                PyString_AS_STRING (tmp) + 1,
                                PyString_GET_SIZE (tmp) - 2);
    DBG("Message_guess_signature: returning Signature at %p", ret);
    Py_DECREF (tmp);
    return ret;
}

static int _message_iter_append_pyobject(DBusMessageIter *appender,
                                         DBusSignatureIter *sig_iter,
                                         PyObject *obj);

static int
_message_iter_append_string(DBusMessageIter *appender,
                            int sig_type, PyObject *obj)
{
    char *s;

    if (PyString_Check (obj)) {
        /* Raise TypeError if the string has embedded NULs */
        if (PyString_AsStringAndSize (obj, &s, NULL) < 0) return -1;
        /* Surely there's a faster stdlib way to validate UTF-8... */
        PyObject *unicode = PyUnicode_DecodeUTF8 (s, PyString_GET_SIZE (obj),
                                                  NULL);
        if (!unicode) {
            PyErr_SetString (PyExc_UnicodeError, "String parameters "
                             "to be sent over D-Bus must be valid UTF-8");
            return -1;
        }
        Py_DECREF (unicode);
        unicode = NULL;

        DBG("Performing actual append: string %s", s);
        if (!dbus_message_iter_append_basic (appender, sig_type,
                                             &s)) {
            PyErr_NoMemory();
            return -1;
        }
    }
    else if (PyUnicode_Check (obj)) {
        PyObject *utf8 = PyUnicode_AsUTF8String (obj);
        if (!utf8) return -1;
        /* Raise TypeError if the string has embedded NULs */
        if (PyString_AsStringAndSize (utf8, &s, NULL) < 0) return -1;
        DBG("Performing actual append: string (from unicode) %s", s);
        if (!dbus_message_iter_append_basic (appender, sig_type, &s)) {
            PyErr_NoMemory();
            return -1;
        }
        Py_DECREF (utf8);
    }
    else {
        PyErr_SetString (PyExc_TypeError,
                         "Expected a string or unicode object");
        return -1;
    }
    return 0;
}

static int
_message_iter_append_byte(DBusMessageIter *appender, PyObject *obj)
{
    unsigned char y;

    if (PyString_Check(obj)) {
        if (PyString_GET_SIZE(obj) != 1) {
            PyErr_Format(PyExc_ValueError, "Expected a string of "
                         "length 1 byte, but found %d bytes",
                         PyString_GET_SIZE (obj));
            return -1;
        }
        y = *(unsigned char *)PyString_AS_STRING(obj);
    }
    else {
        long i = PyInt_AsLong (obj);

        if (i == -1 && PyErr_Occurred()) return -1;
        if (i < 0 || i > 0xff) {
            PyErr_Format(PyExc_ValueError, "%d outside range for a "
                         "byte value", (int)i);
            return -1;
        }
        y = i;
    }
    DBG("Performing actual append: byte (from unicode) \\x%02x", (unsigned)y);
    if (!dbus_message_iter_append_basic(appender, DBUS_TYPE_BYTE, &y)) {
        PyErr_NoMemory();
        return -1;
    }
    return 0;
}

static int
_message_iter_append_dictentry(DBusMessageIter *appender,
                               DBusSignatureIter *sig_iter,
                               PyObject *dict, PyObject *key)
{
    DBusSignatureIter sub_sig_iter;
    DBusMessageIter sub;
    int ret = -1;
    PyObject *value = PyObject_GetItem(dict, key);

    if (!value) return -1;

#ifdef USING_DBG
    fprintf(stderr, "Append dictentry: ");
    PyObject_Print(key, stderr, 0);
    fprintf(stderr, " => ");
    PyObject_Print(value, stderr, 0);
    fprintf(stderr, "\n");
#endif

    DBG("Recursing signature iterator %p -> %p", sig_iter, &sub_sig_iter);
    dbus_signature_iter_recurse(sig_iter, &sub_sig_iter);
#ifdef USING_DBG
    {
        char *s;
        s = dbus_signature_iter_get_signature(sig_iter);
        DBG("Signature of parent iterator %p is %s", sig_iter, s);
        dbus_free(s);
        s = dbus_signature_iter_get_signature(&sub_sig_iter);
        DBG("Signature of sub-iterator %p is %s", &sub_sig_iter, s);
        dbus_free(s);
    }
#endif

    DBG("%s", "Opening DICT_ENTRY container");
    if (!dbus_message_iter_open_container(appender, DBUS_TYPE_DICT_ENTRY,
                                          NULL, &sub)) {
        PyErr_NoMemory();
        goto out;
    }
    ret = _message_iter_append_pyobject(&sub, &sub_sig_iter, key);
    if (ret == 0) {
        ret = _message_iter_append_pyobject(&sub, &sub_sig_iter, value);
    }
    DBG("%s", "Closing DICT_ENTRY container");
    if (!dbus_message_iter_close_container(appender, &sub)) {
        PyErr_NoMemory();
        ret = -1;
    }
out:
    Py_DECREF(value);
    return ret;
}

static int
_message_iter_append_multi(DBusMessageIter *appender,
                           const DBusSignatureIter *sig_iter,
                           int mode, PyObject *obj)
{
    DBusMessageIter sub_appender;
    DBusSignatureIter sub_sig_iter;
    PyObject *contents;
    int ret;
    PyObject *iterator = PyObject_GetIter(obj);
    char *sig = NULL;
    int container = mode;

#ifdef USING_DBG
    fprintf(stderr, "Appending multiple: ");
    PyObject_Print(obj, stderr, 0);
    fprintf(stderr, "\n");
#endif

    if (!iterator) return -1;
    if (mode == DBUS_TYPE_DICT_ENTRY) container = DBUS_TYPE_ARRAY;

    DBG("Recursing signature iterator %p -> %p", sig_iter, &sub_sig_iter);
    dbus_signature_iter_recurse(sig_iter, &sub_sig_iter);
#ifdef USING_DBG
    {
        char *s;
        s = dbus_signature_iter_get_signature(sig_iter);
        DBG("Signature of parent iterator %p is %s", sig_iter, s);
        dbus_free(s);
        s = dbus_signature_iter_get_signature(&sub_sig_iter);
        DBG("Signature of sub-iterator %p is %s", &sub_sig_iter, s);
        dbus_free(s);
    }
#endif

    if (mode == DBUS_TYPE_ARRAY || mode == DBUS_TYPE_DICT_ENTRY) {
        sig = dbus_signature_iter_get_signature(&sub_sig_iter);
        if (!sig) {
            PyErr_NoMemory();
            ret = -1;
            goto out;
        }
    }
    /* else leave sig set to NULL. */

    DBG("Opening %c container", container);
    if (!dbus_message_iter_open_container(appender, container,
                                          sig, &sub_appender)) {
        PyErr_NoMemory();
        ret = -1;
        goto out;
    }
    ret = 0;
    while ((contents = PyIter_Next(iterator))) {

        if (mode == DBUS_TYPE_ARRAY || mode == DBUS_TYPE_DICT_ENTRY) {
            DBG("Recursing signature iterator %p -> %p", sig_iter, &sub_sig_iter);
            dbus_signature_iter_recurse(sig_iter, &sub_sig_iter);
#ifdef USING_DBG
            {
                char *s;
                s = dbus_signature_iter_get_signature(sig_iter);
                DBG("Signature of parent iterator %p is %s", sig_iter, s);
                dbus_free(s);
                s = dbus_signature_iter_get_signature(&sub_sig_iter);
                DBG("Signature of sub-iterator %p is %s", &sub_sig_iter, s);
                dbus_free(s);
            }
#endif
        }

        if (mode == DBUS_TYPE_DICT_ENTRY) {
            ret = _message_iter_append_dictentry(&sub_appender, &sub_sig_iter,
                                                 obj, contents);
        }
        else {
            ret = _message_iter_append_pyobject(&sub_appender, &sub_sig_iter,
                                                contents);
        }
        Py_DECREF(contents);
        if (ret < 0) {
            break;
        }
    }
    if (PyErr_Occurred()) ret = -1;
    /* This must be run as cleanup, even on failure. */
    DBG("Closing %c container", container);
    if (!dbus_message_iter_close_container(appender, &sub_appender)) {
        PyErr_NoMemory();
        ret = -1;
    }

out:
    Py_XDECREF(iterator);
    dbus_free(sig);
    return ret;
}

static int
_message_iter_append_string_as_byte_array (DBusMessageIter *appender,
                                           PyObject *obj)
{
    /* a bit of a faster path for byte arrays that are strings */
    int len = PyString_GET_SIZE(obj);
    const char *s;
    DBusMessageIter sub;
    int ret;

    s = PyString_AS_STRING(obj);
    DBG("Opening ARRAY container", 0);
    if (!dbus_message_iter_open_container(appender, DBUS_TYPE_ARRAY,
                                          DBUS_TYPE_BYTE_AS_STRING, &sub)) {
        PyErr_NoMemory();
        return -1;
    }
    DBG("Appending fixed array of %d bytes", len);
    if (dbus_message_iter_append_fixed_array(&sub, DBUS_TYPE_BYTE, &s, len)) {
        ret = 0;
    }
    else {
        PyErr_NoMemory();
        ret = -1;
    }
    DBG("Clossing ARRAY container", 0);
    if (!dbus_message_iter_close_container(appender, &sub)) {
        PyErr_NoMemory();
        return -1;
    }
    return ret;
}

/* Encode some Python object into a D-Bus variant slot. */
static int
_message_iter_append_variant(DBusMessageIter *appender, PyObject *obj)
{
    DBusMessageIter sub;
    DBusSignatureIter sig_iter;
    const char *sig_str;
    PyObject *sig, *guess_args;
    int ret;

    if (Variant_Check (obj)) {
        /* make sig an owned reference */
        sig = ((Variant *)obj)->signature;
        if (!sig) {
            PyErr_SetString(PyExc_RuntimeError, "Internal error: "
                            "broken Variant");
            return -1;
        }
        Py_INCREF(sig);
        /* obj is still a borrowed reference though */
        obj = ((Variant *)obj)->object;
    }
    else {
        /* Either it's a Variant with no explicit signature, or it's a
        value. */
        guess_args = Py_BuildValue("(O)", obj);
        if (!guess_args) return -1;
        sig = Message_guess_signature (NULL, guess_args);
        Py_DECREF(guess_args);
        if (!sig) return -1;
    }

    sig_str = PyString_AsString(sig);
    if (!sig_str) return -1;

    dbus_signature_iter_init (&sig_iter, sig_str);

    DBG("Opening VARIANT container", 0);
    if (!dbus_message_iter_open_container (appender, DBUS_TYPE_VARIANT,
                                           sig_str, &sub)) {
        PyErr_NoMemory();
        ret = -1;
        goto out;
    }
    ret = _message_iter_append_pyobject(&sub, &sig_iter, obj);
    DBG("Closing VARIANT container", 0);
    if (!dbus_message_iter_close_container (appender, &sub)) {
        PyErr_NoMemory();
        ret = -1;
    }
out:
    Py_XDECREF (sig);
    return ret;
}

static int
_message_iter_append_pyobject(DBusMessageIter *appender,
                              DBusSignatureIter *sig_iter,
                              PyObject *obj)
{
    int sig_type = dbus_signature_iter_get_current_type (sig_iter);
    union {
      dbus_bool_t b;
      double d;
      dbus_uint16_t uint16;
      dbus_int16_t int16;
      dbus_uint32_t uint32;
      dbus_int32_t int32;
#if defined(DBUS_HAVE_INT64) && defined(HAVE_LONG_LONG)
      dbus_uint64_t uint64;
      dbus_int64_t int64;
#endif
    } u;
    int ret = -1;

#ifdef USING_DBG
    fprintf(stderr, "Appending object: ");
    PyObject_Print(obj, stderr, 0);
    fprintf(stderr, ", dbus wants type %c\n", sig_type);
#endif

    switch (sig_type) {
      /* The numeric types are relatively simple to deal with, so are
       * inlined here. */

      case DBUS_TYPE_BOOLEAN:
          if (PyObject_IsTrue(obj)) {
              u.b = 1;
          }
          else {
              u.b = 0;
          }
          DBG("Performing actual append: bool(%ld)", (long)u.b);
          if (!dbus_message_iter_append_basic (appender, sig_type, &u.b)) {
              PyErr_NoMemory();
              ret = -1;
              break;
          }
          ret = 0;
          break;

      case DBUS_TYPE_DOUBLE:
          u.d = PyFloat_AsDouble (obj);
          if (PyErr_Occurred()) {
              ret = -1;
              break;
          }
          DBG("Performing actual append: double(%f)", u.d);
          if (!dbus_message_iter_append_basic(appender, sig_type, &u.d)) {
              PyErr_NoMemory();
              ret = -1;
              break;
          }
          ret = 0;
          break;

          /* The integer types are all basically the same - we delegate to
          intNN_range_check() */
#define PROCESS_INTEGER(size) \
          u.size = size##_range_check (obj);\
          if (u.size == (dbus_##size##_t)(-1) && PyErr_Occurred()) {\
              ret = -1; \
              break; \
          }\
          DBG("Performing actual append: " #size "(%lld)", (long long)u.size); \
          if (!dbus_message_iter_append_basic(appender, sig_type, &u.size)) {\
              PyErr_NoMemory();\
              ret = -1;\
              break;\
          } \
          ret = 0;

      case DBUS_TYPE_INT16:
          PROCESS_INTEGER(int16)
          break;
      case DBUS_TYPE_UINT16:
          PROCESS_INTEGER(uint16)
          break;
      case DBUS_TYPE_INT32:
          PROCESS_INTEGER(int32)
          break;
      case DBUS_TYPE_UINT32:
          PROCESS_INTEGER(uint32)
          break;
#if defined(DBUS_HAVE_INT64) && defined(HAVE_LONG_LONG)
      case DBUS_TYPE_INT64:
          PROCESS_INTEGER(int64)
          break;
      case DBUS_TYPE_UINT64:
          PROCESS_INTEGER(uint64)
          break;
#else
      case DBUS_TYPE_INT64:
      case DBUS_TYPE_UINT64:
          PyErr_SetString (PyExc_RuntimeError, "64-bit integers not "
                           "supported on this platform");
          ret = -1;
          break;
#endif
#undef PROCESS_INTEGER

      /* Now the more complicated cases, which are delegated to helper
       * functions (although in practice, the compiler will hopefully
       * inline them anyway). */

      case DBUS_TYPE_STRING:
      case DBUS_TYPE_SIGNATURE:
      case DBUS_TYPE_OBJECT_PATH:
          ret = _message_iter_append_string(appender, sig_type, obj);
          break;

      case DBUS_TYPE_BYTE:
          ret = _message_iter_append_byte(appender, obj);
          break;

      case DBUS_TYPE_ARRAY:
          /* 3 cases - it might actually be a dict, or it might be a byte array
           * being copied from a string (for which we have a faster path),
           * or it might be a generic array. */

          sig_type = dbus_signature_iter_get_element_type(sig_iter);
          if (sig_type == DBUS_TYPE_DICT_ENTRY)
            ret = _message_iter_append_multi(appender, sig_iter,
                                             DBUS_TYPE_DICT_ENTRY, obj);
          else if (sig_type == DBUS_TYPE_BYTE && PyString_Check(obj))
            ret = _message_iter_append_string_as_byte_array(appender, obj);
          else
            ret = _message_iter_append_multi(appender, sig_iter,
                                             DBUS_TYPE_ARRAY, obj);
          DBG("_message_iter_append_multi(): %d", ret);
          break;

      case DBUS_TYPE_STRUCT:
          ret = _message_iter_append_multi(appender, sig_iter, sig_type, obj);
          break;

      case DBUS_TYPE_VARIANT:
          ret = _message_iter_append_variant(appender, obj);
          break;

      case DBUS_TYPE_INVALID:
          PyErr_SetString(PyExc_TypeError, "Fewer items found in D-Bus "
                          "signature than in Python arguments");
          ret = -1;
          break;

      default:
          PyErr_Format(PyExc_TypeError, "Unknown type '\\x%x' in D-Bus "
                       "signature", sig_type);
          ret = -1;
          break;
    }
    if (ret < 0) return -1;
  
    DBG("Advancing signature iter at %p", sig_iter);
#ifdef USING_DBG
    { dbus_bool_t b =
#endif
    dbus_signature_iter_next(sig_iter);
#ifdef USING_DBG
    DBG("- result: %ld", (long)b);
    }
#endif
    return 0;
}


static PyObject *
Message_append(Message *self, PyObject *args, PyObject *kwargs)
{
    const char *signature = NULL;
    PyObject *signature_obj = NULL;
    DBusSignatureIter sig_iter;
    DBusMessageIter appender;
    int i;
    static char *argnames[] = {"signature", NULL};

    if (!self->msg) return DBusException_UnusableMessage ();

#ifdef USING_DBG
    fprintf(stderr, "DBG/%ld: called Message_append(*", (long)getpid());
    PyObject_Print(args, stderr, 0);
    if (kwargs) {
        fprintf(stderr, ", **");
        PyObject_Print(kwargs, stderr, 0);
    }
    fprintf(stderr, ")\n");
#endif

    /* only use kwargs for this step: deliberately ignore args for now */
    if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwargs, "|z:append",
                                     argnames, &signature)) return NULL;

    if (!signature) {
        DBG("%s", "No signature for message, guessing...");
        signature_obj = Message_guess_signature(NULL, args);
        if (!signature_obj) return NULL;
        signature = PyString_AS_STRING (signature_obj);
    }
    /* from here onwards, you have to do a goto rather than returning NULL
    to make sure signature_obj gets freed */

    /* iterate over args and the signature, together */
    if (!dbus_signature_validate(signature, NULL)) {
        PyErr_SetString(PyExc_ValueError, "Corrupt type signature");
        goto err;
    }
    dbus_signature_iter_init(&sig_iter, signature);
    dbus_message_iter_init_append(self->msg, &appender);
    for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
        if (_message_iter_append_pyobject(&appender, &sig_iter,
                                          PyTuple_GET_ITEM (args, i)) < 0) {
            goto hosed;
        }
    }
    if (dbus_signature_iter_get_current_type(&sig_iter)
        != DBUS_TYPE_INVALID) {
        PyErr_SetString(PyExc_TypeError, "More items found in D-Bus "
                        "signature than in Python arguments");
        goto hosed;
    }

    /* success! */
    Py_XDECREF(signature_obj);
    Py_RETURN_NONE;

hosed:
    /* "If appending any of the arguments fails due to lack of memory,
     * generally the message is hosed and you have to start over" -libdbus docs
     * Enforce this by throwing away the message structure.
     */
    dbus_message_unref(self->msg);
    self->msg = NULL;
err:
    Py_XDECREF(signature_obj);
    return NULL;
}

/* vim:set ft=c cino< sw=4 sts=4 et: */