summaryrefslogtreecommitdiff
path: root/source3/printing/printing.c
blob: 6dbb560e43fc0c2666a6a770140afb6a48275828 (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
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
/*
   Unix SMB/Netbios implementation.
   Version 3.0
   printing backend routines
   Copyright (C) Andrew Tridgell 1992-2000
   Copyright (C) Jeremy Allison 2002

   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 3 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, see <http://www.gnu.org/licenses/>.
*/

#include "includes.h"
#include "system/syslog.h"
#include "system/filesys.h"
#include "printing.h"
#include "../librpc/gen_ndr/ndr_spoolss.h"
#include "nt_printing.h"
#include "../librpc/gen_ndr/netlogon.h"
#include "printing/notify.h"
#include "printing/pcap.h"
#include "serverid.h"
#include "smbd/smbd.h"
#include "auth.h"
#include "messages.h"
#include "util_tdb.h"

extern struct current_user current_user;
extern userdom_struct current_user_info;

/* Current printer interface */
static bool remove_from_jobs_added(const char* sharename, uint32 jobid);

/*
   the printing backend revolves around a tdb database that stores the
   SMB view of the print queue

   The key for this database is a jobid - a internally generated number that
   uniquely identifies a print job

   reading the print queue involves two steps:
     - possibly running lpq and updating the internal database from that
     - reading entries from the database

   jobids are assigned when a job starts spooling.
*/

static TDB_CONTEXT *rap_tdb;
static uint16 next_rap_jobid;
struct rap_jobid_key {
	fstring sharename;
	uint32  jobid;
};

/***************************************************************************
 Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
 bit RPC jobids.... JRA.
***************************************************************************/

uint16 pjobid_to_rap(const char* sharename, uint32 jobid)
{
	uint16 rap_jobid;
	TDB_DATA data, key;
	struct rap_jobid_key jinfo;
	uint8 buf[2];

	DEBUG(10,("pjobid_to_rap: called.\n"));

	if (!rap_tdb) {
		/* Create the in-memory tdb. */
		rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
		if (!rap_tdb)
			return 0;
	}

	ZERO_STRUCT( jinfo );
	fstrcpy( jinfo.sharename, sharename );
	jinfo.jobid = jobid;
	key.dptr = (uint8 *)&jinfo;
	key.dsize = sizeof(jinfo);

	data = tdb_fetch_compat(rap_tdb, key);
	if (data.dptr && data.dsize == sizeof(uint16)) {
		rap_jobid = SVAL(data.dptr, 0);
		SAFE_FREE(data.dptr);
		DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
			(unsigned int)jobid, (unsigned int)rap_jobid));
		return rap_jobid;
	}
	SAFE_FREE(data.dptr);
	/* Not found - create and store mapping. */
	rap_jobid = ++next_rap_jobid;
	if (rap_jobid == 0)
		rap_jobid = ++next_rap_jobid;
	SSVAL(buf,0,rap_jobid);
	data.dptr = buf;
	data.dsize = sizeof(rap_jobid);
	tdb_store(rap_tdb, key, data, TDB_REPLACE);
	tdb_store(rap_tdb, data, key, TDB_REPLACE);

	DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
		(unsigned int)jobid, (unsigned int)rap_jobid));
	return rap_jobid;
}

bool rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
{
	TDB_DATA data, key;
	uint8 buf[2];

	DEBUG(10,("rap_to_pjobid called.\n"));

	if (!rap_tdb)
		return False;

	SSVAL(buf,0,rap_jobid);
	key.dptr = buf;
	key.dsize = sizeof(rap_jobid);
	data = tdb_fetch_compat(rap_tdb, key);
	if ( data.dptr && data.dsize == sizeof(struct rap_jobid_key) )
	{
		struct rap_jobid_key *jinfo = (struct rap_jobid_key*)data.dptr;
		if (sharename != NULL) {
			fstrcpy( sharename, jinfo->sharename );
		}
		*pjobid = jinfo->jobid;
		DEBUG(10,("rap_to_pjobid: jobid %u maps to RAP jobid %u\n",
			(unsigned int)*pjobid, (unsigned int)rap_jobid));
		SAFE_FREE(data.dptr);
		return True;
	}

	DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
		(unsigned int)rap_jobid));
	SAFE_FREE(data.dptr);
	return False;
}

void rap_jobid_delete(const char* sharename, uint32 jobid)
{
	TDB_DATA key, data;
	uint16 rap_jobid;
	struct rap_jobid_key jinfo;
	uint8 buf[2];

	DEBUG(10,("rap_jobid_delete: called.\n"));

	if (!rap_tdb)
		return;

	ZERO_STRUCT( jinfo );
	fstrcpy( jinfo.sharename, sharename );
	jinfo.jobid = jobid;
	key.dptr = (uint8 *)&jinfo;
	key.dsize = sizeof(jinfo);

	data = tdb_fetch_compat(rap_tdb, key);
	if (!data.dptr || (data.dsize != sizeof(uint16))) {
		DEBUG(10,("rap_jobid_delete: cannot find jobid %u\n",
			(unsigned int)jobid ));
		SAFE_FREE(data.dptr);
		return;
	}

	DEBUG(10,("rap_jobid_delete: deleting jobid %u\n",
		(unsigned int)jobid ));

	rap_jobid = SVAL(data.dptr, 0);
	SAFE_FREE(data.dptr);
	SSVAL(buf,0,rap_jobid);
	data.dptr = buf;
	data.dsize = sizeof(rap_jobid);
	tdb_delete(rap_tdb, key);
	tdb_delete(rap_tdb, data);
}

static int get_queue_status(const char* sharename, print_status_struct *);

/****************************************************************************
 Initialise the printing backend. Called once at startup before the fork().
****************************************************************************/

bool print_backend_init(struct messaging_context *msg_ctx)
{
	const char *sversion = "INFO/version";
	int services = lp_numservices();
	int snum;

	unlink(cache_path("printing.tdb"));
	mkdir(cache_path("printing"),0755);

	/* handle a Samba upgrade */

	for (snum = 0; snum < services; snum++) {
		struct tdb_print_db *pdb;
		if (!lp_print_ok(snum))
			continue;

		pdb = get_print_db_byname(lp_const_servicename(snum));
		if (!pdb)
			continue;
		if (tdb_lock_bystring(pdb->tdb, sversion) == -1) {
			DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
			release_print_db(pdb);
			return False;
		}
		if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
			tdb_wipe_all(pdb->tdb);
			tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
		}
		tdb_unlock_bystring(pdb->tdb, sversion);
		release_print_db(pdb);
	}

	close_all_print_db(); /* Don't leave any open. */

	/* do NT print initialization... */
	return nt_printing_init(msg_ctx);
}

/****************************************************************************
 Shut down printing backend. Called once at shutdown to close the tdb.
****************************************************************************/

void printing_end(void)
{
	close_all_print_db(); /* Don't leave any open. */
}

/****************************************************************************
 Retrieve the set of printing functions for a given service.  This allows
 us to set the printer function table based on the value of the 'printing'
 service parameter.

 Use the generic interface as the default and only use cups interface only
 when asked for (and only when supported)
****************************************************************************/

static struct printif *get_printer_fns_from_type( enum printing_types type )
{
	struct printif *printer_fns = &generic_printif;

#ifdef HAVE_CUPS
	if ( type == PRINT_CUPS ) {
		printer_fns = &cups_printif;
	}
#endif /* HAVE_CUPS */

#ifdef HAVE_IPRINT
	if ( type == PRINT_IPRINT ) {
		printer_fns = &iprint_printif;
	}
#endif /* HAVE_IPRINT */

	printer_fns->type = type;

	return printer_fns;
}

static struct printif *get_printer_fns( int snum )
{
	return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
}


/****************************************************************************
 Useful function to generate a tdb key.
****************************************************************************/

static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
{
	TDB_DATA ret;

	SIVAL(tmp, 0, jobid);
	ret.dptr = (uint8 *)tmp;
	ret.dsize = sizeof(*tmp);
	return ret;
}

/****************************************************************************
 Pack the devicemode to store it in a tdb.
****************************************************************************/
static int pack_devicemode(struct spoolss_DeviceMode *devmode, uint8 *buf, int buflen)
{
	enum ndr_err_code ndr_err;
	DATA_BLOB blob;
	int len = 0;

	if (devmode) {
		ndr_err = ndr_push_struct_blob(&blob, talloc_tos(),
					       devmode,
					       (ndr_push_flags_fn_t)
					       ndr_push_spoolss_DeviceMode);
		if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
			DEBUG(10, ("pack_devicemode: "
				   "error encoding spoolss_DeviceMode\n"));
			goto done;
		}
	} else {
		ZERO_STRUCT(blob);
	}

	len = tdb_pack(buf, buflen, "B", blob.length, blob.data);

	if (devmode) {
		DEBUG(8, ("Packed devicemode [%s]\n", devmode->formname));
	}

done:
	return len;
}

/****************************************************************************
 Unpack the devicemode to store it in a tdb.
****************************************************************************/
static int unpack_devicemode(TALLOC_CTX *mem_ctx,
		      const uint8 *buf, int buflen,
		      struct spoolss_DeviceMode **devmode)
{
	struct spoolss_DeviceMode *dm;
	enum ndr_err_code ndr_err;
	char *data = NULL;
	int data_len = 0;
	DATA_BLOB blob;
	int len = 0;

	*devmode = NULL;

	len = tdb_unpack(buf, buflen, "B", &data_len, &data);
	if (!data) {
		return len;
	}

	dm = talloc_zero(mem_ctx, struct spoolss_DeviceMode);
	if (!dm) {
		goto done;
	}

	blob = data_blob_const(data, data_len);

	ndr_err = ndr_pull_struct_blob(&blob, dm, dm,
			(ndr_pull_flags_fn_t)ndr_pull_spoolss_DeviceMode);
	if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
		DEBUG(10, ("unpack_devicemode: "
			   "error parsing spoolss_DeviceMode\n"));
		goto done;
	}

	DEBUG(8, ("Unpacked devicemode [%s](%s)\n",
		  dm->devicename, dm->formname));
	if (dm->driverextra_data.data) {
		DEBUG(8, ("with a private section of %d bytes\n",
			  dm->__driverextra_length));
	}

	*devmode = dm;

done:
	SAFE_FREE(data);
	return len;
}

/***********************************************************************
 unpack a pjob from a tdb buffer
***********************************************************************/

static int unpack_pjob( uint8 *buf, int buflen, struct printjob *pjob )
{
	int	len = 0;
	int	used;
	uint32 pjpid, pjsysjob, pjfd, pjstarttime, pjstatus;
	uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;

	if ( !buf || !pjob )
		return -1;

	len += tdb_unpack(buf+len, buflen-len, "dddddddddfffff",
				&pjpid,
				&pjsysjob,
				&pjfd,
				&pjstarttime,
				&pjstatus,
				&pjsize,
				&pjpage_count,
				&pjspooled,
				&pjsmbjob,
				pjob->filename,
				pjob->jobname,
				pjob->user,
				pjob->clientmachine,
				pjob->queuename);

	if ( len == -1 )
		return -1;

        used = unpack_devicemode(NULL, buf+len, buflen-len, &pjob->devmode);
        if (used == -1) {
		return -1;
        }

	len += used;

	pjob->pid = pjpid;
	pjob->sysjob = pjsysjob;
	pjob->fd = pjfd;
	pjob->starttime = pjstarttime;
	pjob->status = pjstatus;
	pjob->size = pjsize;
	pjob->page_count = pjpage_count;
	pjob->spooled = pjspooled;
	pjob->smbjob = pjsmbjob;

	return len;

}

