summaryrefslogtreecommitdiff
path: root/prnt/cupsext/cupsext.c
blob: 0f42ddab5bcb33cfcd3a4ad1810a05344367786e (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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
/*
cupsext - Python extension class for CUPS 1.1+

(c) Copyright 2003-2007 Hewlett-Packard Development Company, L.P.

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


Portions based on:
"lpadmin" command for the Common UNIX Printing System (CUPS).

Copyright 1997-2003 by Easy Software Products.

These coded instructions, statements, and computer programs are the
property of Easy Software Products and are protected by Federal
copyright law.  Distribution and use rights are outlined in the file
"LICENSE.txt" which should have been included with this file.  If this
file is missing or damaged please contact Easy Software Products
at:

Attn: CUPS Licensing Information
Easy Software Products
44141 Airport View Drive, Suite 204
Hollywood, Maryland 20636-3111 USA

Voice: (301) 373-9603
EMail: cups-info@cups.org
  WWW: http://www.cups.org

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Hewlett-Packard nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PATENT INFRINGEMENT; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


Requires:
CUPS 1.1+
Python 2.2+

Author:
Don Welch

*/


#include <Python.h>
#include <structmember.h>
#include <cups/cups.h>
#include <cups/language.h>
#include <cups/ppd.h>

/* Ref: PEP 353 (Python 2.5) */
#if PY_VERSION_HEX < 0x02050000
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#endif


int g_num_options = 0;
cups_option_t * g_options;

ppd_file_t * ppd = NULL;
cups_dest_t * dest = NULL;

cups_dest_t * g_dests = NULL;
int g_num_dests = 0;

const char * g_ppd_file = NULL;

/*
 * 'validate_name()' - Make sure the printer name only contains valid chars.
 */

static int                                /* O - 0 if name is no good, 1 if name is good */
validate_name( const char *name )         /* I - Name to check */
{
    return 1; // TODO: Make it work with utf-8 encoding
}

static PyObject * PyObj_from_UTF8(const char *utf8)
{
    PyObject *val = PyUnicode_Decode(utf8, strlen(utf8), "utf-8", NULL);

    if (!val)
    {
        // CUPS 1.2 always gives us UTF-8.  Before CUPS 1.2, the
        // ppd-* strings come straight from the PPD with no
        // transcoding, but the attributes-charset is still 'utf-8'
        // so we've no way of knowing the real encoding.
        // In that case, detect the error and force it to ASCII.
        char * ascii;
        const char * orig = utf8;
        int i;

        PyErr_Clear();
        ascii = malloc(1 + strlen (orig));

        for (i = 0; orig[i]; i++)
        {
            ascii[i] = orig[i] & 0x7f;
        }

        ascii[i] = '\0';
        val = PyString_FromString( ascii );
        free( ascii );
    }

    return val;
}

void debug(const char * text)
{
    char buf[4096];
    sprintf( buf, "print '%s'", text);
    PyRun_SimpleString( buf );

}

staticforward PyTypeObject printer_Type;

#define printerObject_Check(v) ((v)->ob_type == &printer_Type)

typedef struct
{
    PyObject_HEAD
    PyObject * device_uri;
    PyObject * printer_uri;
    PyObject * name;
    PyObject * location;
    PyObject * makemodel;
    PyObject * info;
    int accepting;
    int state;
}
printer_Object;


static void printer_dealloc( printer_Object * self )
{

    Py_XDECREF( self->name );
    Py_XDECREF( self->device_uri );
    Py_XDECREF( self->printer_uri );
    Py_XDECREF( self->location );
    Py_XDECREF( self->makemodel );
    Py_XDECREF( self->info );
    PyObject_DEL( self );
}


static PyMemberDef printer_members[] =
    {
        { "device_uri", T_OBJECT_EX, offsetof( printer_Object, device_uri ), 0, "Device URI (device-uri)" },
        { "printer_uri", T_OBJECT_EX, offsetof( printer_Object, printer_uri ), 0, "Printer URI (printer-uri)" },
        { "name", T_OBJECT_EX, offsetof( printer_Object, name ), 0, "Name (printer-name)" },
        { "location", T_OBJECT_EX, offsetof( printer_Object, location ), 0, "Location (printer-location)" },
        { "makemodel", T_OBJECT_EX, offsetof( printer_Object, makemodel ), 0, "Make and model (printer-make-and-model)" },
        { "state", T_INT, offsetof( printer_Object, state ), 0, "State (printer-state)" },
        { "info", T_OBJECT_EX, offsetof( printer_Object, info ), 0, "Info/description (printer-info)" },
        { "accepting", T_INT, offsetof( printer_Object, accepting ), 0, "Accepting/rejecting" },
        {0}
    };

static PyTypeObject printer_Type =
    {
        PyObject_HEAD_INIT( &PyType_Type )
        0,                                     /* ob_size */
        "cupsext.Printer",                   /* tp_name */
        sizeof( printer_Object ),              /* tp_basicsize */
        0,                                     /* tp_itemsize */
        ( destructor ) printer_dealloc,           /* tp_dealloc */
        0,                                     /* tp_print */
        0,                                     /* tp_getattr */
        0,                                     /* tp_setattr */
        0,                                     /* tp_compare */
        0,                                     /* tp_repr */
        0,                                     /* tp_as_number */
        0,                                     /* tp_as_sequence */
        0,                                     /* tp_as_mapping */
        0,                                     /* tp_hash */
        0,                                     /* tp_call */
        0,                                     /* tp_str */
        PyObject_GenericGetAttr,               /* tp_getattro */
        PyObject_GenericSetAttr,               /* tp_setattro */
        0,                                     /* tp_as_buffer */
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* tp_flags */
        "CUPS Printer object",                 /* tp_doc */
        0,                                     /* tp_traverse */
        0,                                     /* tp_clear */
        0,                                     /* tp_richcompare */
        0,                                     /* tp_weaklistoffset */
        0,                                     /* tp_iter */
        0,                                     /* tp_iternext */
        0,         /*job_methods, */           /* tp_methods */
        printer_members,                       /* tp_members */
        0,                                     /* tp_getset */
        0,                                     /* tp_base */
        0,                                     /* tp_dict */
        0,                                     /* tp_descr_get */
        0,                                     /* tp_descr_set */
        0,                                     /* tp_dictoffset */
        0,                                     /* tp_init */
        0,                                     /* tp_alloc */
        0,                                     /* tp_new */
    };




static PyObject * _newPrinter( char * device_uri,
                               char * name,
                               char * printer_uri,
                               char * location,
                               char * makemodel,
                               char * info,
                               int state,
                               int accepting )
{
    printer_Object * self = PyObject_New( printer_Object, &printer_Type );

    if ( !self )
        return NULL;

    if ( device_uri != NULL )
        self->device_uri = Py_BuildValue( "s", device_uri );

    if ( printer_uri != NULL )
        self->printer_uri = Py_BuildValue( "s", printer_uri );

    if ( name != NULL )
        self->name = Py_BuildValue( "s", name );

    if ( location != NULL )
        self->location = Py_BuildValue( "s", location );

    if ( makemodel != NULL )
        self->makemodel = Py_BuildValue( "s", makemodel );

    if ( info != NULL )
        self->info = Py_BuildValue( "s", info );

    self->accepting = accepting;
    self->state = state;

    return ( PyObject * ) self;
}

static PyObject * newPrinter( PyObject * self, PyObject * args, PyObject * kwargs )
{
    char * device_uri = "";
    char * name = "";
    char * location = "";
    char * makemodel = "";
    int state = 0;
    char * printer_uri = "";
    char * info = "";
    int accepting = 0;

    char * kwds[] = { "device_uri", "name", "printer_uri", "location",
                      "makemodel", "info", "state", "accepting", NULL };

    if ( !PyArg_ParseTupleAndKeywords( args, kwargs, "zz|zzzzii", kwds,
                                       &device_uri, &name, &printer_uri,
                                       &location, &makemodel, &info, &state,
                                       &accepting )        )
        return NULL;

    return _newPrinter( device_uri, printer_uri, name, location, makemodel, info, state, accepting);
}



PyObject * getPrinters( PyObject * self, PyObject * args )
{
    http_t * http = NULL;     /* HTTP object */
    ipp_t *request = NULL;  /* IPP request object */
    ipp_t *response = NULL; /* IPP response object */
    ipp_attribute_t *attr;     /* Current IPP attribute */
    PyObject * printer_list;
    cups_lang_t * language;

    static const char * attrs[] =         /* Requested attributes */
    {
        "printer-info",
        "printer-location",
        "printer-make-and-model",
        "printer-state",
        "printer-name",
        "device-uri",
        "printer-uri-supported",
        "printer-is-accepting-jobs",
    };

    /* Connect to the HTTP server */
    if ( ( http = httpConnectEncrypt( cupsServer(), ippPort(), cupsEncryption() ) ) == NULL )
    {
        goto abort;
    }

    /* Assemble the IPP request */
    request = ippNew();
    language = cupsLangDefault();

    request->request.op.operation_id = CUPS_GET_PRINTERS;
    request->request.any.request_id = 1;

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
                  "attributes-charset", NULL, cupsLangEncoding( language ) );

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                  "attributes-natural-language", NULL, language->language );

    ippAddStrings( request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
                   "requested-attributes", sizeof( attrs ) / sizeof( attrs[ 0 ] ),
                   NULL, attrs );

    /* Send the request and get a response. */
    if ( ( response = cupsDoRequest( http, request, "/" ) ) == NULL )
    {
        goto abort;
    }

    Py_ssize_t max_count = 0;

    for ( attr = ippFindAttribute( response, "printer-name", IPP_TAG_NAME ),
            max_count = 0;
            attr != NULL;
            attr = ippFindNextAttribute( response, "printer-name", IPP_TAG_NAME ),
            max_count++ )
        ;

    if ( max_count > 0 )
    {

        //printer_list = PyList_New( max_count );
        printer_list = PyList_New( 0 );

        char * device_uri = "";
        char * printer_uri = "";
        char * info = "";
        char * location = "";
        char * make_model = "";
        char * name = "";
        int accepting = 0;
        cups_ptype_t type;
        ipp_pstate_t state;
        int i = 0;

        for ( attr = response->attrs; attr != NULL; attr = attr->next )
        {
            while ( attr != NULL && attr->group_tag != IPP_TAG_PRINTER )
                attr = attr->next;

            if ( attr == NULL )
                break;

            type = CUPS_PRINTER_REMOTE;
            state = IPP_PRINTER_IDLE;
            accepting = 0;

            while ( attr != NULL && attr->group_tag == IPP_TAG_PRINTER )
            {
                if ( strcmp( attr->name, "printer-name" ) == 0 &&
                        attr->value_tag == IPP_TAG_NAME )
                    name = attr->values[ 0 ].string.text;

                else if ( strcmp( attr->name, "device-uri" ) == 0 &&
                        attr->value_tag == IPP_TAG_URI )
                    device_uri = attr->values[ 0 ].string.text;

                else if ( strcmp( attr->name, "printer-uri-supported" ) == 0 &&
                        attr->value_tag == IPP_TAG_URI )
                    printer_uri = attr->values[ 0 ].string.text;

                else if ( strcmp( attr->name, "printer-info" ) == 0 &&
                        attr->value_tag == IPP_TAG_TEXT )
                    info = attr->values[ 0 ].string.text;

                else if ( strcmp( attr->name, "printer-location" ) == 0 &&
                        attr->value_tag == IPP_TAG_TEXT )
                    location = attr->values[ 0 ].string.text;

                else if ( strcmp( attr->name, "printer-make-and-model" ) == 0 &&
                        attr->value_tag == IPP_TAG_TEXT )
                    make_model = attr->values[ 0 ].string.text;

                else if ( strcmp( attr->name, "printer-state" ) == 0 &&
                        attr->value_tag == IPP_TAG_ENUM )
                    state = ( ipp_pstate_t ) attr->values[ 0 ].integer;

                else if (!strcmp(attr->name, "printer-is-accepting-jobs") &&
                        attr->value_tag == IPP_TAG_BOOLEAN)
                    accepting = attr->values[ 0 ].boolean;

                attr = attr->next;
            }

            if ( device_uri == NULL )
            {
                if ( attr == NULL )
                    break;
                else
                    continue;
            }

            printer_Object * printer;
            printer = ( printer_Object * ) _newPrinter( device_uri, name, printer_uri, location, make_model,
                    info, state, accepting );

            //PyList_SetItem( printer_list, i, ( PyObject * ) printer );
            PyList_Append( printer_list, ( PyObject * ) printer );

            i++;

            if ( attr == NULL )
                break;
        }

        return printer_list;
    }
