summaryrefslogtreecommitdiff
path: root/source3/printing/printing.c
blob: d9bc13d03a274e3281a29b3bf6b00fc9b5c5e6cc (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
/* 
   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 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "includes.h"
#include "printing.h"

extern SIG_ATOMIC_T got_sig_term;
extern SIG_ATOMIC_T reload_after_sighup;

/* Current printer interface */
static BOOL remove_from_jobs_changed(int snum, 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. 
*/

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

static TDB_CONTEXT *rap_tdb;
static uint16 next_rap_jobid;

uint16 pjobid_to_rap(int snum, uint32 jobid)
{
	uint16 rap_jobid;
	TDB_DATA data, key;
	char jinfo[8];

	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;
	}

	SIVAL(&jinfo,0,(int32)snum);
	SIVAL(&jinfo,4,jobid);

	key.dptr = (char *)&jinfo;
	key.dsize = sizeof(jinfo);
	data = tdb_fetch(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;
	data.dptr = (char *)&rap_jobid;
	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, int *psnum, uint32 *pjobid)
{
	TDB_DATA data, key;

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

	if (!rap_tdb)
		return False;

	key.dptr = (char *)&rap_jobid;
	key.dsize = sizeof(rap_jobid);
	data = tdb_fetch(rap_tdb, key);
	if (data.dptr && data.dsize == 8) {
		*psnum = IVAL(data.dptr,0);
		*pjobid = IVAL(data.dptr,4);
		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;
}

static void rap_jobid_delete(int snum, uint32 jobid)
{
	TDB_DATA key, data;
	uint16 rap_jobid;
	char jinfo[8];

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

	if (!rap_tdb)
		return;

	SIVAL(&jinfo,0,(int32)snum);
	SIVAL(&jinfo,4,jobid);

	key.dptr = (char *)&jinfo;
	key.dsize = sizeof(jinfo);
	data = tdb_fetch(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);
	data.dptr = (char *)&rap_jobid;
	data.dsize = sizeof(rap_jobid);
	tdb_delete(rap_tdb, key);
	tdb_delete(rap_tdb, data);
}

static int get_queue_status(int, print_status_struct *);

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

BOOL print_backend_init(void)
{
	const char *sversion = "INFO/version";
	pstring printing_path;
	int services = lp_numservices();
	int snum;

	unlink(lock_path("printing.tdb"));
	pstrcpy(printing_path,lock_path("printing"));
	mkdir(printing_path,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, 0) == -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_traverse(pdb->tdb, tdb_traverse_delete_fn, NULL);
			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();
}

/****************************************************************************
 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( int snum )
{
	struct printif *printer_fns = &generic_printif;

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

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

static TDB_DATA print_key(uint32 jobid)
{
	static uint32 j;
	TDB_DATA ret;

	SIVAL(&j, 0, jobid);
	ret.dptr = (void *)&j;
	ret.dsize = sizeof(j);
	return ret;
}

/***********************************************************************
 unpack a pjob from a tdb buffer 
***********************************************************************/
 
int unpack_pjob( char* 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, "dddddddddffff",
				&pjpid,
				&pjsysjob,
				&pjfd,
				&pjstarttime,
				&pjstatus,
				&pjsize,
				&pjpage_count,
				&pjspooled,
				&pjsmbjob,
				pjob->filename,
				pjob->jobname,
				pjob->user,
				pjob->queuename);
				
	if ( len == -1 )
		return -1;
		
	if ( (used = unpack_devicemode(&pjob->nt_devmode, buf+len, buflen-len)) == -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(int snum, uint32 jobid)
{
	static struct printjob 	pjob;
	TDB_DATA 		ret;
	struct tdb_print_db 	*pdb = get_print_db_byname(lp_const_servicename(snum));
	

	if (!pdb)
		return NULL;

	ret = tdb_fetch(pdb->tdb, print_key(jobid));
	release_print_db(pdb);

	if (!ret.dptr)
		return NULL;
	
	if ( pjob.nt_devmode )
		free_nt_devicemode( &pjob.nt_devmode );
		
	ZERO_STRUCT( pjob );
	
	if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
		SAFE_FREE(ret.dptr);
		return NULL;
	}
	
	SAFE_FREE(ret.dptr);	
	return &pjob;
}

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

static uint32 sysjob_to_jobid_value;

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

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

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

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

		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;

	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)
			tdb_traverse(pdb->tdb, unixjob_traverse_fn, &unix_jobid);
		release_print_db(pdb);
		if (sysjob_to_jobid_value != (uint32)-1)
			return sysjob_to_jobid_value;
	}
	return (uint32)-1;
}

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