/****************************************************************************
 Useful function to find a print job in the database.
****************************************************************************/

static struct printjob *print_job_find(const char *sharename, uint32 jobid)
{
	static struct printjob 	pjob;
	uint32_t tmp;
	TDB_DATA 		ret;
	struct tdb_print_db 	*pdb = get_print_db_byname(sharename);

	DEBUG(10,("print_job_find: looking up job %u for share %s\n",
			(unsigned int)jobid, sharename ));

	if (!pdb) {
		return NULL;
	}

	ret = tdb_fetch_compat(pdb->tdb, print_key(jobid, &tmp));
	release_print_db(pdb);

	if (!ret.dptr) {
		DEBUG(10,("print_job_find: failed to find jobid %u.\n", (unsigned int)jobid ));
		return NULL;
	}

	talloc_free(pjob.devmode);

	ZERO_STRUCT( pjob );

	if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
		DEBUG(10,("print_job_find: failed to unpack jobid %u.\n", (unsigned int)jobid ));
		SAFE_FREE(ret.dptr);
		return NULL;
	}

	SAFE_FREE(ret.dptr);

	DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
			(int)pjob.sysjob, (unsigned int)jobid ));

	return &pjob;
}

/* Convert a unix jobid to a smb jobid */

struct unixjob_traverse_state {
	int sysjob;
	uint32 sysjob_to_jobid_value;
};

static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
			       TDB_DATA data, void *private_data)
{
	struct printjob *pjob;
	struct unixjob_traverse_state *state =
		(struct unixjob_traverse_state *)private_data;

	if (!data.dptr || data.dsize == 0)
		return 0;

	pjob = (struct printjob *)data.dptr;
	if (key.dsize != sizeof(uint32))
		return 0;

	if (state->sysjob == pjob->sysjob) {
		uint32 jobid = IVAL(key.dptr,0);

		state->sysjob_to_jobid_value = jobid;
		return 1;
	}

	return 0;
}

/****************************************************************************
 This is a *horribly expensive call as we have to iterate through all the
 current printer tdb's. Don't do this often ! JRA.
****************************************************************************/

uint32 sysjob_to_jobid(int unix_jobid)
{
	int services = lp_numservices();
	int snum;
	struct unixjob_traverse_state state;

	state.sysjob = unix_jobid;
	state.sysjob_to_jobid_value = (uint32)-1;

	for (snum = 0; snum < services; snum++) {
		struct tdb_print_db *pdb;
		if (!lp_print_ok(snum))
			continue;
		pdb = get_print_db_byname(lp_const_servicename(snum));
		if (!pdb) {
			continue;
		}
		tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
		release_print_db(pdb);
		if (state.sysjob_to_jobid_value != (uint32)-1)
			return state.sysjob_to_jobid_value;
	}
	return (uint32)-1;
}

/****************************************************************************
 Send notifications based on what has changed after a pjob_store.
****************************************************************************/

static const struct {
	uint32_t lpq_status;
	uint32_t spoolss_status;
} lpq_to_spoolss_status_map[] = {
	{ LPQ_QUEUED, JOB_STATUS_QUEUED },
	{ LPQ_PAUSED, JOB_STATUS_PAUSED },
	{ LPQ_SPOOLING, JOB_STATUS_SPOOLING },
	{ LPQ_PRINTING, JOB_STATUS_PRINTING },
	{ LPQ_DELETING, JOB_STATUS_DELETING },
	{ LPQ_OFFLINE, JOB_STATUS_OFFLINE },
	{ LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
	{ LPQ_PRINTED, JOB_STATUS_PRINTED },
	{ LPQ_DELETED, JOB_STATUS_DELETED },
	{ LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
	{ LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
	{ (uint32_t)-1, 0 }
};

/* Convert a lpq status value stored in printing.tdb into the
   appropriate win32 API constant. */

static uint32 map_to_spoolss_status(uint32 lpq_status)
{
	int i = 0;

	while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
		if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
			return lpq_to_spoolss_status_map[i].spoolss_status;
		i++;
	}

	return 0;
}

/***************************************************************************
 Append a jobid to the 'jobs changed' list.
***************************************************************************/

static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32_t jobid)
{
	TDB_DATA data;
	uint32_t store_jobid;

	SIVAL(&store_jobid, 0, jobid);
	data.dptr = (uint8 *) &store_jobid;
	data.dsize = 4;

	DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));

	return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
			   data) == 0);
}

/***************************************************************************
 Remove a jobid from the 'jobs changed' list.
***************************************************************************/

static bool remove_from_jobs_changed(const char* sharename, uint32_t jobid)
{
	struct tdb_print_db *pdb = get_print_db_byname(sharename);
	TDB_DATA data, key;
	size_t job_count, i;
	bool ret = False;
	bool gotlock = False;

	if (!pdb) {
		return False;
	}

	ZERO_STRUCT(data);

	key = string_tdb_data("INFO/jobs_changed");

	if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
		goto out;

	gotlock = True;

	data = tdb_fetch_compat(pdb->tdb, key);

	if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
		goto out;

	job_count = data.dsize / 4;
	for (i = 0; i < job_count; i++) {
		uint32 ch_jobid;

		ch_jobid = IVAL(data.dptr, i*4);
		if (ch_jobid == jobid) {
			if (i < job_count -1 )
				memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
			data.dsize -= 4;
			if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) != 0)
				goto out;
			break;
		}
	}

	ret = True;
  out:

	if (gotlock)
		tdb_chainunlock(pdb->tdb, key);
	SAFE_FREE(data.dptr);
	release_print_db(pdb);
	if (ret)
		DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
	else
		DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
	return ret;
}

static void pjob_store_notify(struct tevent_context *ev,
			      struct messaging_context *msg_ctx,
			      const char* sharename, uint32 jobid,
			      struct printjob *old_data,
			      struct printjob *new_data,
			      bool *pchanged)
{
	bool new_job = false;
	bool changed = false;

	if (old_data == NULL) {
		new_job = true;
	}

	/* ACHTUNG!  Due to a bug in Samba's spoolss parsing of the
	   NOTIFY_INFO_DATA buffer, we *have* to send the job submission
	   time first or else we'll end up with potential alignment
	   errors.  I don't think the systemtime should be spooled as
	   a string, but this gets us around that error.
	   --jerry (i'll feel dirty for this) */

	if (new_job) {
		notify_job_submitted(ev, msg_ctx,
				     sharename, jobid, new_data->starttime);
		notify_job_username(ev, msg_ctx,
				    sharename, jobid, new_data->user);
		notify_job_name(ev, msg_ctx,
				sharename, jobid, new_data->jobname);
		notify_job_status(ev, msg_ctx,
				  sharename, jobid, map_to_spoolss_status(new_data->status));
		notify_job_total_bytes(ev, msg_ctx,
				       sharename, jobid, new_data->size);
		notify_job_total_pages(ev, msg_ctx,
				       sharename, jobid, new_data->page_count);
	} else {
		if (!strequal(old_data->jobname, new_data->jobname)) {
			notify_job_name(ev, msg_ctx, sharename,
					jobid, new_data->jobname);
			changed = true;
		}

		if (old_data->status != new_data->status) {
			notify_job_status(ev, msg_ctx,
					  sharename, jobid,
					  map_to_spoolss_status(new_data->status));
		}

		if (old_data->size != new_data->size) {
			notify_job_total_bytes(ev, msg_ctx,
					       sharename, jobid, new_data->size);
		}

		if (old_data->page_count != new_data->page_count) {
			notify_job_total_pages(ev, msg_ctx,
					       sharename, jobid,
					       new_data->page_count);
		}
	}

	*pchanged = changed;
}

/****************************************************************************
 Store a job structure back to the database.
****************************************************************************/

static bool pjob_store(struct tevent_context *ev,
		       struct messaging_context *msg_ctx,
		       const char* sharename, uint32 jobid,
		       struct printjob *pjob)
{
	uint32_t tmp;
	TDB_DATA 		old_data, new_data;
	bool 			ret = False;
	struct tdb_print_db 	*pdb = get_print_db_byname(sharename);
	uint8			*buf = NULL;
	int			len, newlen, buflen;


	if (!pdb)
		return False;

	/* Get old data */

	old_data = tdb_fetch_compat(pdb->tdb, print_key(jobid, &tmp));

	/* Doh!  Now we have to pack/unpack data since the NT_DEVICEMODE was added */

	newlen = 0;

	do {
		len = 0;
		buflen = newlen;
		len += tdb_pack(buf+len, buflen-len, "dddddddddfffff",
				(uint32)pjob->pid,
				(uint32)pjob->sysjob,
				(uint32)pjob->fd,
				(uint32)pjob->starttime,
				(uint32)pjob->status,
				(uint32)pjob->size,
				(uint32)pjob->page_count,
				(uint32)pjob->spooled,
				(uint32)pjob->smbjob,
				pjob->filename,
				pjob->jobname,
				pjob->user,
				pjob->clientmachine,
				pjob->queuename);

		len += pack_devicemode(pjob->devmode, buf+len, buflen-len);

		if (buflen != len) {
			buf = (uint8 *)SMB_REALLOC(buf, len);
			if (!buf) {
				DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
				goto done;
			}
			newlen = len;
		}
	} while ( buflen != len );


	/* Store new data */

	new_data.dptr = buf;
	new_data.dsize = len;
	ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
			 TDB_REPLACE) == 0);

	/* Send notify updates for what has changed */

	if ( ret ) {
		bool changed = false;
		struct printjob old_pjob;

		if ( old_data.dsize )
		{
			if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
			{
				pjob_store_notify(server_event_context(),
						  msg_ctx,
						  sharename, jobid, &old_pjob,
						  pjob,
						  &changed);
				talloc_free(old_pjob.devmode);

				if (changed) {
					add_to_jobs_changed(pdb, jobid);
				}
			}

		}
		else {
			/* new job */
			pjob_store_notify(server_event_context(), msg_ctx,
					  sharename, jobid, NULL, pjob,
					  &changed);
		}
	}

	release_print_db(pdb);
done:
	SAFE_FREE( old_data.dptr );
	SAFE_FREE( buf );

	return ret;
}

/****************************************************************************
 Remove a job structure from the database.
****************************************************************************/