abort:
    if ( response != NULL )
        ippDelete( response );

    if ( http != NULL )
        httpClose( http );

    printer_list = PyList_New( ( Py_ssize_t ) 0 );
    return printer_list;
}


PyObject * addPrinter( PyObject * self, PyObject * args )
{
    //char buf[1024];
    ipp_status_t status;
    http_t *http = NULL;     /* HTTP object */
    ipp_t *request = NULL;  /* IPP request object */
    ipp_t *response = NULL; /* IPP response object */
    cups_lang_t * language;
    int r;
    char printer_uri[ HTTP_MAX_URI ];
    char * name, * device_uri, *location, *ppd_file, * info, * model;
    const char * status_str = "successful-ok";

    if ( !PyArg_ParseTuple( args, "zzzzzz",
                            &name,             // name of printer
                            &device_uri,       // DeviceURI (e.g., hp:/usb/PSC_2200_Series?serial=0000000010)
                            &location,         // location of printer
                            &ppd_file,         // path to PPD file (uncompressed, must exist)
                            &model,            // model name (e.g., foomatic:...)
                            &info              // info/description
                          ) )
    {
        r = 0;
        status_str = "Invalid arguments";
        goto abort;
    }

    if ( ( strlen( ppd_file ) > 0 && strlen( model ) > 0 ) ||
         ( strlen( ppd_file ) == 0 && strlen( model ) == 0) )
    {
        r = 0;
        status_str = "Invalid arguments: specify only ppd_file or model, not both or neither";
        goto abort;
    }

    if ( !validate_name( name ) )
    {
        r = 0;
        status_str = "Invalid printer name";
        goto abort;
    }


    sprintf( printer_uri, "ipp://localhost/printers/%s", name );

    if ( info == NULL )
        strcpy( info, name );

    /* Connect to the HTTP server */
    if ( ( http = httpConnectEncrypt( cupsServer(), ippPort(), cupsEncryption() ) ) == NULL )
    {
        r = 0;
        status_str = "Unable to connect to CUPS server";
        goto abort;
    }

    /* Assemble the IPP request */
    request = ippNew();
    language = cupsLangDefault();

    request->request.op.operation_id = CUPS_ADD_PRINTER;
    request->request.any.request_id = 1;

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
                  "attributes-charset", NULL, cupsLangEncoding( language ) );

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                  "attributes-natural-language", NULL, language->language );

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_URI,
                  "printer-uri", NULL, printer_uri );

    ippAddInteger( request, IPP_TAG_PRINTER, IPP_TAG_ENUM,
                   "printer-state", IPP_PRINTER_IDLE );

    ippAddBoolean( request, IPP_TAG_PRINTER, "printer-is-accepting-jobs", 1 );

    ippAddString( request, IPP_TAG_PRINTER, IPP_TAG_URI, "device-uri", NULL,
                  device_uri );

    ippAddString( request, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-info", NULL,
                  info );

    ippAddString( request, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-location", NULL,
                  location );

    if ( strlen( model ) > 0 )
    {
        ippAddString( request, IPP_TAG_PRINTER, IPP_TAG_NAME, "ppd-name", NULL, model );

        /* Send the request and get a response. */
        response = cupsDoRequest( http, request, "/admin/" );
    }
    else
    {
        /* Send the request and get a response. */
        response = cupsDoFileRequest( http, request, "/admin/", ppd_file );
    }

    if ( response == NULL )
    {
        status = cupsLastError();
        r = 0;
    }
    else
    {
        status = response->request.status.status_code;
        //ippDelete( response );
        r = 1;
    }

    status_str = ippErrorString( status );