static struct {
	uint32 lpq_status;
	uint32 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 },
	{ LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
	{ -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;
}

static void pjob_store_notify(int snum, uint32 jobid, struct printjob *old_data,
			      struct printjob *new_data)
{
	BOOL new_job = False;

	if (!old_data)
		new_job = True;

	/* Job attributes that can't be changed.  We only send
	   notification for these on a new job. */

 	/* 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(snum, jobid, new_data->starttime);
		notify_job_username(snum, jobid, new_data->user);
	}

	if (new_job || !strequal(old_data->jobname, new_data->jobname))
		notify_job_name(snum, jobid, new_data->jobname);

	/* Job attributes of a new job or attributes that can be
	   modified. */

	if (new_job || !strequal(old_data->jobname, new_data->jobname))
		notify_job_name(snum, jobid, new_data->jobname);

	if (new_job || old_data->status != new_data->status)
		notify_job_status(snum, jobid, map_to_spoolss_status(new_data->status));

	if (new_job || old_data->size != new_data->size)
		notify_job_total_bytes(snum, jobid, new_data->size);

	if (new_job || old_data->page_count != new_data->page_count)
		notify_job_total_pages(snum, jobid, new_data->page_count);
}

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

static BOOL pjob_store(int snum, uint32 jobid, struct printjob *pjob)
{
	TDB_DATA 		old_data, new_data;
	BOOL 			ret = False;
	struct tdb_print_db 	*pdb = get_print_db_byname(lp_const_servicename(snum));
	char			*buf = NULL;
	int			len, newlen, buflen;
	

	if (!pdb)
		return False;

	/* Get old data */

	old_data = tdb_fetch(pdb->tdb, print_key(jobid));

	/* 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, "dddddddddffff",
				(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->queuename);

		len += pack_devicemode(pjob->nt_devmode, buf+len, buflen-len);
	
		if (buflen != len) {
			char *tb;

			tb = (char *)Realloc(buf, len);
			if (!tb) {
				DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
				goto done;
			}
			else 
				buf = tb;
			newlen = len;
		}
	} while ( buflen != len );
		
	
	/* Store new data */

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

	release_print_db(pdb);

	/* Send notify updates for what has changed */

	if ( ret ) {
		struct printjob old_pjob;

		if ( old_data.dsize )
		{
			if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
			{
				pjob_store_notify( snum, jobid, &old_pjob , pjob );
				free_nt_devicemode( &old_pjob.nt_devmode );
			}
		}
		else {
			/* new job */
			pjob_store_notify( snum, jobid, NULL, pjob );
		}
	}

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

	return ret;
}

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

void pjob_delete(int snum, uint32 jobid)
{
	struct printjob *pjob = print_job_find(snum, jobid);
	uint32 job_status = 0;
	struct tdb_print_db *pdb = get_print_db_byname(lp_const_servicename(snum));

	if (!pdb)
		return;

	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(snum, jobid, job_status);
	
	/* Remove from printing.tdb */

	tdb_delete(pdb->tdb, print_key(jobid));
	remove_from_jobs_changed(snum, jobid);
	release_print_db(pdb);
	rap_jobid_delete(snum, jobid);
}

/****************************************************************************
 Parse a file name from the system spooler to generate a jobid.
****************************************************************************/

static uint32 print_parse_jobid(char *fname)
{
	int jobid;

	if (strncmp(fname,PRINT_SPOOL_PREFIX,strlen(PRINT_SPOOL_PREFIX)) != 0)
		return (uint32)-1;
	fname += strlen(PRINT_SPOOL_PREFIX);

	jobid = atoi(fname);
	if (jobid <= 0)
		return (uint32)-1;

	return (uint32)jobid;
}

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

static void print_unix_job(int snum, 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(snum, 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 : lp_const_servicename(snum));

	pjob_store(snum, jobid, &pj);
}


struct traverse_struct {
	print_queue_struct *queue;
	int qcount, snum, maxcount, total_jobs;
	time_t lpq_time;
};

/****************************************************************************
 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;
	free_nt_devicemode( &pjob.nt_devmode );


	if (ts->snum != lp_servicenumber(pjob.queuename)) {
		/* this isn't for the queue we are looking at - this cannot happen with the split tdb's. JRA */
		return 0;
	}

	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->snum, 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(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->snum, 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 = print_parse_jobid(ts->queue[i].fs_file);
			if (jobid == curr_jobid)
				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->snum, 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(int snum)
{
	fstring key;
	const char *printername = lp_const_servicename(snum);
	struct tdb_print_db *pdb = get_print_db_byname(printername);

	if (!pdb)
		return;
	slprintf(key, sizeof(key)-1, "CACHE/%s", printername);
	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(fstring printer_name)
{
	fstring keystr;
	TDB_DATA data, key;
	pid_t updating_pid;
	struct tdb_print_db *pdb = get_print_db_byname(printer_name);

	if (!pdb)
		return (pid_t)-1;
	slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
    	key.dptr = keystr;
	key.dsize = strlen(keystr);

	data = tdb_fetch(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(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 printer_name, BOOL delete)
{
	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(printer_name);

	if (!pdb)
		return;

	slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
    	key.dptr = keystr;
	key.dsize = strlen(keystr);

	if (delete) {
		tdb_delete(pdb->tdb, key);
		release_print_db(pdb);
		return;
	}
	
	SIVAL( buffer, 0, updating_pid);
	data.dptr = (void *)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.
****************************************************************************/

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

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

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

	for (i = 0; i < pts->qcount; i++) {
		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 = 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++) {
		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);
	}

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

static TDB_DATA get_jobs_changed_data(struct tdb_print_db *pdb)
{
	TDB_DATA data, key;

	key.dptr = "INFO/jobs_changed";
	key.dsize = strlen(key.dptr);
	ZERO_STRUCT(data);

	data = tdb_fetch(pdb->tdb, key);
	if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
		SAFE_FREE(data.dptr);
		ZERO_STRUCT(data);
	}

	return data;
}

static void check_job_changed(int snum, 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_changed(snum, jobid);
	}
}

/****************************************************************************
 Update the internal database from the system print queue for a queue.
****************************************************************************/

static void print_queue_update_internal(int snum)
{
	int i, qcount;
	print_queue_struct *queue = NULL;
	print_status_struct status;
	print_status_struct old_status;
	struct printjob *pjob;
	struct traverse_struct tstruct;
	fstring keystr, printer_name, cachestr;
	TDB_DATA data, key;
	TDB_DATA jcdata;
	struct tdb_print_db *pdb;
	struct printif *current_printif = get_printer_fns( snum );

	fstrcpy(printer_name, lp_const_servicename(snum));
	pdb = get_print_db_byname(printer_name);
	if (!pdb)
		return;

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

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

	/* Lock the queue for the database update */

	slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", printer_name);
	/* Only wait 10 seconds for this. */
	if (tdb_lock_bystring(pdb->tdb, keystr, 10) == -1) {
		DEBUG(0,("print_queue_update: Failed to lock printer %s database\n", printer_name));
		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(printer_name) != -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(printer_name, False);

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

	tdb_unlock_bystring(pdb->tdb, keystr);

	/*
	 * 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", printer_name);
	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))(snum, &queue, &status);

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

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

	qsort(queue, qcount, sizeof(print_queue_struct),
	      QSORT_CAST(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_changed_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(snum, &queue[i], jobid);
			continue;
		}

		/* we have an active SMB print job - update its status */
		pjob = print_job_find(snum, 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(snum, &queue[i], jobid);
			continue;
		}

		pjob->sysjob = queue[i].job;
		pjob->status = queue[i].status;
		pjob_store(snum, jobid, pjob);
		check_job_changed(snum, 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 = snum;
	tstruct.total_jobs = 0;
	tstruct.lpq_time = time(NULL);

	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: printer %s INFO/total_jobs = %d\n",
				printer_name, tstruct.total_jobs ));

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

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

	/* store the new queue status structure */
	slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printer_name);
	key.dptr = keystr;
	key.dsize = strlen(keystr);

	status.qcount = qcount;
	data.dptr = (void *)&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", printer_name);
	tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));

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