static void pjob_delete(struct tevent_context *ev,
			struct messaging_context *msg_ctx,
			const char* sharename, uint32 jobid)
{
	uint32_t tmp;
	struct printjob *pjob;
	uint32 job_status = 0;
	struct tdb_print_db *pdb;

	pdb = get_print_db_byname( sharename );

	if (!pdb)
		return;

	pjob = print_job_find( sharename, jobid );

	if (!pjob) {
		DEBUG(5, ("pjob_delete: we were asked to delete nonexistent job %u\n",
					(unsigned int)jobid));
		release_print_db(pdb);
		return;
	}

	/* We must cycle through JOB_STATUS_DELETING and
           JOB_STATUS_DELETED for the port monitor to delete the job
           properly. */

	job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
	notify_job_status(ev, msg_ctx, sharename, jobid, job_status);

	/* Remove from printing.tdb */

	tdb_delete(pdb->tdb, print_key(jobid, &tmp));
	remove_from_jobs_added(sharename, jobid);
	release_print_db( pdb );
	rap_jobid_delete(sharename, jobid);
}

/****************************************************************************
 List a unix job in the print database.
****************************************************************************/

static void print_unix_job(struct tevent_context *ev,
			   struct messaging_context *msg_ctx,
			   const char *sharename, print_queue_struct *q,
			   uint32 jobid)
{
	struct printjob pj, *old_pj;

	if (jobid == (uint32)-1)
		jobid = q->job + UNIX_JOB_START;

	/* Preserve the timestamp on an existing unix print job */

	old_pj = print_job_find(sharename, jobid);

	ZERO_STRUCT(pj);

	pj.pid = (pid_t)-1;
	pj.sysjob = q->job;
	pj.fd = -1;
	pj.starttime = old_pj ? old_pj->starttime : q->time;
	pj.status = q->status;
	pj.size = q->size;
	pj.spooled = True;
	fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
	if (jobid < UNIX_JOB_START) {
		pj.smbjob = True;
		fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
	} else {
		pj.smbjob = False;
		fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
	}
	fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
	fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );

	pjob_store(ev, msg_ctx, sharename, jobid, &pj);
}


struct traverse_struct {
	print_queue_struct *queue;
	int qcount, snum, maxcount, total_jobs;
	const char *sharename;
	time_t lpq_time;
	const char *lprm_command;
	struct printif *print_if;
	struct tevent_context *ev;
	struct messaging_context *msg_ctx;
};

/****************************************************************************
 Utility fn to delete any jobs that are no longer active.
****************************************************************************/

static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
{
	struct traverse_struct *ts = (struct traverse_struct *)state;
	struct printjob pjob;
	uint32 jobid;
	int i = 0;

	if (  key.dsize != sizeof(jobid) )
		return 0;

	jobid = IVAL(key.dptr, 0);
	if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
		return 0;
	talloc_free(pjob.devmode);


	if (!pjob.smbjob) {
		/* remove a unix job if it isn't in the system queue any more */

		for (i=0;i<ts->qcount;i++) {
			uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
			if (jobid == u_jobid)
				break;
		}
		if (i == ts->qcount) {
			DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
						(unsigned int)jobid ));
			pjob_delete(ts->ev, ts->msg_ctx,
				    ts->sharename, jobid);
			return 0;
		}

		/* need to continue the the bottom of the function to
		   save the correct attributes */
	}

	/* maybe it hasn't been spooled yet */
	if (!pjob.spooled) {
		/* if a job is not spooled and the process doesn't
                   exist then kill it. This cleans up after smbd
                   deaths */
		if (!process_exists_by_pid(pjob.pid)) {
			DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
						(unsigned int)jobid, (unsigned int)pjob.pid ));
			pjob_delete(ts->ev, ts->msg_ctx,
				    ts->sharename, jobid);
		} else
			ts->total_jobs++;
		return 0;
	}

	/* this check only makes sense for jobs submitted from Windows clients */

	if ( pjob.smbjob ) {
		for (i=0;i<ts->qcount;i++) {
			uint32 curr_jobid;

			if ( pjob.status == LPQ_DELETED )
				continue;

			curr_jobid = print_parse_jobid(ts->queue[i].fs_file);

			if (jobid == curr_jobid) {

				/* try to clean up any jobs that need to be deleted */

				if ( pjob.status == LPQ_DELETING ) {
					int result;

					result = (*(ts->print_if->job_delete))(
						ts->sharename, ts->lprm_command, &pjob );

					if ( result != 0 ) {
						/* if we can't delete, then reset the job status */
						pjob.status = LPQ_QUEUED;
						pjob_store(ts->ev, ts->msg_ctx,
							   ts->sharename, jobid, &pjob);
					}
					else {
						/* if we deleted the job, the remove the tdb record */
						pjob_delete(ts->ev,
							    ts->msg_ctx,
							    ts->sharename, jobid);
						pjob.status = LPQ_DELETED;
					}

				}

				break;
			}
		}
	}

	/* The job isn't in the system queue - we have to assume it has
	   completed, so delete the database entry. */

	if (i == ts->qcount) {

		/* A race can occur between the time a job is spooled and
		   when it appears in the lpq output.  This happens when
		   the job is added to printing.tdb when another smbd
		   running print_queue_update() has completed a lpq and
		   is currently traversing the printing tdb and deleting jobs.
		   Don't delete the job if it was submitted after the lpq_time. */

		if (pjob.starttime < ts->lpq_time) {
			DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
						(unsigned int)jobid,
						(unsigned int)pjob.starttime,
						(unsigned int)ts->lpq_time ));
			pjob_delete(ts->ev, ts->msg_ctx,
				    ts->sharename, jobid);
		} else
			ts->total_jobs++;
		return 0;
	}

	/* Save the pjob attributes we will store.
	   FIXME!!! This is the only place where queue->job
	   represents the SMB jobid      --jerry */

	ts->queue[i].job = jobid;
	ts->queue[i].size = pjob.size;
	ts->queue[i].page_count = pjob.page_count;
	ts->queue[i].status = pjob.status;
	ts->queue[i].priority = 1;
	ts->queue[i].time = pjob.starttime;
	fstrcpy(ts->queue[i].fs_user, pjob.user);
	fstrcpy(ts->queue[i].fs_file, pjob.jobname);

	ts->total_jobs++;

	return 0;
}

/****************************************************************************
 Check if the print queue has been updated recently enough.
****************************************************************************/

static void print_cache_flush(const char *sharename)
{
	fstring key;
	struct tdb_print_db *pdb = get_print_db_byname(sharename);

	if (!pdb)
		return;
	slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
	tdb_store_int32(pdb->tdb, key, -1);
	release_print_db(pdb);
}

/****************************************************************************
 Check if someone already thinks they are doing the update.
****************************************************************************/

static pid_t get_updating_pid(const char *sharename)
{
	fstring keystr;
	TDB_DATA data, key;
	pid_t updating_pid;
	struct tdb_print_db *pdb = get_print_db_byname(sharename);

	if (!pdb)
		return (pid_t)-1;
	slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
    	key = string_tdb_data(keystr);

	data = tdb_fetch_compat(pdb->tdb, key);
	release_print_db(pdb);
	if (!data.dptr || data.dsize != sizeof(pid_t)) {
		SAFE_FREE(data.dptr);
		return (pid_t)-1;
	}

	updating_pid = IVAL(data.dptr, 0);
	SAFE_FREE(data.dptr);

	if (process_exists_by_pid(updating_pid))
		return updating_pid;

	return (pid_t)-1;
}

/****************************************************************************
 Set the fact that we're doing the update, or have finished doing the update
 in the tdb.
****************************************************************************/

static void set_updating_pid(const fstring sharename, bool updating)
{
	fstring keystr;
	TDB_DATA key;
	TDB_DATA data;
	pid_t updating_pid = sys_getpid();
	uint8 buffer[4];

	struct tdb_print_db *pdb = get_print_db_byname(sharename);

	if (!pdb)
		return;

	slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
    	key = string_tdb_data(keystr);

	DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
		updating ? "" : "not ",
		sharename ));

	if ( !updating ) {
		tdb_delete(pdb->tdb, key);
		release_print_db(pdb);
		return;
	}

	SIVAL( buffer, 0, updating_pid);
	data.dptr = buffer;
	data.dsize = 4;		/* we always assume this is a 4 byte value */

	tdb_store(pdb->tdb, key, data, TDB_REPLACE);
	release_print_db(pdb);
}

/****************************************************************************
 Sort print jobs by submittal time.
****************************************************************************/

static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
{
	/* Silly cases */

	if (!j1 && !j2)
		return 0;
	if (!j1)
		return -1;
	if (!j2)
		return 1;

	/* Sort on job start time */

	if (j1->time == j2->time)
		return 0;
	return (j1->time > j2->time) ? 1 : -1;
}

/****************************************************************************
 Store the sorted queue representation for later portmon retrieval.
 Skip deleted jobs
****************************************************************************/

static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
{
	TDB_DATA data;
	int max_reported_jobs = lp_max_reported_jobs(pts->snum);
	print_queue_struct *queue = pts->queue;
	size_t len;
	size_t i;
	unsigned int qcount;

	if (max_reported_jobs && (max_reported_jobs < pts->qcount))
		pts->qcount = max_reported_jobs;
	qcount = 0;

	/* Work out the size. */
	data.dsize = 0;
	data.dsize += tdb_pack(NULL, 0, "d", qcount);

	for (i = 0; i < pts->qcount; i++) {
		if ( queue[i].status == LPQ_DELETED )
			continue;

		qcount++;
		data.dsize += tdb_pack(NULL, 0, "ddddddff",
				(uint32)queue[i].job,
				(uint32)queue[i].size,
				(uint32)queue[i].page_count,
				(uint32)queue[i].status,
				(uint32)queue[i].priority,
				(uint32)queue[i].time,
				queue[i].fs_user,
				queue[i].fs_file);
	}

	if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
		return;

        len = 0;
	len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
	for (i = 0; i < pts->qcount; i++) {
		if ( queue[i].status == LPQ_DELETED )
			continue;

		len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
				(uint32)queue[i].job,
				(uint32)queue[i].size,
				(uint32)queue[i].page_count,
				(uint32)queue[i].status,
				(uint32)queue[i].priority,
				(uint32)queue[i].time,
				queue[i].fs_user,
				queue[i].fs_file);
	}

	tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
		  TDB_REPLACE);
	SAFE_FREE(data.dptr);
	return;
}

static TDB_DATA get_jobs_added_data(struct tdb_print_db *pdb)
{
	TDB_DATA data;

	ZERO_STRUCT(data);

	data = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_added"));
	if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
		SAFE_FREE(data.dptr);
		ZERO_STRUCT(data);
	}

	return data;
}

static void check_job_added(const char *sharename, TDB_DATA data, uint32 jobid)
{
	unsigned int i;
	unsigned int job_count = data.dsize / 4;

	for (i = 0; i < job_count; i++) {
		uint32 ch_jobid;

		ch_jobid = IVAL(data.dptr, i*4);
		if (ch_jobid == jobid)
			remove_from_jobs_added(sharename, jobid);
	}
}

/****************************************************************************
 Check if the print queue has been updated recently enough.
****************************************************************************/