abort:

    if ( http != NULL )
        httpClose( http );

    if ( response != NULL )
        ippDelete( response );

    return Py_BuildValue( "is", r, status_str );

}

/*
 * 'delPrinter()' - Delete a printer from the system...
 */
PyObject * delPrinter( PyObject * self, PyObject * args )
{
    ipp_t * request = NULL,                        /* IPP Request */
                      *response = NULL;                /* IPP Response */
    cups_lang_t *language;                /* Default language */
    char uri[ HTTP_MAX_URI ];        /* URI for printer/class */
    char * name;
    http_t *http = NULL;     /* HTTP object */
    int r = 0;
    const char *username = NULL;

    username = cupsUser();

    if ( !PyArg_ParseTuple( args, "z",
                            &name ) )         // name of printer
    {
        goto abort;
    }

    if ( !validate_name( name ) )
    {
        goto abort;
    }

    /* Connect to the HTTP server */
    if ( ( http = httpConnectEncrypt( cupsServer(), ippPort(), cupsEncryption() ) ) == NULL )
    {
        goto abort;
    }
    snprintf( uri, sizeof( uri ), "ipp://localhost/printers/%s", name );

    /*
        * Build a CUPS_DELETE_PRINTER request, which requires the following
        * attributes:
        *
        *    attributes-charset
        *    attributes-natural-language
        *    printer-uri
       */
    request = ippNew();

    request->request.op.operation_id = CUPS_DELETE_PRINTER;
    request->request.op.request_id = 1;

    language = cupsLangDefault();

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
                  "attributes-charset", NULL, cupsLangEncoding( language ) );

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                  "attributes-natural-language", NULL, language->language );

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_URI,
                  "printer-uri", NULL, uri );

    /*
     * Do the request and get back a response...
     */
    response = cupsDoRequest( http, request, "/admin/" );

    if ( ( response != NULL ) && ( response->request.status.status_code <= IPP_OK_CONFLICT ) )
    {
        r = 1;
    }

abort:
    if (username)
        cupsSetUser(username);

    if ( http != NULL )
        httpClose( http );

    if ( response != NULL )
        ippDelete( response );

    return Py_BuildValue( "i", r );

}

/*
 * 'setDefaultPrinter()' - Set the default printing destination.
 */

PyObject * setDefaultPrinter( PyObject * self, PyObject * args )