/****************************************************************************
this is the receive function of the background lpq updater
****************************************************************************/
static void print_queue_receive(int msg_type, pid_t src, void *buf, size_t len)
{
	int snum;
	snum=*((int *)buf);
	print_queue_update_internal(snum);
}

static pid_t background_lpq_updater_pid = -1;

/****************************************************************************
main thread of the background lpq updater
****************************************************************************/
void start_background_queue(void)
{
	DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
	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);
	}

	if(background_lpq_updater_pid == 0) {
		/* Child. */
		DEBUG(5,("start_background_queue: background LPQ thread started\n"));

		claim_connection( NULL, "smbd lpq backend", 0, False, 
			FLAG_MSG_GENERAL|FLAG_MSG_SMBD|FLAG_MSG_PRINT_GENERAL);

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

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

		message_register(MSG_PRINTER_UPDATE, print_queue_receive);
		
		DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
		while (1) {
			pause();
			
			/* check for some essential signals first */
			
                        if (got_sig_term) {
                                exit_server("Caught TERM signal");
                        }

                        if (reload_after_sighup) {
                                change_to_root_user();
                                DEBUG(1,("Reloading services after SIGHUP\n"));
                                reload_services(False);
                                reload_after_sighup = 0;
                        }
			
			/* now check for messages */
			
			DEBUG(10,("start_background_queue: background LPQ thread got a message\n"));
			message_dispatch();
		}
	}
}