static bool print_cache_expired(const char *sharename, bool check_pending)
{
	fstring key;
	time_t last_qscan_time, time_now = time(NULL);
	struct tdb_print_db *pdb = get_print_db_byname(sharename);
	bool result = False;

	if (!pdb)
		return False;

	snprintf(key, sizeof(key), "CACHE/%s", sharename);
	last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);

	/*
	 * Invalidate the queue for 3 reasons.
	 * (1). last queue scan time == -1.
	 * (2). Current time - last queue scan time > allowed cache time.
	 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
	 * This last test picks up machines for which the clock has been moved
	 * forward, an lpq scan done and then the clock moved back. Otherwise
	 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
	 */

	if (last_qscan_time == ((time_t)-1)
		|| (time_now - last_qscan_time) >= lp_lpqcachetime()
		|| last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
	{
		uint32 u;
		time_t msg_pending_time;

		DEBUG(4, ("print_cache_expired: cache expired for queue %s "
			"(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
			sharename, (int)last_qscan_time, (int)time_now,
			(int)lp_lpqcachetime() ));

		/* check if another smbd has already sent a message to update the
		   queue.  Give the pending message one minute to clear and
		   then send another message anyways.  Make sure to check for
		   clocks that have been run forward and then back again. */

		snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);

		if ( check_pending
			&& tdb_fetch_uint32( pdb->tdb, key, &u )
			&& (msg_pending_time=u) > 0
			&& msg_pending_time <= time_now
			&& (time_now - msg_pending_time) < 60 )
		{
			DEBUG(4,("print_cache_expired: message already pending for %s.  Accepting cache\n",
				sharename));
			goto done;
		}

		result = True;
	}

done:
	release_print_db(pdb);
	return result;
}

/****************************************************************************
 main work for updating the lpq cache for a printer queue
****************************************************************************/

static void print_queue_update_internal( struct tevent_context *ev,
					 struct messaging_context *msg_ctx,
					 const char *sharename,
                                         struct printif *current_printif,
                                         char *lpq_command, char *lprm_command )
{
	int i, qcount;
	print_queue_struct *queue = NULL;
	print_status_struct status;
	print_status_struct old_status;
	struct printjob *pjob;
	struct traverse_struct tstruct;
	TDB_DATA data, key;
	TDB_DATA jcdata;
	fstring keystr, cachestr;
	struct tdb_print_db *pdb = get_print_db_byname(sharename);

	if (!pdb) {
		return;
	}

	DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
		sharename, current_printif->type, lpq_command));

	/*
	 * Update the cache time FIRST ! Stops others even
	 * attempting to get the lock and doing this
	 * if the lpq takes a long time.
	 */

	slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
	tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));

        /* get the current queue using the appropriate interface */
	ZERO_STRUCT(status);

	qcount = (*(current_printif->queue_get))(sharename,
		current_printif->type,
		lpq_command, &queue, &status);

	DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
		qcount, (qcount != 1) ?	"s" : "", sharename));

	/* Sort the queue by submission time otherwise they are displayed
	   in hash order. */

	TYPESAFE_QSORT(queue, qcount, printjob_comp);

	/*
	  any job in the internal database that is marked as spooled
	  and doesn't exist in the system queue is considered finished
	  and removed from the database

	  any job in the system database but not in the internal database
	  is added as a unix job

	  fill in any system job numbers as we go
	*/

	jcdata = get_jobs_added_data(pdb);

	for (i=0; i<qcount; i++) {
		uint32 jobid = print_parse_jobid(queue[i].fs_file);

		if (jobid == (uint32)-1) {
			/* assume its a unix print job */
			print_unix_job(ev, msg_ctx,
				       sharename, &queue[i], jobid);
			continue;
		}

		/* we have an active SMB print job - update its status */
		pjob = print_job_find(sharename, jobid);
		if (!pjob) {
			/* err, somethings wrong. Probably smbd was restarted
			   with jobs in the queue. All we can do is treat them
			   like unix jobs. Pity. */
			print_unix_job(ev, msg_ctx,
				       sharename, &queue[i], jobid);
			continue;
		}

		pjob->sysjob = queue[i].job;

		/* don't reset the status on jobs to be deleted */

		if ( pjob->status != LPQ_DELETING )
			pjob->status = queue[i].status;

		pjob_store(ev, msg_ctx, sharename, jobid, pjob);

		check_job_added(sharename, jcdata, jobid);
	}

	SAFE_FREE(jcdata.dptr);

	/* now delete any queued entries that don't appear in the
           system queue */
	tstruct.queue = queue;
	tstruct.qcount = qcount;
	tstruct.snum = -1;
	tstruct.total_jobs = 0;
	tstruct.lpq_time = time(NULL);
	tstruct.sharename = sharename;
	tstruct.lprm_command = lprm_command;
	tstruct.print_if = current_printif;
	tstruct.ev = ev;
	tstruct.msg_ctx = msg_ctx;

	tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);

	/* Store the linearised queue, max jobs only. */
	store_queue_struct(pdb, &tstruct);

	SAFE_FREE(tstruct.queue);

	DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
				sharename, tstruct.total_jobs ));

	tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);

	get_queue_status(sharename, &old_status);
	if (old_status.qcount != qcount)
		DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
					old_status.qcount, qcount, sharename));

	/* store the new queue status structure */
	slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
	key = string_tdb_data(keystr);

	status.qcount = qcount;
	data.dptr = (uint8 *)&status;
	data.dsize = sizeof(status);
	tdb_store(pdb->tdb, key, data, TDB_REPLACE);

	/*
	 * Update the cache time again. We want to do this call
	 * as little as possible...
	 */

	slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
	tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));

	/* clear the msg pending record for this queue */

	snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);

	if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
		/* log a message but continue on */

		DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
			sharename));
	}

	release_print_db( pdb );

	return;
}

/****************************************************************************
 Update the internal database from the system print queue for a queue.
 obtain a lock on the print queue before proceeding (needed when mutiple
 smbd processes maytry to update the lpq cache concurrently).
****************************************************************************/

static void print_queue_update_with_lock( struct tevent_context *ev,
					  struct messaging_context *msg_ctx,
					  const char *sharename,
                                          struct printif *current_printif,
                                          char *lpq_command, char *lprm_command )
{
	fstring keystr;
	struct tdb_print_db *pdb;

	DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
	pdb = get_print_db_byname(sharename);
	if (!pdb)
		return;

	if ( !print_cache_expired(sharename, False) ) {
		DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
		release_print_db(pdb);
		return;
	}

	/*
	 * Check to see if someone else is doing this update.
	 * This is essentially a mutex on the update.
	 */

	if (get_updating_pid(sharename) != -1) {
		release_print_db(pdb);
		return;
	}

	/* Lock the queue for the database update */

	slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
	/* Only wait 10 seconds for this. */
	if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) == -1) {
		DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
		release_print_db(pdb);
		return;
	}

	/*
	 * Ensure that no one else got in here.
	 * If the updating pid is still -1 then we are
	 * the winner.
	 */

	if (get_updating_pid(sharename) != -1) {
		/*
		 * Someone else is doing the update, exit.
		 */
		tdb_unlock_bystring(pdb->tdb, keystr);
		release_print_db(pdb);
		return;
	}

	/*
	 * We're going to do the update ourselves.
	 */

	/* Tell others we're doing the update. */
	set_updating_pid(sharename, True);

	/*
	 * Allow others to enter and notice we're doing
	 * the update.
	 */

	tdb_unlock_bystring(pdb->tdb, keystr);

	/* do the main work now */

	print_queue_update_internal(ev, msg_ctx,
				    sharename, current_printif,
				    lpq_command, lprm_command);

	/* Delete our pid from the db. */
	set_updating_pid(sharename, False);
	release_print_db(pdb);
}

/****************************************************************************
this is the receive function of the background lpq updater
****************************************************************************/
void print_queue_receive(struct messaging_context *msg,
				void *private_data,
				uint32_t msg_type,
				struct server_id server_id,
				DATA_BLOB *data)
{
	fstring sharename;
	char *lpqcommand = NULL, *lprmcommand = NULL;
	int printing_type;
	size_t len;

	len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
		sharename,
		&printing_type,
		&lpqcommand,
		&lprmcommand );

	if ( len == -1 ) {
		SAFE_FREE(lpqcommand);
		SAFE_FREE(lprmcommand);
		DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
		return;
	}

	print_queue_update_with_lock(server_event_context(), msg, sharename,
		get_printer_fns_from_type((enum printing_types)printing_type),
		lpqcommand, lprmcommand );

	SAFE_FREE(lpqcommand);
	SAFE_FREE(lprmcommand);
	return;
}

static void printing_pause_fd_handler(struct tevent_context *ev,
				      struct tevent_fd *fde,
				      uint16_t flags,
				      void *private_data)
{
	/*
	 * If pause_pipe[1] is closed it means the parent smbd
	 * and children exited or aborted.
	 */
	exit_server_cleanly(NULL);
}

extern struct child_pid *children;
extern int num_children;

static void add_child_pid(pid_t pid)
{
	struct child_pid *child;

        child = SMB_MALLOC_P(struct child_pid);
        if (child == NULL) {
                DEBUG(0, ("Could not add child struct -- malloc failed\n"));
                return;
        }
        child->pid = pid;
        DLIST_ADD(children, child);
        num_children += 1;
}

static pid_t background_lpq_updater_pid = -1;

/****************************************************************************
main thread of the background lpq updater
****************************************************************************/
void start_background_queue(struct tevent_context *ev,
			    struct messaging_context *msg_ctx)
{
	/* Use local variables for this as we don't
	 * need to save the parent side of this, just
	 * ensure it closes when the process exits.
	 */
	int pause_pipe[2];

	DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));

	if (pipe(pause_pipe) == -1) {
		DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
		exit(1);
	}

	background_lpq_updater_pid = sys_fork();

	if (background_lpq_updater_pid == -1) {
		DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
		exit(1);
	}

	/* Track the printing pid along with other smbd children */
	add_child_pid(background_lpq_updater_pid);

	if(background_lpq_updater_pid == 0) {
		struct tevent_fd *fde;
		int ret;
		NTSTATUS status;

		/* Child. */
		DEBUG(5,("start_background_queue: background LPQ thread started\n"));

		close(pause_pipe[0]);
		pause_pipe[0] = -1;

		status = reinit_after_fork(msg_ctx, ev, procid_self(), true);

		if (!NT_STATUS_IS_OK(status)) {
			DEBUG(0,("reinit_after_fork() failed\n"));
			smb_panic("reinit_after_fork() failed");
		}

		smbd_setup_sig_term_handler();
		smbd_setup_sig_hup_handler(ev, msg_ctx);

		if (!serverid_register(procid_self(),
				       FLAG_MSG_GENERAL|FLAG_MSG_SMBD
				       |FLAG_MSG_PRINT_GENERAL)) {
			exit(1);
		}

		if (!locking_init()) {
			exit(1);
		}

		messaging_register(msg_ctx, NULL, MSG_PRINTER_UPDATE,
				   print_queue_receive);

		fde = tevent_add_fd(ev, ev, pause_pipe[1], TEVENT_FD_READ,
				    printing_pause_fd_handler,
				    NULL);
		if (!fde) {
			DEBUG(0,("tevent_add_fd() failed for pause_pipe\n"));
			smb_panic("tevent_add_fd() failed for pause_pipe");
		}

		DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
		ret = tevent_loop_wait(ev);
		/* should not be reached */
		DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
			 ret, (ret == 0) ? "out of events" : strerror(errno)));
		exit(1);
	}

	close(pause_pipe[1]);
}