{
    char uri[ HTTP_MAX_URI ];        /* URI for printer/class */
    ipp_t *request = NULL,                        /* IPP Request */
          *response = NULL;                /* IPP Response */
    cups_lang_t *language;                /* Default language */
    char * name;
    http_t *http = NULL;     /* HTTP object */
    int r = 0;
    const char *username = NULL;

    username = cupsUser();

    if ( !PyArg_ParseTuple( args, "z",
                            &name ) )         // name of printer
    {
        goto abort;
    }

    //char buf[1024];
    //sprintf( buf, "print '%s'", name);
    //PyRun_SimpleString( buf );

    if ( !validate_name( name ) )
    {
        goto abort;
    }

    /* Connect to the HTTP server */
    if ( ( http = httpConnectEncrypt( cupsServer(), ippPort(), cupsEncryption() ) ) == NULL )
    {
        goto abort;
    }

    /*
      * Build a CUPS_SET_DEFAULT request, which requires the following
      * attributes:
      *
      *    attributes-charset
      *    attributes-natural-language
      *    printer-uri
      */

    snprintf( uri, sizeof( uri ), "ipp://localhost/printers/%s", name );

    request = ippNew();

    request->request.op.operation_id = CUPS_SET_DEFAULT;
    request->request.op.request_id = 1;

    language = cupsLangDefault();

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
                  "attributes-charset", NULL, "utf-8" ); //cupsLangEncoding( language ) );

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                  "attributes-natural-language",
                  //NULL, language != NULL ? language->language : "en");
                  NULL, language->language );

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_URI,
                  "printer-uri", NULL, uri );

    /*
     * Do the request and get back a response...
     */

    response = cupsDoRequest( http, request, "/admin/" );

    if ( ( response != NULL ) && ( response->request.status.status_code <= IPP_OK_CONFLICT ) )
    {
        r = 1;
    }

abort:
    if (username)
        cupsSetUser(username);

    if ( http != NULL )
        httpClose( http );

    if ( response != NULL )
        ippDelete( response );

    return Py_BuildValue( "i", r );


}



PyObject * controlPrinter( PyObject * self, PyObject * args )
{
    ipp_t *request = NULL,                 /* IPP Request */
          *response = NULL;                /* IPP Response */
    char * name;
    http_t *http = NULL;     /* HTTP object */
    int op;
    int r = 0;
    char uri[ HTTP_MAX_URI ];        /* URI for printer/class */
    cups_lang_t *language;
    const char *username = NULL;

    username = cupsUser();

    if ( !PyArg_ParseTuple( args, "zi", &name, &op) )
    {
        goto abort;
    }

    if ( !validate_name( name ) )
    {
        goto abort;
    }

    /* Connect to the HTTP server */
    if ( ( http = httpConnectEncrypt( cupsServer(), ippPort(), cupsEncryption() ) ) == NULL )
    {
        goto abort;
    }

    request = ippNew();

    request->request.op.operation_id = op;
    request->request.op.request_id = 1;

    language = cupsLangDefault();

    snprintf( uri, sizeof( uri ), "ipp://localhost/printers/%s", name );

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
                  "attributes-charset", NULL, cupsLangEncoding( language ) );

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                  "attributes-natural-language", NULL, language->language );

    ippAddString( request, IPP_TAG_OPERATION, IPP_TAG_URI,
                  "printer-uri", NULL, uri );


    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                "requesting-user-name", NULL, cupsUser());

    if (op == IPP_PURGE_JOBS)
        ippAddBoolean(request, IPP_TAG_OPERATION, "purge-jobs", 1);

    response = cupsDoRequest(http, request, "/admin/");

    if (( response != NULL ) && (response->request.status.status_code <= IPP_OK_CONFLICT))
    {
        r = 1;
    }

abort:
    if (username)
        cupsSetUser(username);

    if ( http != NULL )
        httpClose( http );

    if ( response != NULL )
        ippDelete( response );

    return Py_BuildValue( "i", r );;
}



staticforward PyTypeObject job_Type;

typedef struct
{
    PyObject_HEAD
    int id;
    PyObject * dest;
    PyObject * title;
    PyObject * user;
    int state;
    int size;
}
job_Object;



static void job_dealloc( job_Object * self )
{

    Py_XDECREF( self->dest );
    Py_XDECREF( self->title );
    Py_XDECREF( self->user );
    PyObject_DEL( self );
}

static PyMemberDef job_members[] =
    {
        { "id", T_INT, offsetof( job_Object, id ), 0, "Id" },
        { "dest", T_OBJECT_EX, offsetof( job_Object, dest ), 0, "Destination" },
        { "state", T_INT, offsetof( job_Object, state ), 0, "State" },
        { "title", T_OBJECT_EX, offsetof( job_Object, title ), 0, "Title" },
        { "user", T_OBJECT_EX, offsetof( job_Object, user ), 0, "User" },
        { "size", T_INT, offsetof( job_Object, size ), 0, "Size" },
        {0}
    };



static PyTypeObject job_Type =
    {
        PyObject_HEAD_INIT( &PyType_Type )
        0,                                     /* ob_size */
        "Job",                                 /* tp_name */
        sizeof( job_Object ),                  /* tp_basicsize */
        0,                                     /* tp_itemsize */
        ( destructor ) job_dealloc,               /* tp_dealloc */
        0,                                     /* tp_print */
        0,                                     /* tp_getattr */
        0,                                     /* tp_setattr */
        0,                                     /* tp_compare */
        0,                                     /* tp_repr */
        0,                                     /* tp_as_number */
        0,                                     /* tp_as_sequence */
        0,                                     /* tp_as_mapping */
        0,                                     /* tp_hash */
        0,                                     /* tp_call */
        0,                                     /* tp_str */
        PyObject_GenericGetAttr,               /* tp_getattro */
        PyObject_GenericSetAttr,               /* tp_setattro */
        0,                                     /* tp_as_buffer */
        Py_TPFLAGS_DEFAULT,                    /* tp_flags */
        "CUPS Job object",                     /* tp_doc */
        0,                                     /* tp_traverse */
        0,                                     /* tp_clear */
        0,                                     /* tp_richcompare */
        0,                                     /* tp_weaklistoffset */
        0,                                     /* tp_iter */
        0,                                     /* tp_iternext */
        0,         /*job_methods, */                  /* tp_methods */
        job_members,                           /* tp_members */
        0,                                     /* tp_getset */
        0,                                     /* tp_base */
        0,                                     /* tp_dict */
        0,                                     /* tp_descr_get */
        0,                                     /* tp_descr_set */
        0,                                     /* tp_dictoffset */
        0,                                     /* tp_init */
        0,        //(initproc)job_init,            /* tp_init */
        0,                                     /* tp_alloc */
        //PyType_GenericAlloc,
        0,         //job_new,                       /* tp_new */
        //PyType_GenericNew,
    };