/****************************************************************************
update the internal database from the system print queue for a queue
****************************************************************************/
static void print_queue_update(int snum)
{
	/* 
	 * Make sure that the backgroup queueu process exists.  
	 * Otherwise just do the update ourselves 
	 */
	   
	if ( background_lpq_updater_pid != -1 ) {
		become_root();
		message_send_pid(background_lpq_updater_pid,
				 MSG_PRINTER_UPDATE, &snum, sizeof(snum),
				 False);
		unbecome_root();
	} else
		print_queue_update_internal( snum );
}

/****************************************************************************
 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(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 = 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) == -1) {
		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(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) == -1) {
		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(int snum, uint32 jobid)
{
	struct tdb_print_db *pdb = get_print_db_byname(lp_const_servicename(snum));
	BOOL ret;

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

/****************************************************************************
 Give the fd used for a jobid.
****************************************************************************/

int print_job_fd(int snum, uint32 jobid)
{
	struct printjob *pjob = print_job_find(snum, jobid);
	if (!pjob)
		return -1;
	/* don't allow another process to get this info - it is meaningless */
	if (pjob->pid != sys_getpid())
		return -1;
	return pjob->fd;
}

/****************************************************************************
 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(int snum, uint32 jobid)
{
	struct printjob *pjob = print_job_find(snum, 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.
****************************************************************************/

NT_DEVICEMODE *print_job_devmode(int snum, uint32 jobid)
{
	struct printjob *pjob = print_job_find(snum, jobid);
	
	if ( !pjob )
		return NULL;
		
	return pjob->nt_devmode;
}