/****************************************************************************
update the internal database from the system print queue for a queue
****************************************************************************/

static void print_queue_update(struct messaging_context *msg_ctx,
			       int snum, bool force)
{
	fstring key;
	fstring sharename;
	char *lpqcommand = NULL;
	char *lprmcommand = NULL;
	uint8 *buffer = NULL;
	size_t len = 0;
	size_t newlen;
	struct tdb_print_db *pdb;
	int type;
	struct printif *current_printif;
	TALLOC_CTX *ctx = talloc_tos();

	fstrcpy( sharename, lp_const_servicename(snum));

	/* don't strip out characters like '$' from the printername */

	lpqcommand = talloc_string_sub2(ctx,
			lp_lpqcommand(snum),
			"%p",
			lp_printername(snum),
			false, false, false);
	if (!lpqcommand) {
		return;
	}
	lpqcommand = talloc_sub_advanced(ctx,
			lp_servicename(snum),
			current_user_info.unix_name,
			"",
			current_user.ut.gid,
			get_current_username(),
			current_user_info.domain,
			lpqcommand);
	if (!lpqcommand) {
		return;
	}

	lprmcommand = talloc_string_sub2(ctx,
			lp_lprmcommand(snum),
			"%p",
			lp_printername(snum),
			false, false, false);
	if (!lprmcommand) {
		return;
	}
	lprmcommand = talloc_sub_advanced(ctx,
			lp_servicename(snum),
			current_user_info.unix_name,
			"",
			current_user.ut.gid,
			get_current_username(),
			current_user_info.domain,
			lprmcommand);
	if (!lprmcommand) {
		return;
	}

	/*
	 * Make sure that the background queue process exists.
	 * Otherwise just do the update ourselves
	 */

	if ( force || background_lpq_updater_pid == -1 ) {
		DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
		current_printif = get_printer_fns( snum );
		print_queue_update_with_lock(server_event_context(), msg_ctx,
					     sharename, current_printif,
					     lpqcommand, lprmcommand);

		return;
	}

	type = lp_printing(snum);

	/* get the length */

	len = tdb_pack( NULL, 0, "fdPP",
		sharename,
		type,
		lpqcommand,
		lprmcommand );

	buffer = SMB_XMALLOC_ARRAY( uint8, len );

	/* now pack the buffer */
	newlen = tdb_pack( buffer, len, "fdPP",
		sharename,
		type,
		lpqcommand,
		lprmcommand );

	SMB_ASSERT( newlen == len );

	DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
		"type = %d, lpq command = [%s] lprm command = [%s]\n",
		sharename, type, lpqcommand, lprmcommand ));

	/* here we set a msg pending record for other smbd processes
	   to throttle the number of duplicate print_queue_update msgs
	   sent.  */

	pdb = get_print_db_byname(sharename);
	if (!pdb) {
		SAFE_FREE(buffer);
		return;
	}

	snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);

	if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
		/* log a message but continue on */

		DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
			sharename));
	}

	release_print_db( pdb );

	/* finally send the message */

	messaging_send_buf(msg_ctx, pid_to_procid(background_lpq_updater_pid),
			   MSG_PRINTER_UPDATE, (uint8 *)buffer, len);

	SAFE_FREE( buffer );

	return;
}

/****************************************************************************
 Create/Update an entry in the print tdb that will allow us to send notify
 updates only to interested smbd's.
****************************************************************************/

bool print_notify_register_pid(int snum)
{
	TDB_DATA data;
	struct tdb_print_db *pdb = NULL;
	TDB_CONTEXT *tdb = NULL;
	const char *printername;
	uint32 mypid = (uint32)sys_getpid();
	bool ret = False;
	size_t i;

	/* if (snum == -1), then the change notify request was
	   on a print server handle and we need to register on
	   all print queus */

	if (snum == -1)
	{
		int num_services = lp_numservices();
		int idx;

		for ( idx=0; idx<num_services; idx++ ) {
			if (lp_snum_ok(idx) && lp_print_ok(idx) )
				print_notify_register_pid(idx);
		}

		return True;
	}
	else /* register for a specific printer */
	{
		printername = lp_const_servicename(snum);
		pdb = get_print_db_byname(printername);
		if (!pdb)
			return False;
		tdb = pdb->tdb;
	}

	if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
		DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
					printername));
		if (pdb)
			release_print_db(pdb);
		return False;
	}

	data = get_printer_notify_pid_list( tdb, printername, True );

	/* Add ourselves and increase the refcount. */

	for (i = 0; i < data.dsize; i += 8) {
		if (IVAL(data.dptr,i) == mypid) {
			uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
			SIVAL(data.dptr, i+4, new_refcount);
			break;
		}
	}

	if (i == data.dsize) {
		/* We weren't in the list. Realloc. */
		data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
		if (!data.dptr) {
			DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
						printername));
			goto done;
		}
		data.dsize += 8;
		SIVAL(data.dptr,data.dsize - 8,mypid);
		SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
	}

	/* Store back the record. */
	if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) != 0) {
		DEBUG(0,("print_notify_register_pid: Failed to update pid \
list for printer %s\n", printername));
		goto done;
	}

	ret = True;

 done:

	tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
	if (pdb)
		release_print_db(pdb);
	SAFE_FREE(data.dptr);
	return ret;
}

/****************************************************************************
 Update an entry in the print tdb that will allow us to send notify
 updates only to interested smbd's.
****************************************************************************/

bool print_notify_deregister_pid(int snum)
{
	TDB_DATA data;
	struct tdb_print_db *pdb = NULL;
	TDB_CONTEXT *tdb = NULL;
	const char *printername;
	uint32 mypid = (uint32)sys_getpid();
	size_t i;
	bool ret = False;

	/* if ( snum == -1 ), we are deregister a print server handle
	   which means to deregister on all print queues */

	if (snum == -1)
	{
		int num_services = lp_numservices();
		int idx;

		for ( idx=0; idx<num_services; idx++ ) {
			if ( lp_snum_ok(idx) && lp_print_ok(idx) )
				print_notify_deregister_pid(idx);
		}

		return True;
	}
	else /* deregister a specific printer */
	{
		printername = lp_const_servicename(snum);
		pdb = get_print_db_byname(printername);
		if (!pdb)
			return False;
		tdb = pdb->tdb;
	}

	if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
		DEBUG(0,("print_notify_register_pid: Failed to lock \
printer %s database\n", printername));
		if (pdb)
			release_print_db(pdb);
		return False;
	}

	data = get_printer_notify_pid_list( tdb, printername, True );

	/* Reduce refcount. Remove ourselves if zero. */

	for (i = 0; i < data.dsize; ) {
		if (IVAL(data.dptr,i) == mypid) {
			uint32 refcount = IVAL(data.dptr, i+4);

			refcount--;

			if (refcount == 0) {
				if (data.dsize - i > 8)
					memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
				data.dsize -= 8;
				continue;
			}
			SIVAL(data.dptr, i+4, refcount);
		}

		i += 8;
	}

	if (data.dsize == 0)
		SAFE_FREE(data.dptr);

	/* Store back the record. */
	if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) != 0) {
		DEBUG(0,("print_notify_register_pid: Failed to update pid \
list for printer %s\n", printername));
		goto done;
	}

	ret = True;

  done:

	tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
	if (pdb)
		release_print_db(pdb);
	SAFE_FREE(data.dptr);
	return ret;
}

/****************************************************************************
 Check if a jobid is valid. It is valid if it exists in the database.
****************************************************************************/

bool print_job_exists(const char* sharename, uint32 jobid)
{
	struct tdb_print_db *pdb = get_print_db_byname(sharename);
	bool ret;
	uint32_t tmp;

	if (!pdb)
		return False;
	ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
	release_print_db(pdb);
	return ret;
}

/****************************************************************************
 Give the filename used for a jobid.
 Only valid for the process doing the spooling and when the job
 has not been spooled.
****************************************************************************/

char *print_job_fname(const char* sharename, uint32 jobid)
{
	struct printjob *pjob = print_job_find(sharename, jobid);
	if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
		return NULL;
	return pjob->filename;
}


/****************************************************************************
 Give the filename used for a jobid.
 Only valid for the process doing the spooling and when the job
 has not been spooled.
****************************************************************************/

struct spoolss_DeviceMode *print_job_devmode(const char* sharename, uint32 jobid)
{
	struct printjob *pjob = print_job_find(sharename, jobid);

	if ( !pjob )
		return NULL;

	return pjob->devmode;
}

/****************************************************************************
 Set the name of a job. Only possible for owner.
****************************************************************************/

bool print_job_set_name(struct tevent_context *ev,
			struct messaging_context *msg_ctx,
			const char *sharename, uint32 jobid, const char *name)
{
	struct printjob *pjob;

	pjob = print_job_find(sharename, jobid);
	if (!pjob || pjob->pid != sys_getpid())
		return False;

	fstrcpy(pjob->jobname, name);
	return pjob_store(ev, msg_ctx, sharename, jobid, pjob);
}

/****************************************************************************
 Get the name of a job. Only possible for owner.
****************************************************************************/

bool print_job_get_name(TALLOC_CTX *mem_ctx, const char *sharename, uint32_t jobid, char **name)
{
	struct printjob *pjob;

	pjob = print_job_find(sharename, jobid);
	if (!pjob || pjob->pid != sys_getpid()) {
		return false;
	}

	*name = talloc_strdup(mem_ctx, pjob->jobname);
	if (!*name) {
		return false;
	}

	return true;
}


/***************************************************************************
 Remove a jobid from the 'jobs added' list.
***************************************************************************/

static bool remove_from_jobs_added(const char* sharename, uint32 jobid)
{
	struct tdb_print_db *pdb = get_print_db_byname(sharename);
	TDB_DATA data, key;
	size_t job_count, i;
	bool ret = False;
	bool gotlock = False;

	if (!pdb) {
		return False;
	}

	ZERO_STRUCT(data);

	key = string_tdb_data("INFO/jobs_added");

	if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
		goto out;

	gotlock = True;

	data = tdb_fetch_compat(pdb->tdb, key);

	if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
		goto out;

	job_count = data.dsize / 4;
	for (i = 0; i < job_count; i++) {
		uint32 ch_jobid;

		ch_jobid = IVAL(data.dptr, i*4);
		if (ch_jobid == jobid) {
			if (i < job_count -1 )
				memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
			data.dsize -= 4;
			if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) != 0)
				goto out;
			break;
		}
	}

	ret = True;
  out:

	if (gotlock)
		tdb_chainunlock(pdb->tdb, key);
	SAFE_FREE(data.dptr);
	release_print_db(pdb);
	if (ret)
		DEBUG(10,("remove_from_jobs_added: removed jobid %u\n", (unsigned int)jobid ));
	else
		DEBUG(10,("remove_from_jobs_added: Failed to remove jobid %u\n", (unsigned int)jobid ));
	return ret;
}

/****************************************************************************
 Delete a print job - don't update queue.
****************************************************************************/