static /*job_Object **/ PyObject * _newJob( int id, int state, char * dest, char * title, char * user, int size )
{
    job_Object * jo;
    jo = PyObject_New( job_Object, &job_Type );
    if ( jo == NULL )
        return NULL;
    jo->id = id;
    jo->size = size;
    jo->state = state;
    if ( dest != NULL )
        jo->dest = PyObj_from_UTF8( dest );
    else
        jo->dest = Py_BuildValue( "" );

    if ( title != NULL )
        jo->title = PyObj_from_UTF8( title );
    else
        jo->title = Py_BuildValue( "" );

    if ( user != NULL )
        jo->user = PyObj_from_UTF8( user );
    else
        jo->user = Py_BuildValue( "" );

    return ( PyObject * ) jo;

}

static /*job_Object **/ PyObject * newJob( PyObject * self, PyObject * args, PyObject * kwargs )
{
    char * dest = "";
    int id = 0;
    int state = 0;
    char * title = "";
    char * user = "";
    int size = 0;

    char * kwds[] = { "id", "state", "dest", "title", "user", "size", NULL };

    if ( !PyArg_ParseTupleAndKeywords( args, kwargs, "i|izzzi", kwds,
                                       &id, &state, &dest, &title, &user, &size ) )
        return NULL;

    return _newJob( id, state, dest, title, user, size );

}




PyObject * getDefaultPrinter( PyObject * self, PyObject * args )
{
    const char * defdest;
    defdest = cupsGetDefault();

    /*char buf[1024];
    sprintf( buf, "print 'Default Printer: %s'", defdest);
    PyRun_SimpleString( buf );
    */

    if ( defdest == NULL )
        return Py_BuildValue( "" ); // None
    else
        return Py_BuildValue( "s", defdest );

}


PyObject * cancelJob( PyObject * self, PyObject * args )         // cancelJob( dest, jobid )
{
    int status;
    int jobid;
    char * dest;

    if ( !PyArg_ParseTuple( args, "si", &dest, &jobid ) )
    {
        return Py_BuildValue( "i", 0 );
    }

    status = cupsCancelJob( dest, jobid );

    return Py_BuildValue( "i", status );
}

PyObject * getJobs( PyObject * self, PyObject * args )
{
    cups_job_t * jobs;
    Py_ssize_t i;
    int num_jobs;
    PyObject * job_list;
    int my_job;
    int completed;

    if ( !PyArg_ParseTuple( args, "ii", &my_job, &completed ) )
    {
        return PyList_New( ( Py_ssize_t ) 0 );
    }

    num_jobs = cupsGetJobs( &jobs, NULL, my_job, completed );

    if ( num_jobs > 0 )
    {
        job_list = PyList_New( num_jobs );

        for ( i = 0; i < num_jobs; i++ )
        {
            job_Object * newjob;
            newjob = ( job_Object * ) _newJob( jobs[ i ].id,
                                               jobs[ i ].state,
                                               jobs[ i ].dest,
                                               jobs[ i ].title,
                                               jobs[ i ].user,
                                               jobs[ i ].size );

            PyList_SetItem( job_list, i, ( PyObject * ) newjob );

        }
        cupsFreeJobs( num_jobs, jobs );
    }
    else
    {
        job_list = PyList_New( ( Py_ssize_t ) 0 );
    }
    return job_list;
}

PyObject * getVersion( PyObject * self, PyObject * args )
{
    return Py_BuildValue( "f", CUPS_VERSION );
}

PyObject * getVersionTuple( PyObject * self, PyObject * args )
{
    return Py_BuildValue( "(iii)", CUPS_VERSION_MAJOR, CUPS_VERSION_MINOR, CUPS_VERSION_PATCH );
}

PyObject * getServer( PyObject * self, PyObject * args )
{
    return Py_BuildValue( "s", cupsServer() );
}

PyObject * setServer( PyObject * self, PyObject * args )
{
    char * server = NULL;

    if (!PyArg_ParseTuple(args, "z", &server))
        return Py_BuildValue( "" );

    if (!strlen(server)) // Pass an empty string to restore default server
        server = NULL;

    cupsSetServer(server);

    return Py_BuildValue( "" );
}


// ***************************************************************************************************

PyObject * getPPDList( PyObject * self, PyObject * args )
{

/*
    * Build a CUPS_GET_PPDS request, which requires the following
    * attributes:
    *
    *    attributes-charset
    *    attributes-natural-language
    *    printer-uri
    */

    ipp_t *request = NULL,                 /* IPP Request */
          *response = NULL;                /* IPP Response */
    PyObject * result;
    cups_lang_t *language;
    ipp_attribute_t * attr;
    //PyObject * ppd_list;
    http_t *http = NULL;     /* HTTP object */
    //char buf[1024];

    result = PyDict_New ();

    if ( ( http = httpConnectEncrypt( cupsServer(), ippPort(), cupsEncryption() ) ) == NULL )
    {
        goto abort;
    }

    request = ippNew();

    request->request.op.operation_id = CUPS_GET_PPDS;
    request->request.op.request_id   = 1;

    language = cupsLangDefault();

    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
             "attributes-charset", NULL, cupsLangEncoding(language));

    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
             "attributes-natural-language", NULL, language->language);

    //ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
    //             NULL, "ipp://localhost/printers/");

    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
                 NULL, "ipp://localhost/printers/officejet_4100");

    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "requested-attributes",
                 NULL, "all");

    /*
    * Do the request and get back a response...
    */

    if ((response = cupsDoRequest(http, request, "/")) != NULL)
    {

        for (attr = response->attrs; attr; attr = attr->next)
        {
            PyObject *dict;
            char *ppdname = NULL;

            while (attr && attr->group_tag != IPP_TAG_PRINTER)
                attr = attr->next;

            if (!attr)
                break;

            dict = PyDict_New ();

            for (; attr && attr->group_tag == IPP_TAG_PRINTER; attr = attr->next)
            {
                PyObject *val = NULL;

                if (!strcmp (attr->name, "ppd-name") && attr->value_tag == IPP_TAG_NAME)
                {
                    ppdname = attr->values[0].string.text;

                    //sprintf( buf, "print '%s'", ppdname);
                    //PyRun_SimpleString( buf );
                }

                else if (attr->value_tag == IPP_TAG_TEXT || attr->value_tag == IPP_TAG_NAME || attr->value_tag == IPP_TAG_KEYWORD)
                //else if ((!strcmp (attr->name, "ppd-natural-language") && attr->value_tag == IPP_TAG_LANGUAGE) ||
                //    (!strcmp (attr->name, "ppd-make-and-model") && attr->value_tag == IPP_TAG_TEXT) ||
                //    (!strcmp (attr->name, "ppd-make") && attr->value_tag == IPP_TAG_TEXT) ||
                //    (!strcmp (attr->name, "ppd-device-id") && attr->value_tag == IPP_TAG_TEXT))
                {
                    val = PyObj_from_UTF8(attr->values[0].string.text);
                }

                if (val)
                {
                    PyDict_SetItemString (dict, attr->name, val);
                    Py_DECREF (val);
                }
            }

            if (ppdname)
            {
                PyDict_SetItemString (result, ppdname, dict);
            }
            else
            {
                Py_DECREF (dict);
            }

            if (!attr)
                break;
        }

        //return result;
    }