/****************************************************************************
 Set the place in the queue for a job.
****************************************************************************/

BOOL print_job_set_place(int snum, uint32 jobid, int place)
{
	DEBUG(2,("print_job_set_place not implemented yet\n"));
	return False;
}

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

BOOL print_job_set_name(int snum, uint32 jobid, char *name)
{
	struct printjob *pjob = print_job_find(snum, jobid);
	if (!pjob || pjob->pid != sys_getpid())
		return False;

	fstrcpy(pjob->jobname, name);
	return pjob_store(snum, jobid, pjob);
}

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

static BOOL remove_from_jobs_changed(int snum, uint32 jobid)
{
	const char *printername = lp_const_servicename(snum);
	struct tdb_print_db *pdb = get_print_db_byname(printername);
	TDB_DATA data, key;
	size_t job_count, i;
	BOOL ret = False;
	BOOL gotlock = False;

	key.dptr = "INFO/jobs_changed";
	key.dsize = strlen(key.dptr);
	ZERO_STRUCT(data);

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

	gotlock = True;

	data = tdb_fetch(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) == -1)
				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;
}

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

static BOOL print_job_delete1(int snum, uint32 jobid)
{
	struct printjob *pjob = print_job_find(snum, 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. */

	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(snum, jobid, pjob);

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

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

	if (result == 0) {
		const char *printername = lp_const_servicename(snum);
		struct tdb_print_db *pdb = get_print_db_byname(printername);
		int njobs = 1;

		if (!pdb)
			return False;
		pjob_delete(snum, 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);
	}

	return (result == 0);
}

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

static BOOL is_owner(struct current_user *user, int snum, uint32 jobid)
{
	struct printjob *pjob = print_job_find(snum, jobid);
	user_struct *vuser;

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

	if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
		return strequal(pjob->user, vuser->user.smb_name);
	} else {
		return strequal(pjob->user, uidtoname(user->uid));
	}
}

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