static bool print_job_delete1(struct tevent_context *ev,
			      struct messaging_context *msg_ctx,
			      int snum, uint32 jobid)
{
	const char* sharename = lp_const_servicename(snum);
	struct printjob *pjob = print_job_find(sharename, jobid);
	int result = 0;
	struct printif *current_printif = get_printer_fns( snum );

	if (!pjob)
		return False;

	/*
	 * If already deleting just return.
	 */

	if (pjob->status == LPQ_DELETING)
		return True;

	/* Hrm - we need to be able to cope with deleting a job before it
	   has reached the spooler.  Just mark it as LPQ_DELETING and
	   let the print_queue_update() code rmeove the record */


	if (pjob->sysjob == -1) {
		DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
	}

	/* Set the tdb entry to be deleting. */

	pjob->status = LPQ_DELETING;
	pjob_store(ev, msg_ctx, sharename, jobid, pjob);

	if (pjob->spooled && pjob->sysjob != -1)
	{
		result = (*(current_printif->job_delete))(
			lp_printername(snum),
			lp_lprmcommand(snum),
			pjob);

		/* Delete the tdb entry if the delete succeeded or the job hasn't
		   been spooled. */

		if (result == 0) {
			struct tdb_print_db *pdb = get_print_db_byname(sharename);
			int njobs = 1;

			if (!pdb)
				return False;
			pjob_delete(ev, msg_ctx, sharename, jobid);
			/* Ensure we keep a rough count of the number of total jobs... */
			tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
			release_print_db(pdb);
		}
	}

	remove_from_jobs_added( sharename, jobid );

	return (result == 0);
}

/****************************************************************************
 Return true if the current user owns the print job.
****************************************************************************/

static bool is_owner(const struct auth_serversupplied_info *server_info,
		     const char *servicename,
		     uint32 jobid)
{
	struct printjob *pjob = print_job_find(servicename, jobid);

	if (!pjob || !server_info)
		return False;

	return strequal(pjob->user, server_info->sanitized_username);
}

/****************************************************************************
 Delete a print job.
****************************************************************************/

WERROR print_job_delete(const struct auth_serversupplied_info *server_info,
			struct messaging_context *msg_ctx,
			int snum, uint32_t jobid)
{
	const char* sharename = lp_const_servicename(snum);
	struct printjob *pjob;
	bool 	owner;
	char 	*fname;

	owner = is_owner(server_info, lp_const_servicename(snum), jobid);

	/* Check access against security descriptor or whether the user
	   owns their job. */

	if (!owner &&
	    !print_access_check(server_info, msg_ctx, snum,
				JOB_ACCESS_ADMINISTER)) {
		DEBUG(3, ("delete denied by security descriptor\n"));

		/* BEGIN_ADMIN_LOG */
		sys_adminlog( LOG_ERR,
			      "Permission denied-- user not allowed to delete, \
pause, or resume print job. User name: %s. Printer name: %s.",
			      uidtoname(server_info->utok.uid),
			      lp_printername(snum) );
		/* END_ADMIN_LOG */

		return WERR_ACCESS_DENIED;
	}

	/*
	 * get the spooled filename of the print job
	 * if this works, then the file has not been spooled
	 * to the underlying print system.  Just delete the
	 * spool file & return.
	 */

	fname = print_job_fname(sharename, jobid);
	if (fname != NULL) {
		/* remove the spool file */
		DEBUG(10, ("print_job_delete: "
			   "Removing spool file [%s]\n", fname));
		if (unlink(fname) == -1) {
			return map_werror_from_unix(errno);
		}
	}

	if (!print_job_delete1(server_event_context(), msg_ctx, snum, jobid)) {
		return WERR_ACCESS_DENIED;
	}

	/* force update the database and say the delete failed if the
           job still exists */

	print_queue_update(msg_ctx, snum, True);

	pjob = print_job_find(sharename, jobid);
	if (pjob && (pjob->status != LPQ_DELETING)) {
		return WERR_ACCESS_DENIED;
	}

	return WERR_PRINTER_HAS_JOBS_QUEUED;
}

/****************************************************************************
 Pause a job.
****************************************************************************/

bool print_job_pause(const struct auth_serversupplied_info *server_info,
		     struct messaging_context *msg_ctx,
		     int snum, uint32 jobid, WERROR *errcode)
{
	const char* sharename = lp_const_servicename(snum);
	struct printjob *pjob;
	int ret = -1;
	struct printif *current_printif = get_printer_fns( snum );

	pjob = print_job_find(sharename, jobid);

	if (!pjob || !server_info) {
		DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
			(unsigned int)jobid ));
		return False;
	}

	if (!pjob->spooled || pjob->sysjob == -1) {
		DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
			(int)pjob->sysjob, (unsigned int)jobid ));
		return False;
	}

	if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
	    !print_access_check(server_info, msg_ctx, snum,
				JOB_ACCESS_ADMINISTER)) {
		DEBUG(3, ("pause denied by security descriptor\n"));

		/* BEGIN_ADMIN_LOG */
		sys_adminlog( LOG_ERR,
			"Permission denied-- user not allowed to delete, \
pause, or resume print job. User name: %s. Printer name: %s.",
			      uidtoname(server_info->utok.uid),
			      lp_printername(snum) );
		/* END_ADMIN_LOG */

		*errcode = WERR_ACCESS_DENIED;
		return False;
	}

	/* need to pause the spooled entry */
	ret = (*(current_printif->job_pause))(snum, pjob);

	if (ret != 0) {
		*errcode = WERR_INVALID_PARAM;
		return False;
	}

	/* force update the database */
	print_cache_flush(lp_const_servicename(snum));

	/* Send a printer notify message */

	notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
			  JOB_STATUS_PAUSED);

	/* how do we tell if this succeeded? */

	return True;
}

/****************************************************************************
 Resume a job.
****************************************************************************/

bool print_job_resume(const struct auth_serversupplied_info *server_info,
		      struct messaging_context *msg_ctx,
		      int snum, uint32 jobid, WERROR *errcode)
{
	const char *sharename = lp_const_servicename(snum);
	struct printjob *pjob;
	int ret;
	struct printif *current_printif = get_printer_fns( snum );

	pjob = print_job_find(sharename, jobid);

	if (!pjob || !server_info) {
		DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
			(unsigned int)jobid ));
		return False;
	}

	if (!pjob->spooled || pjob->sysjob == -1) {
		DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
			(int)pjob->sysjob, (unsigned int)jobid ));
		return False;
	}

	if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
	    !print_access_check(server_info, msg_ctx, snum,
				JOB_ACCESS_ADMINISTER)) {
		DEBUG(3, ("resume denied by security descriptor\n"));
		*errcode = WERR_ACCESS_DENIED;

		/* BEGIN_ADMIN_LOG */
		sys_adminlog( LOG_ERR,
			 "Permission denied-- user not allowed to delete, \
pause, or resume print job. User name: %s. Printer name: %s.",
			      uidtoname(server_info->utok.uid),
			      lp_printername(snum) );
		/* END_ADMIN_LOG */
		return False;
	}

	ret = (*(current_printif->job_resume))(snum, pjob);

	if (ret != 0) {
		*errcode = WERR_INVALID_PARAM;
		return False;
	}

	/* force update the database */
	print_cache_flush(lp_const_servicename(snum));

	/* Send a printer notify message */

	notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
			  JOB_STATUS_QUEUED);

	return True;
}

/****************************************************************************
 Write to a print file.
****************************************************************************/

ssize_t print_job_write(struct tevent_context *ev,
			struct messaging_context *msg_ctx,
			int snum, uint32 jobid, const char *buf, size_t size)
{
	const char* sharename = lp_const_servicename(snum);
	ssize_t return_code;
	struct printjob *pjob;

	pjob = print_job_find(sharename, jobid);

	if (!pjob)
		return -1;
	/* don't allow another process to get this info - it is meaningless */
	if (pjob->pid != sys_getpid())
		return -1;

	/* if SMBD is spooling this can't be allowed */
	if (pjob->status == PJOB_SMBD_SPOOLING) {
		return -1;
	}

	return_code = write_data(pjob->fd, buf, size);

	if (return_code>0) {
		pjob->size += size;
		pjob_store(ev, msg_ctx, sharename, jobid, pjob);
	}
	return return_code;
}

/****************************************************************************
 Get the queue status - do not update if db is out of date.
****************************************************************************/

static int get_queue_status(const char* sharename, print_status_struct *status)
{
	fstring keystr;
	TDB_DATA data;
	struct tdb_print_db *pdb = get_print_db_byname(sharename);
	int len;

	if (status) {
		ZERO_STRUCTP(status);
	}

	if (!pdb)
		return 0;

	if (status) {
		fstr_sprintf(keystr, "STATUS/%s", sharename);
		data = tdb_fetch_compat(pdb->tdb, string_tdb_data(keystr));
		if (data.dptr) {
			if (data.dsize == sizeof(print_status_struct))
				/* this memcpy is ok since the status struct was
				   not packed before storing it in the tdb */
				memcpy(status, data.dptr, sizeof(print_status_struct));
			SAFE_FREE(data.dptr);
		}
	}
	len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
	release_print_db(pdb);
	return (len == -1 ? 0 : len);
}

/****************************************************************************
 Determine the number of jobs in a queue.
****************************************************************************/

int print_queue_length(struct messaging_context *msg_ctx, int snum,
		       print_status_struct *pstatus)
{
	const char* sharename = lp_const_servicename( snum );
	print_status_struct status;
	int len;

	ZERO_STRUCT( status );

	/* make sure the database is up to date */
	if (print_cache_expired(lp_const_servicename(snum), True))
		print_queue_update(msg_ctx, snum, False);

	/* also fetch the queue status */
	memset(&status, 0, sizeof(status));
	len = get_queue_status(sharename, &status);

	if (pstatus)
		*pstatus = status;

	return len;
}

/***************************************************************************
 Allocate a jobid. Hold the lock for as short a time as possible.
***************************************************************************/