abort:
    if ( http != NULL )
        httpClose( http );

    if ( response != NULL )
        ippDelete( response );

    return result;
}


PyObject * openPPD( PyObject * self, PyObject * args )
{
    char * printer;
    FILE * file;
    int j;

    if ( !PyArg_ParseTuple( args, "z", &printer ) )
    {
        return Py_BuildValue( "" ); // None
    }

    if ( ( g_ppd_file = cupsGetPPD( ( const char * ) printer ) ) == NULL )
    {
        goto bailout;
    }

    if ( ( file = fopen( g_ppd_file, "r" )) == NULL )
    {
      unlink(g_ppd_file);
      g_ppd_file = NULL;
      goto bailout;
    }

    ppd = ppdOpen( file );
    ppdLocalize( ppd );
    fclose( file );

    g_num_dests = cupsGetDests( &g_dests );

    if ( g_num_dests == 0 )
    {
        goto bailout;
    }

    if ( ( dest = cupsGetDest( printer, NULL, g_num_dests, g_dests ) ) == NULL )
    {
        goto bailout;
    }

    ppdMarkDefaults( ppd );
    cupsMarkOptions( ppd, dest->num_options, dest->options );

    for ( j = 0; j < dest->num_options; j++ )
    {
        if ( cupsGetOption( dest->options[ j ].name, g_num_options, g_options ) == NULL )
        {
            g_num_options = cupsAddOption( dest->options[ j ].name, dest->options[ j ].value, g_num_options, &g_options );
        }
    }

bailout:
    return Py_BuildValue( "s", g_ppd_file );
}


PyObject * closePPD( PyObject * self, PyObject * args )
{
    if ( ppd != NULL )
    {
        ppdClose( ppd );
        unlink( g_ppd_file );
    }

    ppd = NULL;

    return Py_BuildValue( "" ); // None
}


PyObject * getPPD( PyObject * self, PyObject * args )
{
    char * printer;

    if ( !PyArg_ParseTuple( args, "z", &printer ) )
    {
        return Py_BuildValue( "" ); // None
    }

    const char * ppd_file;
    ppd_file = cupsGetPPD( ( const char * ) printer );

    return Py_BuildValue( "s", ppd_file );

}


PyObject * getPPDOption( PyObject * self, PyObject * args )
{
    if ( ppd != NULL )
    {
        char * option;

        if ( !PyArg_ParseTuple( args, "z", &option ) )
        {
            return Py_BuildValue( "" ); // None
        }

        ppd_choice_t * marked_choice;
        marked_choice = ppdFindMarkedChoice( ppd, option );

        if ( marked_choice == NULL )
        {
            return Py_BuildValue( "" ); // None
        }
        else
        {
            return Py_BuildValue( "s", marked_choice->text );
        }
    }
    else
    {
        return Py_BuildValue( "" ); // None
    }
}

PyObject * getPPDPageSize( PyObject * self, PyObject * args )
{
    //char buf[1024];

    if ( ppd != NULL )
    {
        ppd_size_t * size = NULL;
        float width = 0.0;
        float length = 0.0;
        ppd_choice_t * page_size = NULL;

        page_size = ppdFindMarkedChoice( ppd, "PageSize" );

        //sprintf( buf, "print '%s'", page_size->text );
        //PyRun_SimpleString( buf );

        if ( page_size == NULL )
            goto bailout;

        size = ppdPageSize( ppd, page_size->text );

        if ( size == NULL )
            goto bailout;

        //sprintf( buf, "print '%s'", size->name );
        //PyRun_SimpleString( buf );

        width = ppdPageWidth( ppd, page_size->text );
        length = ppdPageLength( ppd, page_size->text );

        return Py_BuildValue( "(sffffff)", page_size->text, width, length, size->left,
            size->bottom, size->right, size->top );
    }

bailout:
    return Py_BuildValue( "(sffffff)", "", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 );
}

// ***************************************************************************************************



PyObject * resetOptions( PyObject * self, PyObject * args )
{
    if ( g_num_options > 0 )
        cupsFreeOptions( g_num_options, g_options );
    g_num_options = 0;
    g_options = ( cups_option_t * ) 0;

    return Py_BuildValue( "" );

}

PyObject * addOption( PyObject * self, PyObject * args )
{
    char * option;

    if ( !PyArg_ParseTuple( args, "z", &option ) )
    {
        return Py_BuildValue( "i", 0 );
    }

    g_num_options = cupsParseOptions( option, g_num_options, &g_options );

    return Py_BuildValue( "i", g_num_options ); // >0
}

PyObject * removeOption( PyObject * self, PyObject * args )
{
    char * option;
    int j;
    int r = 0;

    if ( !PyArg_ParseTuple( args, "z", &option ) )
    {
        return Py_BuildValue( "i", 0 );
    }

    for (j = 0; j < g_num_options; j++)
    {
        if ( !strcasecmp(g_options[j].name, option) )
        {
            g_num_options--;

            if ( j < g_num_options )
            {
                memcpy( (g_options + j), (g_options + j + 1),
                    sizeof(cups_option_t) * (g_num_options - j) );

                r = 1;
            }
        }
    }

    return Py_BuildValue( "i", r );
}


PyObject * getOptions( PyObject * self, PyObject * args )
{
    PyObject * option_list;
    int j;

    option_list = PyList_New( ( Py_ssize_t ) 0 );
    for ( j = 0; j < g_num_options; j++ )
    {
        PyList_Append( option_list, Py_BuildValue( "(ss)", g_options[ j ].name, g_options[ j ].value ) );
    }

    return option_list;
}


// ***************************************************************************************************