BOOL print_job_delete(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
{
	BOOL 	owner, deleted;
	char 	*fname;

	*errcode = WERR_OK;
		
	owner = is_owner(user, snum, jobid);
	
	/* Check access against security descriptor or whether the user
	   owns their job. */

	if (!owner && 
	    !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
		DEBUG(3, ("delete 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(user->uid), PRINTERNAME(snum) );
		/* END_ADMIN_LOG */

		return False;
	}

	/* 
	 * 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.
	 */
	 
	if ( (fname = print_job_fname( snum, jobid )) != NULL )
	{
		/* remove the spool file */
		DEBUG(10,("print_job_delete: Removing spool file [%s]\n", fname ));
		if ( unlink( fname ) == -1 ) {
			*errcode = map_werror_from_unix(errno);
			return False;
		}
	}
	
	if (!print_job_delete1(snum, jobid)) {
		*errcode = WERR_ACCESS_DENIED;
		return False;
	}

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

	print_queue_update(snum);
	
	deleted = !print_job_exists(snum, jobid);
	if ( !deleted )
		*errcode = WERR_ACCESS_DENIED;

	return deleted;
}

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

BOOL print_job_pause(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
{
	struct printjob *pjob = print_job_find(snum, jobid);
	int ret = -1;
	struct printif *current_printif = get_printer_fns( snum );
	
	if (!pjob || !user) 
		return False;

	if (!pjob->spooled || pjob->sysjob == -1) 
		return False;

	if (!is_owner(user, snum, jobid) &&
	    !print_access_check(user, 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(user->uid), 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(snum);

	/* Send a printer notify message */

	notify_job_status(snum, jobid, JOB_STATUS_PAUSED);

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

	return True;
}

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

BOOL print_job_resume(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
{
	struct printjob *pjob = print_job_find(snum, jobid);
	int ret;
	struct printif *current_printif = get_printer_fns( snum );
	
	if (!pjob || !user)
		return False;

	if (!pjob->spooled || pjob->sysjob == -1)
		return False;

	if (!is_owner(user, snum, jobid) &&
	    !print_access_check(user, 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(user->uid), 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(snum);

	/* Send a printer notify message */

	notify_job_status(snum, jobid, JOB_STATUS_QUEUED);

	return True;
}

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

int print_job_write(int snum, uint32 jobid, const char *buf, int size)
{
	int return_code;
	struct printjob *pjob = print_job_find(snum, jobid);

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

	return_code = write(pjob->fd, buf, size);
	if (return_code>0) {
		pjob->size += size;
		pjob_store(snum, jobid, pjob);
	}
	return return_code;
}

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

static BOOL print_cache_expired(int snum)
{
	fstring key;
	time_t last_qscan_time, time_now = time(NULL);
	const char *printername = lp_const_servicename(snum);
	struct tdb_print_db *pdb = get_print_db_byname(printername);

	if (!pdb)
		return False;

	slprintf(key, sizeof(key), "CACHE/%s", printername);
	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)) {
		DEBUG(3, ("print cache expired for queue %s \
(last_qscan_time = %d, time now = %d, qcachetime = %d)\n", printername,
			(int)last_qscan_time, (int)time_now, (int)lp_lpqcachetime() ));
		release_print_db(pdb);
		return True;
	}
	release_print_db(pdb);
	return False;
}

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

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

	if (!pdb)
		return 0;

	if (status) {
		ZERO_STRUCTP(status);
		slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printername);
		key.dptr = keystr;
		key.dsize = strlen(keystr);
		data = tdb_fetch(pdb->tdb, key);
		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(int snum, print_status_struct *pstatus)
{
	print_status_struct status;
	int len;
 
	/* make sure the database is up to date */
	if (print_cache_expired(snum))
		print_queue_update(snum);
 
	/* also fetch the queue status */
	memset(&status, 0, sizeof(status));
	len = get_queue_status(snum, &status);

	if (pstatus)
		*pstatus = status;

	return len;
}

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

static BOOL allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char *printername, uint32 *pjobid)
{
	int i;
	uint32 jobid;

	*pjobid = (uint32)-1;

	for (i = 0; i < 3; i++) {
		/* Lock the database - only wait 20 seconds. */
		if (tdb_lock_bystring(pdb->tdb, "INFO/nextjob", 20) == -1) {
			DEBUG(0,("allocate_print_jobid: failed to lock printing database %s\n", printername ));
			return False;
		}

		if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
			if (tdb_error(pdb->tdb) != TDB_ERR_NOEXIST) {
				DEBUG(0, ("allocate_print_jobid: failed to fetch INFO/nextjob for print queue %s\n",
						printername ));
				return False;
			}
			jobid = 0;
		}

		jobid = NEXT_JOBID(jobid);

		if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
			DEBUG(3, ("allocate_print_jobid: failed to store INFO/nextjob.\n"));
			tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
			return False;
		}

		/* We've finished with the INFO/nextjob lock. */
		tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
				
		if (!print_job_exists(snum, jobid))
			break;
	}

	if (i > 2) {
		DEBUG(0, ("allocate_print_jobid: failed to allocate a print job for queue %s\n",
				printername ));
		/* Probably full... */
		errno = ENOSPC;
		return False;
	}

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

	*pjobid = jobid;
	return True;
}

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

static BOOL add_to_jobs_changed(struct tdb_print_db *pdb, uint32 jobid)
{
	TDB_DATA data, key;
	uint32 store_jobid;

	key.dptr = "INFO/jobs_changed";
	key.dsize = strlen(key.dptr);
	SIVAL(&store_jobid, 0, jobid);
	data.dptr = (char *)&store_jobid;
	data.dsize = 4;

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

	return (tdb_append(pdb->tdb, key, data) == 0);
}

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

uint32 print_job_start(struct current_user *user, int snum, char *jobname, NT_DEVICEMODE *nt_devmode )
{
	uint32 jobid;
	char *path;
	struct printjob pjob;
	user_struct *vuser;
	const char *printername = lp_const_servicename(snum);
	struct tdb_print_db *pdb = get_print_db_byname(printername);
	int njobs;

	errno = 0;

	if (!pdb)
		return (uint32)-1;

	if (!print_access_check(user, snum, PRINTER_ACCESS_USE)) {
		DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
		release_print_db(pdb);
		return (uint32)-1;
	}

	if (!print_time_access_check(snum)) {
		DEBUG(3, ("print_job_start: job start denied by time check\n"));
		release_print_db(pdb);
		return (uint32)-1;
	}

	path = lp_pathname(snum);

	/* see if we have sufficient disk space */
	if (lp_minprintspace(snum)) {
		SMB_BIG_UINT dspace, dsize;
		if (sys_fsusage(path, &dspace, &dsize) == 0 &&
		    dspace < 2*(SMB_BIG_UINT)lp_minprintspace(snum)) {
			DEBUG(3, ("print_job_start: disk space check failed.\n"));
			release_print_db(pdb);
			errno = ENOSPC;
			return (uint32)-1;
		}
	}

	/* for autoloaded printers, check that the printcap entry still exists */
	if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum), NULL)) {
		DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
		release_print_db(pdb);
		errno = ENOENT;
		return (uint32)-1;
	}

	/* Insure the maximum queue size is not violated */
	if ((njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
		DEBUG(3, ("print_job_start: Queue %s number of jobs (%d) larger than max printjobs per queue (%d).\n",
			printername, njobs, lp_maxprintjobs(snum) ));
		release_print_db(pdb);
		errno = ENOSPC;
		return (uint32)-1;
	}

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

	if (!allocate_print_jobid(pdb, snum, printername, &jobid))
		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.nt_devmode = nt_devmode;
	
	fstrcpy(pjob.jobname, jobname);

	if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
		fstrcpy(pjob.user, vuser->user.smb_name);
	} else {
		fstrcpy(pjob.user, uidtoname(user->uid));
	}

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

	/* we have a job entry - now create the spool file */
	slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX", 
		 path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
	pjob.fd = smb_mkstemp(pjob.filename);

	if (pjob.fd == -1) {
		if (errno == EACCES) {
			/* Common setup error, force a report. */
			DEBUG(0, ("print_job_start: insufficient permissions \
to open spool file %s.\n", pjob.filename));
		} else {
			/* Normal case, report at level 3 and above. */
			DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
			DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
		}
		goto fail;
	}

	pjob_store(snum, jobid, &pjob);

	/* Update the 'jobs changed' entry used by print_queue_status. */
	add_to_jobs_changed(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);

	return jobid;

 fail:
	if (jobid != -1)
		pjob_delete(snum, jobid);

	release_print_db(pdb);

	DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
	return (uint32)-1;
}

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

void print_job_endpage(int snum, uint32 jobid)
{
	struct printjob *pjob = print_job_find(snum, 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(snum, 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.
****************************************************************************/

BOOL print_job_end(int snum, uint32 jobid, BOOL normal_close)
{
	struct printjob *pjob = print_job_find(snum, jobid);
	int ret;
	SMB_STRUCT_STAT sbuf;
	struct printif *current_printif = get_printer_fns( snum );

	if (!pjob)
		return False;

	if (pjob->spooled || pjob->pid != sys_getpid())
		return False;

	if (normal_close && (sys_fstat(pjob->fd, &sbuf) == 0)) {
		pjob->size = sbuf.st_size;
		close(pjob->fd);
		pjob->fd = -1;
	} else {

		/* 
		 * Not a normal close or we couldn't stat the job file,
		 * so something has gone wrong. Cleanup.
		 */
		close(pjob->fd);
		pjob->fd = -1;
		DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
		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(snum, jobid);
		return True;
	}

	pjob->smbjob = jobid;

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

	if (ret)
		goto fail;

	/* The print job has been sucessfully handed over to the back-end */
	
	pjob->spooled = True;
	pjob->status = LPQ_QUEUED;
	pjob_store(snum, jobid, pjob);
	
	/* make sure the database is up to date */
	if (print_cache_expired(snum))
		print_queue_update(snum);
	
	return True;

fail:

	/* The print job was not succesfully started. Cleanup */
	/* Still need to add proper error return propagation! 010122:JRR */
	unlink(pjob->filename);
	pjob_delete(snum, jobid);
	return False;
}

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

static BOOL get_stored_queue_info(struct tdb_print_db *pdb, int snum, int *pcount, print_queue_struct **ppqueue)
{
	TDB_DATA data, key, cgdata;
	print_queue_struct *queue = NULL;
	uint32 qcount = 0;
	uint32 extra_count = 0;
	int total_count = 0;
	size_t len = 0;
	uint32 i;
	int max_reported_jobs = lp_max_reported_jobs(snum);
	BOOL ret = False;

	/* make sure the database is up to date */
	if (print_cache_expired(snum))
		print_queue_update(snum);
 
	*pcount = 0;
	*ppqueue = NULL;

	ZERO_STRUCT(data);
	ZERO_STRUCT(cgdata);
	key.dptr = "INFO/linear_queue_array";
	key.dsize = strlen(key.dptr);

	/* Get the stored queue data. */
	data = tdb_fetch(pdb->tdb, key);
	
	if (data.dptr && data.dsize >= sizeof(qcount))
		len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
		
	/* Get the changed jobs list. */
	key.dptr = "INFO/jobs_changed";
	key.dsize = strlen(key.dptr);

	cgdata = tdb_fetch(pdb->tdb, key);
	if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
		extra_count = cgdata.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 = (print_queue_struct *)malloc(sizeof(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 in the changed jobids. */
	for( i  = 0; i < extra_count; i++) {
		uint32 jobid;
		struct printjob *pjob;

		jobid = IVAL(cgdata.dptr, i*4);
		DEBUG(5,("get_stored_queue_info: changed job = %u\n", (unsigned int)jobid));
		pjob = print_job_find(snum, jobid);
		if (!pjob) {
			DEBUG(5,("get_stored_queue_info: failed to find changed job = %u\n", (unsigned int)jobid));
			remove_from_jobs_changed(snum, 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++;
	}

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

	qsort(queue, total_count, sizeof(print_queue_struct), QSORT_CAST(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(int snum, 
		       print_queue_struct **ppqueue,
		       print_status_struct *status)
{
	fstring keystr;
	TDB_DATA data, key;
	const char *printername;
	struct tdb_print_db *pdb;
	int count = 0;

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

	if (print_cache_expired(snum))
		print_queue_update(snum);

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

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

	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", printername);
	key.dptr = keystr;
	key.dsize = strlen(keystr);
	data = tdb_fetch(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(pdb, snum, &count, ppqueue)) {
		release_print_db(pdb);
		return 0;
	}

	release_print_db(pdb);
	return count;
}

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

BOOL print_queue_pause(struct current_user *user, int snum, WERROR *errcode)
{
	int ret;
	struct printif *current_printif = get_printer_fns( snum );
	
	if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
		*errcode = WERR_ACCESS_DENIED;
		return False;
	}

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

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

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

	/* Send a printer notify message */

	notify_printer_status(snum, PRINTER_STATUS_PAUSED);

	return True;
}

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

BOOL print_queue_resume(struct current_user *user, int snum, WERROR *errcode)
{
	int ret;
	struct printif *current_printif = get_printer_fns( snum );

	if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
		*errcode = WERR_ACCESS_DENIED;
		return False;
	}

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

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

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

	/* Send a printer notify message */

	notify_printer_status(snum, PRINTER_STATUS_OK);

	return True;
}

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

BOOL print_queue_purge(struct current_user *user, int snum, WERROR *errcode)
{
	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(snum);
	
	can_job_admin = print_access_check(user, snum, JOB_ACCESS_ADMINISTER);
	njobs = print_queue_status(snum, &queue, &status);

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

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

	SAFE_FREE(queue);

	return True;
}