static WERROR allocate_print_jobid(struct tdb_print_db *pdb, int snum,
				   const char *sharename, uint32 *pjobid)
{
	int i;
	uint32 jobid;
	enum TDB_ERROR terr;
	int ret;

	*pjobid = (uint32)-1;

	for (i = 0; i < 3; i++) {
		/* Lock the database - only wait 20 seconds. */
		ret = tdb_lock_bystring_with_timeout(pdb->tdb,
						     "INFO/nextjob", 20);
		if (ret == -1) {
			DEBUG(0, ("allocate_print_jobid: "
				  "Failed to lock printing database %s\n",
				  sharename));
			terr = tdb_error(pdb->tdb);
			return ntstatus_to_werror(map_nt_error_from_tdb(terr));
		}

		if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
			terr = tdb_error(pdb->tdb);
			if (terr != TDB_ERR_NOEXIST) {
				DEBUG(0, ("allocate_print_jobid: "
					  "Failed to fetch INFO/nextjob "
					  "for print queue %s\n", sharename));
				tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
				return ntstatus_to_werror(map_nt_error_from_tdb(terr));
			}
			DEBUG(10, ("allocate_print_jobid: "
				   "No existing jobid in %s\n", sharename));
			jobid = 0;
		}

		DEBUG(10, ("allocate_print_jobid: "
			   "Read jobid %u from %s\n", jobid, sharename));

		jobid = NEXT_JOBID(jobid);

		ret = tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid);
		if (ret == -1) {
			terr = tdb_error(pdb->tdb);
			DEBUG(3, ("allocate_print_jobid: "
				  "Failed to store INFO/nextjob.\n"));
			tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
			return ntstatus_to_werror(map_nt_error_from_tdb(terr));
		}

		/* We've finished with the INFO/nextjob lock. */
		tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");

		if (!print_job_exists(sharename, jobid)) {
			break;
		}
		DEBUG(10, ("allocate_print_jobid: "
			   "Found jobid %u in %s\n", jobid, sharename));
	}

	if (i > 2) {
		DEBUG(0, ("allocate_print_jobid: "
			  "Failed to allocate a print job for queue %s\n",
			  sharename));
		/* Probably full... */
		return WERR_NO_SPOOL_SPACE;
	}

	/* Store a dummy placeholder. */
	{
		uint32_t tmp;
		TDB_DATA dum;
		dum.dptr = NULL;
		dum.dsize = 0;
		if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
			      TDB_INSERT) != 0) {
			DEBUG(3, ("allocate_print_jobid: "
				  "jobid (%d) failed to store placeholder.\n",
				  jobid ));
			terr = tdb_error(pdb->tdb);
			return ntstatus_to_werror(map_nt_error_from_tdb(terr));
		}
	}

	*pjobid = jobid;
	return WERR_OK;
}

/***************************************************************************
 Append a jobid to the 'jobs added' list.
***************************************************************************/

static bool add_to_jobs_added(struct tdb_print_db *pdb, uint32 jobid)
{
	TDB_DATA data;
	uint32 store_jobid;

	SIVAL(&store_jobid, 0, jobid);
	data.dptr = (uint8 *)&store_jobid;
	data.dsize = 4;

	DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));

	return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_added"),
			   data) == 0);
}


/***************************************************************************
 Do all checks needed to determine if we can start a job.
***************************************************************************/

static WERROR print_job_checks(const struct auth_serversupplied_info *server_info,
			       struct messaging_context *msg_ctx,
			       int snum, int *njobs)
{
	const char *sharename = lp_const_servicename(snum);
	uint64_t dspace, dsize;
	uint64_t minspace;
	int ret;

	if (!print_access_check(server_info, msg_ctx, snum,
				PRINTER_ACCESS_USE)) {
		DEBUG(3, ("print_job_checks: "
			  "job start denied by security descriptor\n"));
		return WERR_ACCESS_DENIED;
	}

	if (!print_time_access_check(server_info, msg_ctx, sharename)) {
		DEBUG(3, ("print_job_checks: "
			  "job start denied by time check\n"));
		return WERR_ACCESS_DENIED;
	}

	/* see if we have sufficient disk space */
	if (lp_minprintspace(snum)) {
		minspace = lp_minprintspace(snum);
		ret = sys_fsusage(lp_pathname(snum), &dspace, &dsize);
		if (ret == 0 && dspace < 2*minspace) {
			DEBUG(3, ("print_job_checks: "
				  "disk space check failed.\n"));
			return WERR_NO_SPOOL_SPACE;
		}
	}

	/* for autoloaded printers, check that the printcap entry still exists */
	if (lp_autoloaded(snum) && !pcap_printername_ok(sharename)) {
		DEBUG(3, ("print_job_checks: printer name %s check failed.\n",
			  sharename));
		return WERR_ACCESS_DENIED;
	}

	/* Insure the maximum queue size is not violated */
	*njobs = print_queue_length(msg_ctx, snum, NULL);
	if (*njobs > lp_maxprintjobs(snum)) {
		DEBUG(3, ("print_job_checks: Queue %s number of jobs (%d) "
			  "larger than max printjobs per queue (%d).\n",
			  sharename, *njobs, lp_maxprintjobs(snum)));
		return WERR_NO_SPOOL_SPACE;
	}

	return WERR_OK;
}

/***************************************************************************
 Create a job file.
***************************************************************************/

static WERROR print_job_spool_file(int snum, uint32_t jobid,
				   const char *output_file,
				   struct printjob *pjob)
{
	WERROR werr;
	SMB_STRUCT_STAT st;
	const char *path;
	int len;

	/* if this file is within the printer path, it means that smbd
	 * is spooling it and will pass us control when it is finished.
	 * Verify that the file name is ok, within path, and it is
	 * already already there */
	if (output_file) {
		path = lp_pathname(snum);
		len = strlen(path);
		if (strncmp(output_file, path, len) == 0 &&
		    (output_file[len - 1] == '/' || output_file[len] == '/')) {

			/* verify path is not too long */
			if (strlen(output_file) >= sizeof(pjob->filename)) {
				return WERR_INVALID_NAME;
			}

			/* verify that the file exists */
			if (sys_stat(output_file, &st, false) != 0) {
				return WERR_INVALID_NAME;
			}

			fstrcpy(pjob->filename, output_file);

			DEBUG(3, ("print_job_spool_file:"
				  "External spooling activated"));

			/* we do not open the file until spooling is done */
			pjob->fd = -1;
			pjob->status = PJOB_SMBD_SPOOLING;

			return WERR_OK;
		}
	}

	slprintf(pjob->filename, sizeof(pjob->filename)-1,
		 "%s/%s%.8u.XXXXXX", lp_pathname(snum),
		 PRINT_SPOOL_PREFIX, (unsigned int)jobid);
	pjob->fd = mkstemp(pjob->filename);

	if (pjob->fd == -1) {
		werr = map_werror_from_unix(errno);
		if (W_ERROR_EQUAL(werr, WERR_ACCESS_DENIED)) {
			/* Common setup error, force a report. */
			DEBUG(0, ("print_job_spool_file: "
				  "insufficient permissions to open spool "
				  "file %s.\n", pjob->filename));
		} else {
			/* Normal case, report at level 3 and above. */
			DEBUG(3, ("print_job_spool_file: "
				  "can't open spool file %s\n",
				  pjob->filename));
		}
		return werr;
	}

	return WERR_OK;
}

/***************************************************************************
 Start spooling a job - return the jobid.
***************************************************************************/

WERROR print_job_start(const struct auth_serversupplied_info *server_info,
		       struct messaging_context *msg_ctx,
		       const char *clientmachine,
		       int snum, const char *docname, const char *filename,
		       struct spoolss_DeviceMode *devmode, uint32_t *_jobid)
{
	uint32_t jobid;
	char *path;
	struct printjob pjob;
	const char *sharename = lp_const_servicename(snum);
	struct tdb_print_db *pdb = get_print_db_byname(sharename);
	int njobs;
	WERROR werr;

	if (!pdb) {
		return WERR_INTERNAL_DB_CORRUPTION;
	}

	path = lp_pathname(snum);

	werr = print_job_checks(server_info, msg_ctx, snum, &njobs);
	if (!W_ERROR_IS_OK(werr)) {
		release_print_db(pdb);
		return werr;
	}

	DEBUG(10, ("print_job_start: "
		   "Queue %s number of jobs (%d), max printjobs = %d\n",
		   sharename, njobs, lp_maxprintjobs(snum)));

	werr = allocate_print_jobid(pdb, snum, sharename, &jobid);
	if (!W_ERROR_IS_OK(werr)) {
		goto fail;
	}

	/* create the database entry */

	ZERO_STRUCT(pjob);

	pjob.pid = sys_getpid();
	pjob.sysjob = -1;
	pjob.fd = -1;
	pjob.starttime = time(NULL);
	pjob.status = LPQ_SPOOLING;
	pjob.size = 0;
	pjob.spooled = False;
	pjob.smbjob = True;
	pjob.devmode = devmode;

	fstrcpy(pjob.jobname, docname);

	fstrcpy(pjob.clientmachine, clientmachine);

	fstrcpy(pjob.user, lp_printjob_username(snum));
	standard_sub_advanced(sharename, server_info->sanitized_username,
			      path, server_info->utok.gid,
			      server_info->sanitized_username,
			      server_info->info3->base.domain.string,
			      pjob.user, sizeof(pjob.user)-1);
	/* ensure NULL termination */
	pjob.user[sizeof(pjob.user)-1] = '\0';

	fstrcpy(pjob.queuename, lp_const_servicename(snum));

	/* we have a job entry - now create the spool file */
	werr = print_job_spool_file(snum, jobid, filename, &pjob);
	if (!W_ERROR_IS_OK(werr)) {
		goto fail;
	}

	pjob_store(server_event_context(), msg_ctx, sharename, jobid, &pjob);

	/* Update the 'jobs added' entry used by print_queue_status. */
	add_to_jobs_added(pdb, jobid);

	/* Ensure we keep a rough count of the number of total jobs... */
	tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);

	release_print_db(pdb);

	*_jobid = jobid;
	return WERR_OK;

fail:
	if (jobid != -1) {
		pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
	}

	release_print_db(pdb);

	DEBUG(3, ("print_job_start: returning fail. "
		  "Error = %s\n", win_errstr(werr)));
	return werr;
}

/****************************************************************************
 Update the number of pages spooled to jobid
****************************************************************************/

void print_job_endpage(struct messaging_context *msg_ctx,
		       int snum, uint32 jobid)
{
	const char* sharename = lp_const_servicename(snum);
	struct printjob *pjob;

	pjob = print_job_find(sharename, jobid);
	if (!pjob)
		return;
	/* don't allow another process to get this info - it is meaningless */
	if (pjob->pid != sys_getpid())
		return;

	pjob->page_count++;
	pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
}

/****************************************************************************
 Print a file - called on closing the file. This spools the job.
 If normal close is false then we're tearing down the jobs - treat as an
 error.
****************************************************************************/