PyObject * getGroupList( PyObject * self, PyObject * args )
{
    PyObject * group_list;
    ppd_group_t *group;
    int i;

/*  debug("at 0"); */

    if ( ppd != NULL && dest != NULL )
    {
/*      debug("at 1"); */

        group_list = PyList_New( ( Py_ssize_t ) 0 );
        for ( i = ppd->num_groups, group = ppd->groups; i > 0; i--, group++ )
        {
/*          debug(group->name); */
            PyList_Append( group_list, PyObj_from_UTF8( group->name ) );
        }

        return group_list;
    }

    return PyList_New( ( Py_ssize_t ) 0 );
}


PyObject * getGroup( PyObject * self, PyObject * args )
{
    const char *the_group;
    ppd_group_t *group;
    int i;

    if ( !PyArg_ParseTuple( args, "z", &the_group ) )
    {
        goto bailout;
    }

    if ( ppd != NULL && dest != NULL )
    {
        for ( i = ppd->num_groups, group = ppd->groups; i > 0; i--, group++ )
        {
            if ( strcasecmp( group->name, the_group ) == 0 )
            {
                return Py_BuildValue( "(si)", group->text, group->num_subgroups);
            }
        }
    }

bailout:
    return Py_BuildValue( "" );
}



PyObject * getOptionList( PyObject * self, PyObject * args )
{
    PyObject * option_list;
    const char *the_group;
    ppd_group_t *group;
    int i, j;
    ppd_option_t *option;

    if ( !PyArg_ParseTuple( args, "z", &the_group ) )
    {
        goto bailout;
    }

    if ( ppd != NULL && dest != NULL )
    {
        option_list = PyList_New( ( Py_ssize_t ) 0 );

        for ( i = ppd->num_groups, group = ppd->groups; i > 0; i--, group++ )
        {
            if ( strcasecmp( group->name, the_group ) == 0 )
            {
                for ( j = group->num_options, option = group->options; j > 0; j--, option++ )
                {
                    PyList_Append( option_list, PyObj_from_UTF8( option->keyword ) );
                }

                break;
            }
        }

        return option_list;
    }



bailout:
    return PyList_New( ( Py_ssize_t ) 0 );
}




PyObject * getOption( PyObject * self, PyObject * args )
{
    const char *the_group;
    const char *the_option;
    ppd_group_t *group;
    int i, j;
    ppd_option_t *option;


    if ( !PyArg_ParseTuple( args, "zz", &the_group, &the_option ) )
    {
        goto bailout;
    }

    if ( ppd != NULL && dest != NULL )
    {

        for ( i = ppd->num_groups, group = ppd->groups; i > 0; i--, group++ )
        {
            if ( strcasecmp( group->name, the_group ) == 0 )
            {
                for ( j = group->num_options, option = group->options; j > 0; j--, option++ )
                {
                    if ( strcasecmp( option->keyword, the_option ) == 0 )
                    {
                        return Py_BuildValue( "(ssbi)", option->text, option->defchoice,
                                              option->conflicted > 0 ? 1 : 0, option->ui );
                    }
                }
            }
        }
    }

bailout:
    return Py_BuildValue( "" );
}


PyObject * getChoiceList( PyObject * self, PyObject * args )
{
    PyObject * choice_list;
    const char *the_group;
    const char *the_option;
    ppd_group_t *group;
    int i, j, k;
    ppd_option_t *option;
    ppd_choice_t *choice;

    if ( !PyArg_ParseTuple( args, "zz", &the_group, &the_option ) )
    {
        goto bailout;
    }

    if ( ppd != NULL && dest != NULL )
    {
        choice_list = PyList_New( ( Py_ssize_t ) 0 );

        for ( i = ppd->num_groups, group = ppd->groups; i > 0; i--, group++ )
        {
            if ( strcasecmp( group->name, the_group ) == 0 )
            {
                for ( j = group->num_options, option = group->options; j > 0; j--, option++ )
                {
                    if ( strcasecmp( option->keyword, the_option ) == 0 )
                    {
                        for ( k = option->num_choices, choice = option->choices; k > 0; k--, choice++ )
                        {
                            PyList_Append( choice_list, PyObj_from_UTF8( choice->choice ) );
                        }

                        break;
                    }
                }
                break;
            }
        }

        return choice_list;
    }


bailout:
    return PyList_New( ( Py_ssize_t ) 0 );
}



PyObject * getChoice( PyObject * self, PyObject * args )
{
    const char * the_group;
    const char *the_option;
    const char *the_choice;
    ppd_group_t *group;
    int i, j, k;
    ppd_option_t *option;
    ppd_choice_t *choice;


    if ( !PyArg_ParseTuple( args, "zzz", &the_group, &the_option, &the_choice ) )
    {
        goto bailout;
    }

    if ( ppd != NULL && dest != NULL )
    {
        for ( i = ppd->num_groups, group = ppd->groups; i > 0; i--, group++ )
        {
            if ( strcasecmp( group->name, the_group ) == 0 )
            {
                for ( j = group->num_options, option = group->options; j > 0; j--, option++ )
                {
                    if ( strcasecmp( option->keyword, the_option ) == 0 )
                    {
                        for ( k = option->num_choices, choice = option->choices; k > 0; k--, choice++ )
                        {
                            if ( strcasecmp( choice->choice, the_choice ) == 0 )
                            {
                                return Py_BuildValue( "(sb)", choice->text, choice->marked > 0 ? 1 : 0 );
                            }
                        }
                    }
                }
            }
        }
    }


bailout:
    return Py_BuildValue( "" );



}

PyObject * setOptions( PyObject * self, PyObject * args )
{
    if ( ppd != NULL && dest != NULL )
    {
        cupsFreeOptions( dest->num_options, dest->options );
        dest->num_options = g_num_options;
        dest->options = g_options;
        cupsSetDests( g_num_dests, g_dests );
        cupsMarkOptions( ppd, dest->num_options, dest->options );
    }

    return Py_BuildValue( "" );
}

// ***************************************************************************************************