NTSTATUS print_job_end(struct messaging_context *msg_ctx, int snum,
		       uint32 jobid, enum file_close_type close_type)
{
	const char* sharename = lp_const_servicename(snum);
	struct printjob *pjob;
	int ret;
	SMB_STRUCT_STAT sbuf;
	struct printif *current_printif = get_printer_fns( snum );
	NTSTATUS status = NT_STATUS_UNSUCCESSFUL;

	pjob = print_job_find(sharename, jobid);

	if (!pjob) {
		return NT_STATUS_PRINT_CANCELLED;
	}

	if (pjob->spooled || pjob->pid != sys_getpid()) {
		return NT_STATUS_ACCESS_DENIED;
	}

	if (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) {
		if (pjob->status == PJOB_SMBD_SPOOLING) {
			/* take over the file now, smbd is done */
			if (sys_stat(pjob->filename, &sbuf, false) != 0) {
				status = map_nt_error_from_unix(errno);
				DEBUG(3, ("print_job_end: "
					  "stat file failed for jobid %d\n",
					  jobid));
				goto fail;
			}

			pjob->status = LPQ_SPOOLING;

		} else {

			if ((sys_fstat(pjob->fd, &sbuf, false) != 0)) {
				status = map_nt_error_from_unix(errno);
				close(pjob->fd);
				DEBUG(3, ("print_job_end: "
					  "stat file failed for jobid %d\n",
					  jobid));
				goto fail;
			}

			close(pjob->fd);
		}

		pjob->size = sbuf.st_ex_size;
	} else {

		/*
		 * Not a normal close, something has gone wrong. Cleanup.
		 */
		if (pjob->fd != -1) {
			close(pjob->fd);
		}
		goto fail;
	}

	/* Technically, this is not quite right. If the printer has a separator
	 * page turned on, the NT spooler prints the separator page even if the
	 * print job is 0 bytes. 010215 JRR */
	if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
		/* don't bother spooling empty files or something being deleted. */
		DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
			pjob->filename, pjob->size ? "deleted" : "zero length" ));
		unlink(pjob->filename);
		pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
		return NT_STATUS_OK;
	}

	ret = (*(current_printif->job_submit))(snum, pjob);

	if (ret) {
		status = NT_STATUS_PRINT_CANCELLED;
		goto fail;
	}

	/* The print job has been successfully handed over to the back-end */

	pjob->spooled = True;
	pjob->status = LPQ_QUEUED;
	pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);

	/* make sure the database is up to date */
	if (print_cache_expired(lp_const_servicename(snum), True))
		print_queue_update(msg_ctx, snum, False);

	return NT_STATUS_OK;

fail:

	/* The print job was not successfully started. Cleanup */
	/* Still need to add proper error return propagation! 010122:JRR */
	pjob->fd = -1;
	unlink(pjob->filename);
	pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
	return status;
}

/****************************************************************************
 Get a snapshot of jobs in the system without traversing.
****************************************************************************/

static bool get_stored_queue_info(struct messaging_context *msg_ctx,
				  struct tdb_print_db *pdb, int snum,
				  int *pcount, print_queue_struct **ppqueue)
{
	TDB_DATA data, cgdata, jcdata;
	print_queue_struct *queue = NULL;
	uint32 qcount = 0;
	uint32 extra_count = 0;
	uint32_t changed_count = 0;
	int total_count = 0;
	size_t len = 0;
	uint32 i;
	int max_reported_jobs = lp_max_reported_jobs(snum);
	bool ret = False;
	const char* sharename = lp_servicename(snum);

	/* make sure the database is up to date */
	if (print_cache_expired(lp_const_servicename(snum), True))
		print_queue_update(msg_ctx, snum, False);

	*pcount = 0;
	*ppqueue = NULL;

	ZERO_STRUCT(data);
	ZERO_STRUCT(cgdata);

	/* Get the stored queue data. */
	data = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));

	if (data.dptr && data.dsize >= sizeof(qcount))
		len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);

	/* Get the added jobs list. */
	cgdata = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_added"));
	if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
		extra_count = cgdata.dsize/4;

	/* Get the changed jobs list. */
	jcdata = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
	if (jcdata.dptr != NULL && (jcdata.dsize % 4 == 0))
		changed_count = jcdata.dsize / 4;

	DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));

	/* Allocate the queue size. */
	if (qcount == 0 && extra_count == 0)
		goto out;

	if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
		goto out;

	/* Retrieve the linearised queue data. */

	for( i  = 0; i < qcount; i++) {
		uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
		len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
				&qjob,
				&qsize,
				&qpage_count,
				&qstatus,
				&qpriority,
				&qtime,
				queue[i].fs_user,
				queue[i].fs_file);
		queue[i].job = qjob;
		queue[i].size = qsize;
		queue[i].page_count = qpage_count;
		queue[i].status = qstatus;
		queue[i].priority = qpriority;
		queue[i].time = qtime;
	}

	total_count = qcount;

	/* Add new jobids to the queue. */
	for( i  = 0; i < extra_count; i++) {
		uint32 jobid;
		struct printjob *pjob;

		jobid = IVAL(cgdata.dptr, i*4);
		DEBUG(5,("get_stored_queue_info: added job = %u\n", (unsigned int)jobid));
		pjob = print_job_find(lp_const_servicename(snum), jobid);
		if (!pjob) {
			DEBUG(5,("get_stored_queue_info: failed to find added job = %u\n", (unsigned int)jobid));
			remove_from_jobs_added(sharename, jobid);
			continue;
		}

		queue[total_count].job = jobid;
		queue[total_count].size = pjob->size;
		queue[total_count].page_count = pjob->page_count;
		queue[total_count].status = pjob->status;
		queue[total_count].priority = 1;
		queue[total_count].time = pjob->starttime;
		fstrcpy(queue[total_count].fs_user, pjob->user);
		fstrcpy(queue[total_count].fs_file, pjob->jobname);
		total_count++;
	}

	/* Update the changed jobids. */
	for (i = 0; i < changed_count; i++) {
		uint32_t jobid = IVAL(jcdata.dptr, i * 4);
		uint32_t j;
		bool found = false;

		for (j = 0; j < total_count; j++) {
			if (queue[j].job == jobid) {
				found = true;
				break;
			}
		}

		if (found) {
			struct printjob *pjob;

			DEBUG(5,("get_stored_queue_info: changed job: %u\n",
				 (unsigned int) jobid));

			pjob = print_job_find(sharename, jobid);
			if (pjob == NULL) {
				DEBUG(5,("get_stored_queue_info: failed to find "
					 "changed job = %u\n",
					 (unsigned int) jobid));
				remove_from_jobs_changed(sharename, jobid);
				continue;
			}

			queue[j].job = jobid;
			queue[j].size = pjob->size;
			queue[j].page_count = pjob->page_count;
			queue[j].status = pjob->status;
			queue[j].priority = 1;
			queue[j].time = pjob->starttime;
			fstrcpy(queue[j].fs_user, pjob->user);
			fstrcpy(queue[j].fs_file, pjob->jobname);

			DEBUG(5,("get_stored_queue_info: updated queue[%u], jobid: %u, jobname: %s\n",
				 (unsigned int) j, (unsigned int) jobid, pjob->jobname));
		}

		remove_from_jobs_changed(sharename, jobid);
	}

	/* Sort the queue by submission time otherwise they are displayed
	   in hash order. */

	TYPESAFE_QSORT(queue, total_count, printjob_comp);

	DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));

	if (max_reported_jobs && total_count > max_reported_jobs)
		total_count = max_reported_jobs;

	*ppqueue = queue;
	*pcount = total_count;

	ret = True;

  out:

	SAFE_FREE(data.dptr);
	SAFE_FREE(cgdata.dptr);
	return ret;
}

/****************************************************************************
 Get a printer queue listing.
 set queue = NULL and status = NULL if you just want to update the cache
****************************************************************************/

int print_queue_status(struct messaging_context *msg_ctx, int snum,
		       print_queue_struct **ppqueue,
		       print_status_struct *status)
{
	fstring keystr;
	TDB_DATA data, key;
	const char *sharename;
	struct tdb_print_db *pdb;
	int count = 0;

	/* make sure the database is up to date */

	if (print_cache_expired(lp_const_servicename(snum), True))
		print_queue_update(msg_ctx, snum, False);

	/* return if we are done */
	if ( !ppqueue || !status )
		return 0;

	*ppqueue = NULL;
	sharename = lp_const_servicename(snum);
	pdb = get_print_db_byname(sharename);

	if (!pdb)
		return 0;

	/*
	 * Fetch the queue status.  We must do this first, as there may
	 * be no jobs in the queue.
	 */

	ZERO_STRUCTP(status);
	slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
	key = string_tdb_data(keystr);

	data = tdb_fetch_compat(pdb->tdb, key);
	if (data.dptr) {
		if (data.dsize == sizeof(*status)) {
			/* this memcpy is ok since the status struct was
			   not packed before storing it in the tdb */
			memcpy(status, data.dptr, sizeof(*status));
		}
		SAFE_FREE(data.dptr);
	}

	/*
	 * Now, fetch the print queue information.  We first count the number
	 * of entries, and then only retrieve the queue if necessary.
	 */

	if (!get_stored_queue_info(msg_ctx, pdb, snum, &count, ppqueue)) {
		release_print_db(pdb);
		return 0;
	}

	release_print_db(pdb);
	return count;
}

/****************************************************************************
 Pause a queue.
****************************************************************************/

WERROR print_queue_pause(const struct auth_serversupplied_info *server_info,
			 struct messaging_context *msg_ctx, int snum)
{
	int ret;
	struct printif *current_printif = get_printer_fns( snum );

	if (!print_access_check(server_info, msg_ctx, snum,
				PRINTER_ACCESS_ADMINISTER)) {
		return WERR_ACCESS_DENIED;
	}


	become_root();

	ret = (*(current_printif->queue_pause))(snum);

	unbecome_root();

	if (ret != 0) {
		return WERR_INVALID_PARAM;
	}

	/* force update the database */
	print_cache_flush(lp_const_servicename(snum));

	/* Send a printer notify message */

	notify_printer_status(server_event_context(), msg_ctx, snum,
			      PRINTER_STATUS_PAUSED);

	return WERR_OK;
}

/****************************************************************************
 Resume a queue.
****************************************************************************/

WERROR print_queue_resume(const struct auth_serversupplied_info *server_info,
			  struct messaging_context *msg_ctx, int snum)
{
	int ret;
	struct printif *current_printif = get_printer_fns( snum );

	if (!print_access_check(server_info, msg_ctx, snum,
				PRINTER_ACCESS_ADMINISTER)) {
		return WERR_ACCESS_DENIED;
	}

	become_root();

	ret = (*(current_printif->queue_resume))(snum);

	unbecome_root();

	if (ret != 0) {
		return WERR_INVALID_PARAM;
	}

	/* make sure the database is up to date */
	if (print_cache_expired(lp_const_servicename(snum), True))
		print_queue_update(msg_ctx, snum, True);

	/* Send a printer notify message */

	notify_printer_status(server_event_context(), msg_ctx, snum,
			      PRINTER_STATUS_OK);

	return WERR_OK;
}

/****************************************************************************
 Purge a queue - implemented by deleting all jobs that we can delete.
****************************************************************************/

WERROR print_queue_purge(const struct auth_serversupplied_info *server_info,
			 struct messaging_context *msg_ctx, int snum)
{
	print_queue_struct *queue;
	print_status_struct status;
	int njobs, i;
	bool can_job_admin;

	/* Force and update so the count is accurate (i.e. not a cached count) */
	print_queue_update(msg_ctx, snum, True);

	can_job_admin = print_access_check(server_info,
					   msg_ctx,
					   snum,
					   JOB_ACCESS_ADMINISTER);
	njobs = print_queue_status(msg_ctx, snum, &queue, &status);

	if ( can_job_admin )
		become_root();

	for (i=0;i<njobs;i++) {
		bool owner = is_owner(server_info, lp_const_servicename(snum),
				      queue[i].job);

		if (owner || can_job_admin) {
			print_job_delete1(server_event_context(), msg_ctx,
					  snum, queue[i].job);
		}
	}

	if ( can_job_admin )
		unbecome_root();

	/* update the cache */
	print_queue_update(msg_ctx, snum, True);

	SAFE_FREE(queue);

	return WERR_OK;
}