PyObject * printFileWithOptions( PyObject * self, PyObject * args )
{
    char * printer;
    char * filename;
    char * title;
    int job_id = -1;
    cups_dest_t * dests = NULL;
    cups_dest_t * dest = NULL;
    int num_dests = 0;
    int i = 0;

    if ( !PyArg_ParseTuple( args, "zzz", &printer, &filename, &title ) )
    {
        return Py_BuildValue( "" ); // None
    }

    num_dests = cupsGetDests(&dests);
    dest = cupsGetDest( printer, NULL, num_dests, dests );

    if ( dest != NULL )
    {
        for( i = 0; i < dest->num_options; i++ )
        {
            if ( cupsGetOption( dest->options[i].name, g_num_options, g_options ) == NULL )
                g_num_options = cupsAddOption( dest->options[i].name, dest->options[i].value, g_num_options, &g_options );

        }

        job_id = cupsPrintFile( dest->name, filename, title, g_num_options, g_options );

        return Py_BuildValue( "i", job_id );
    }

    return Py_BuildValue( "i", -1 );
}

// ***************************************************************************************************

static PyObject * passwordFunc = NULL;
static char *passwordPrompt = NULL;

const char * password_callback(const char * prompt)
{

    PyObject *result = NULL;
    PyObject *usernameObj = NULL;
    PyObject *passwordObj = NULL;
    char *username = NULL;
    char *password = NULL;

    if (passwordFunc != NULL)  {

        if (passwordPrompt)
	    prompt = passwordPrompt;

        result = PyObject_CallFunction(passwordFunc, "s", prompt);
        if (!result)
	    return "";

        usernameObj = PyTuple_GetItem(result, 0);
        if (!usernameObj)
            return "";
        username = PyString_AsString(usernameObj);
/*      printf("usernameObj=%p, username='%s'\n", usernameObj, username); */
        if (!username)
	    return "";

        passwordObj = PyTuple_GetItem(result, 1);
        if (!passwordObj)
	    return "";
        password = PyString_AsString(passwordObj);
/*      printf("passwordObj=%p, password='%s'\n", passwordObj, password); */
        if (!password)
	    return "";

        cupsSetUser(username);
        return password;

    }

    return "";

}

PyObject *setPasswordPrompt(PyObject *self, PyObject *args)
{

    char *userPrompt = NULL;

    if (!PyArg_ParseTuple(args, "z", &userPrompt))
        return Py_BuildValue("");

    if (strlen(userPrompt) != 0)
        passwordPrompt = userPrompt;
    else
        passwordPrompt = NULL;

    return Py_BuildValue("");

}

PyObject * setPasswordCallback( PyObject * self, PyObject * args )
{
    if( !PyArg_ParseTuple( args, "O", &passwordFunc ) )
    {
        return Py_BuildValue( "i", 0 );
    }

    cupsSetPasswordCB(password_callback);

    return Py_BuildValue( "i", 1 );
}


PyObject * getPassword( PyObject * self, PyObject * args )
{
    const char * pwd;
    char * prompt;

    if( !PyArg_ParseTuple( args, "s", &prompt ) )
    {
        return Py_BuildValue( "" );
    }

    pwd = cupsGetPassword( prompt );

    if( pwd )
    {
        return Py_BuildValue( "s", pwd );
    }
    else
    {
        return Py_BuildValue( "" );
    }
}






// ***************************************************************************************************

static PyMethodDef cupsext_methods[] =
    {
        { "getPrinters", ( PyCFunction ) getPrinters, METH_VARARGS },
        { "addPrinter", ( PyCFunction ) addPrinter, METH_VARARGS },
        { "delPrinter", ( PyCFunction ) delPrinter, METH_VARARGS },
        { "getDefaultPrinter", ( PyCFunction ) getDefaultPrinter, METH_VARARGS },
        { "setDefaultPrinter", ( PyCFunction ) setDefaultPrinter, METH_VARARGS },
        { "controlPrinter", ( PyCFunction ) controlPrinter, METH_VARARGS },
        { "getPPDList", ( PyCFunction ) getPPDList, METH_VARARGS },
        { "getPPD", ( PyCFunction ) getPPD, METH_VARARGS },
        { "openPPD", ( PyCFunction ) openPPD, METH_VARARGS },
        { "closePPD", ( PyCFunction ) closePPD, METH_VARARGS },
        { "getPPDOption", ( PyCFunction ) getPPDOption, METH_VARARGS },
        { "getPPDPageSize", ( PyCFunction ) getPPDPageSize, METH_VARARGS },
        { "getVersion", ( PyCFunction ) getVersion, METH_VARARGS },
        { "getVersionTuple", ( PyCFunction ) getVersionTuple, METH_VARARGS },
        { "cancelJob", ( PyCFunction ) cancelJob, METH_VARARGS },
        { "getJobs", ( PyCFunction ) getJobs, METH_VARARGS },
        { "getServer", ( PyCFunction ) getServer, METH_VARARGS },
        { "setServer", ( PyCFunction ) setServer, METH_VARARGS },
        { "addOption", ( PyCFunction ) addOption, METH_VARARGS },
        { "removeOption", ( PyCFunction ) removeOption, METH_VARARGS },
        { "resetOptions", ( PyCFunction ) resetOptions, METH_VARARGS },
        { "printFileWithOptions", ( PyCFunction ) printFileWithOptions, METH_VARARGS },
        { "Job", ( PyCFunction ) newJob, METH_VARARGS | METH_KEYWORDS },
        { "Printer", ( PyCFunction ) newPrinter, METH_VARARGS | METH_KEYWORDS },
        { "getGroupList", ( PyCFunction ) getGroupList, METH_VARARGS },
        { "getGroup", ( PyCFunction ) getGroup, METH_VARARGS },
        { "getOptionList", ( PyCFunction ) getOptionList, METH_VARARGS },
        { "getOption", ( PyCFunction ) getOption, METH_VARARGS },
        { "getChoiceList", ( PyCFunction ) getChoiceList, METH_VARARGS },
        { "getChoice", ( PyCFunction ) getChoice, METH_VARARGS },
        { "setOptions", ( PyCFunction ) setOptions, METH_VARARGS },
        { "getOptions", ( PyCFunction ) getOptions, METH_VARARGS },
        { "setPasswordPrompt", (PyCFunction) setPasswordPrompt, METH_VARARGS },
        { "setPasswordCallback", ( PyCFunction ) setPasswordCallback, METH_VARARGS },
        { "getPassword", ( PyCFunction ) getPassword, METH_VARARGS },
        { NULL, NULL }
    };


static char cupsext_documentation[] = "Python extension for CUPS 1.x";

void initcupsext( void )
{

    PyObject * mod = Py_InitModule4( "cupsext", cupsext_methods,
                                     cupsext_documentation, ( PyObject* ) NULL,
                                     PYTHON_API_VERSION );

    if ( mod == NULL )
        return ;


}