Ensure we're root before opening a printer backend tdb.
[samba.git] / source / printing / printing.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 3.0
4    printing backend routines
5    Copyright (C) Andrew Tridgell 1992-2000
6    Copyright (C) Jeremy Allison 2002
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "printing.h"
24
25 /* Current printer interface */
26 static struct printif *current_printif = &generic_printif;
27
28 /* 
29    the printing backend revolves around a tdb database that stores the
30    SMB view of the print queue 
31    
32    The key for this database is a jobid - a internally generated number that
33    uniquely identifies a print job
34
35    reading the print queue involves two steps:
36      - possibly running lpq and updating the internal database from that
37      - reading entries from the database
38
39    jobids are assigned when a job starts spooling. 
40 */
41
42 /***************************************************************************
43  Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
44  bit RPC jobids.... JRA.
45 ***************************************************************************/
46
47 static TDB_CONTEXT *rap_tdb;
48 static uint16 next_rap_jobid;
49
50 uint16 pjobid_to_rap(int snum, uint32 jobid)
51 {
52         uint16 rap_jobid;
53         TDB_DATA data, key;
54         char jinfo[8];
55
56         if (!rap_tdb) {
57                 /* Create the in-memory tdb. */
58                 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
59                 if (!rap_tdb)
60                         return 0;
61         }
62
63         SIVAL(&jinfo,0,(int32)snum);
64         SIVAL(&jinfo,4,jobid);
65
66         key.dptr = (char *)&jinfo;
67         key.dsize = sizeof(jinfo);
68         data = tdb_fetch(rap_tdb, key);
69         if (data.dptr && data.dsize == sizeof(uint16)) {
70                 memcpy(&rap_jobid, data.dptr, sizeof(uint16));
71                 SAFE_FREE(data.dptr);
72                 return rap_jobid;
73         }
74         /* Not found - create and store mapping. */
75         rap_jobid = ++next_rap_jobid;
76         if (rap_jobid == 0)
77                 rap_jobid = ++next_rap_jobid;
78         data.dptr = (char *)&rap_jobid;
79         data.dsize = sizeof(rap_jobid);
80         tdb_store(rap_tdb, key, data, TDB_REPLACE);
81         tdb_store(rap_tdb, data, key, TDB_REPLACE);
82         return rap_jobid;
83 }
84
85 BOOL rap_to_pjobid(uint16 rap_jobid, int *psnum, uint32 *pjobid)
86 {
87         TDB_DATA data, key;
88         char jinfo[8];
89
90         if (!rap_tdb)
91                 return False;
92
93         key.dptr = (char *)&rap_jobid;
94         key.dsize = sizeof(rap_jobid);
95         data = tdb_fetch(rap_tdb, key);
96         if (data.dptr && data.dsize == sizeof(jinfo)) {
97                 *psnum = IVAL(&jinfo,0);
98                 *pjobid = IVAL(&jinfo,4);
99                 SAFE_FREE(data.dptr);
100                 return True;
101         }
102         return False;
103 }
104
105 static void rap_jobid_delete(int snum, uint32 jobid)
106 {
107         TDB_DATA key, data;
108         uint16 rap_jobid;
109         char jinfo[8];
110
111         if (!rap_tdb)
112                 return;
113
114         SIVAL(&jinfo,0,(int32)snum);
115         SIVAL(&jinfo,4,jobid);
116
117         key.dptr = (char *)&jinfo;
118         key.dsize = sizeof(jinfo);
119         data = tdb_fetch(rap_tdb, key);
120         if (!data.dptr || (data.dsize != sizeof(uint16)))
121                 return;
122
123         memcpy(&rap_jobid, data.dptr, sizeof(uint16));
124         SAFE_FREE(data.dptr);
125         data.dptr = (char *)&rap_jobid;
126         data.dsize = sizeof(rap_jobid);
127         tdb_delete(rap_tdb, key);
128         tdb_delete(rap_tdb, data);
129 }
130
131 static pid_t local_pid;
132
133 static int get_queue_status(int, print_status_struct *);
134
135 #define MAX_PRINT_DBS_OPEN 1
136
137 struct tdb_print_db {
138         struct tdb_print_db *next, *prev;
139         TDB_CONTEXT *tdb;
140         fstring printer_name;
141 };
142
143 static struct tdb_print_db *print_db_head;
144
145 /****************************************************************************
146   Function to find or create the printer specific job tdb given a printername.
147   Limits the number of tdb's open to MAX_PRINT_DBS_OPEN.
148 ****************************************************************************/
149
150 static struct tdb_print_db *get_print_db_byname(const char *printername)
151 {
152         struct tdb_print_db *p, *last_entry;
153         int num_open = 0;
154         pstring printdb_path;
155
156         for (p = print_db_head, last_entry = print_db_head; p; p = p->next) {
157                 if (p->tdb && strequal(p->printer_name, printername)) {
158                         DLIST_PROMOTE(print_db_head, p);
159                         return p;
160                 }
161                 num_open++;
162                 last_entry = p;
163         }
164         /* Not found. */
165         if (num_open >= MAX_PRINT_DBS_OPEN) {
166                 /* Recycle the last entry. */
167                 DLIST_PROMOTE(print_db_head, last_entry);
168                 if (print_db_head->tdb) {
169                         if (tdb_close(print_db_head->tdb)) {
170                                 DEBUG(0,("get_print_db: Failed to close tdb for printer %s\n",
171                                                         print_db_head->printer_name ));
172                                 return NULL;
173                         }
174                 }
175                 p = print_db_head;
176                 ZERO_STRUCTP(p);
177         } else {
178                 /* Create one. */
179                 p = (struct tdb_print_db *)malloc(sizeof(struct tdb_print_db));
180                 if (!p) {
181                         DEBUG(0,("get_print_db: malloc fail !\n"));
182                         return NULL;
183                 }
184                 ZERO_STRUCTP(p);
185                 DLIST_ADD(print_db_head, p);
186         }
187
188         pstrcpy(printdb_path, lock_path("printing/"));
189         pstrcat(printdb_path, printername);
190         pstrcat(printdb_path, ".tdb");
191
192         become_root();
193         p->tdb = tdb_open_log(printdb_path, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
194         unbecome_root();
195
196         if (!p->tdb) {
197                 DEBUG(0,("get_print_db: Failed to open printer backend database %s.\n",
198                                         printdb_path ));
199                 DLIST_REMOVE(print_db_head, p);
200                 SAFE_FREE(p);
201                 return NULL;
202         }
203         fstrcpy(p->printer_name, printername);
204         return p;
205 }
206
207 /****************************************************************************
208  Initialise the printing backend. Called once at startup. 
209  Does not survive a fork
210 ****************************************************************************/
211
212 BOOL print_backend_init(void)
213 {
214         char *sversion = "INFO/version";
215         pstring printing_path;
216         int services = lp_numservices();
217         int snum;
218
219         if (local_pid == sys_getpid())
220                 return True;
221
222         unlink(lock_path("printing.tdb"));
223         pstrcpy(printing_path,lock_path("printing"));
224         mkdir(printing_path,0755);
225
226         local_pid = sys_getpid();
227
228         /* handle a Samba upgrade */
229
230         for (snum = 0; snum < services; snum++) {
231                 struct tdb_print_db *pdb;
232                 if (!lp_print_ok(snum))
233                         continue;
234
235                 pdb = get_print_db_byname(lp_const_servicename(snum));
236                 if (!pdb)
237                         continue;
238                 tdb_lock_bystring(pdb->tdb, sversion);
239                 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
240                         tdb_traverse(pdb->tdb, tdb_traverse_delete_fn, NULL);
241                         tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
242                 }
243                 tdb_unlock_bystring(pdb->tdb, sversion);
244         }
245
246         /* select the appropriate printing interface... */
247 #ifdef HAVE_CUPS
248         if (strcmp(lp_printcapname(), "cups") == 0)
249                 current_printif = &cups_printif;
250 #endif /* HAVE_CUPS */
251
252         /* do NT print initialization... */
253         return nt_printing_init();
254 }
255
256 /****************************************************************************
257  Shut down printing backend. Called once at shutdown to close the tdb.
258 ****************************************************************************/
259
260 void printing_end(void)
261 {
262         struct tdb_print_db *p;
263
264         for (p = print_db_head; p; ) {
265                 struct tdb_print_db *next_p = p->next;
266                 if (p->tdb)
267                         tdb_close(p->tdb);
268                 DLIST_REMOVE(print_db_head, p);
269                 SAFE_FREE(p);
270                 p = next_p;
271         }
272 }
273
274 /****************************************************************************
275  Useful function to generate a tdb key.
276 ****************************************************************************/
277
278 static TDB_DATA print_key(uint32 jobid)
279 {
280         static uint32 j;
281         TDB_DATA ret;
282
283         j = jobid;
284         ret.dptr = (void *)&j;
285         ret.dsize = sizeof(j);
286         return ret;
287 }
288
289 /****************************************************************************
290  Useful function to find a print job in the database.
291 ****************************************************************************/
292
293 static struct printjob *print_job_find(int snum, uint32 jobid)
294 {
295         static struct printjob pjob;
296         TDB_DATA ret;
297         struct tdb_print_db *pdb = get_print_db_byname(lp_const_servicename(snum));
298
299         if (!pdb)
300                 return NULL;
301
302         ret = tdb_fetch(pdb->tdb, print_key(jobid));
303         if (!ret.dptr || ret.dsize != sizeof(pjob))
304                 return NULL;
305
306         memcpy(&pjob, ret.dptr, sizeof(pjob));
307         SAFE_FREE(ret.dptr);
308         return &pjob;
309 }
310
311 /* Convert a unix jobid to a smb jobid */
312
313 static uint32 sysjob_to_jobid_value;
314
315 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
316                                TDB_DATA data, void *state)
317 {
318         struct printjob *pjob = (struct printjob *)data.dptr;
319         int *sysjob = (int *)state;
320
321         if (key.dsize != sizeof(uint32))
322                 return 0;
323
324         if (*sysjob == pjob->sysjob) {
325                 uint32 *jobid = (uint32 *)key.dptr;
326
327                 sysjob_to_jobid_value = *jobid;
328                 return 1;
329         }
330
331         return 0;
332 }
333
334 /****************************************************************************
335  This is a *horribly expensive call as we have to iterate through all the
336  current printer tdb's. Don't do this often ! JRA.
337 ****************************************************************************/
338
339 uint32 sysjob_to_jobid(int unix_jobid)
340 {
341         int services = lp_numservices();
342         int snum;
343
344         sysjob_to_jobid_value = (uint32)-1;
345
346         for (snum = 0; snum < services; snum++) {
347                 struct tdb_print_db *pdb;
348                 if (!lp_print_ok(snum))
349                         continue;
350                 pdb = get_print_db_byname(lp_const_servicename(snum));
351                 if (pdb)
352                         tdb_traverse(pdb->tdb, unixjob_traverse_fn, &unix_jobid);
353                 if (sysjob_to_jobid_value != (uint32)-1)
354                         return sysjob_to_jobid_value;
355         }
356         return (uint32)-1;
357 }
358
359 /****************************************************************************
360  Send notifications based on what has changed after a pjob_store.
361 ****************************************************************************/
362
363 static struct {
364         uint32 lpq_status;
365         uint32 spoolss_status;
366 } lpq_to_spoolss_status_map[] = {
367         { LPQ_QUEUED, JOB_STATUS_QUEUED },
368         { LPQ_PAUSED, JOB_STATUS_PAUSED },
369         { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
370         { LPQ_PRINTING, JOB_STATUS_PRINTING },
371         { LPQ_DELETING, JOB_STATUS_DELETING },
372         { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
373         { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
374         { LPQ_PRINTED, JOB_STATUS_PRINTED },
375         { LPQ_DELETED, JOB_STATUS_DELETED },
376         { LPQ_BLOCKED, JOB_STATUS_BLOCKED },
377         { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
378         { -1, 0 }
379 };
380
381 /* Convert a lpq status value stored in printing.tdb into the
382    appropriate win32 API constant. */
383
384 static uint32 map_to_spoolss_status(uint32 lpq_status)
385 {
386         int i = 0;
387
388         while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
389                 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
390                         return lpq_to_spoolss_status_map[i].spoolss_status;
391                 i++;
392         }
393
394         return 0;
395 }
396
397 static void pjob_store_notify(int snum, uint32 jobid, struct printjob *old_data,
398                               struct printjob *new_data)
399 {
400         BOOL new_job = False;
401
402         if (!old_data)
403                 new_job = True;
404
405         /* Notify the job name first */
406
407         if (new_job || !strequal(old_data->jobname, new_data->jobname))
408                 notify_job_name(snum, jobid, new_data->jobname);
409
410         /* Job attributes that can't be changed.  We only send
411            notification for these on a new job. */
412
413         if (new_job) {
414                 notify_job_submitted(snum, jobid, new_data->starttime);
415                 notify_job_username(snum, jobid, new_data->user);
416         }
417
418         /* Job attributes of a new job or attributes that can be
419            modified. */
420
421         if (new_job || old_data->status != new_data->status)
422                 notify_job_status(snum, jobid, map_to_spoolss_status(new_data->status));
423
424         if (new_job || old_data->size != new_data->size)
425                 notify_job_total_bytes(snum, jobid, new_data->size);
426
427         if (new_job || old_data->page_count != new_data->page_count)
428                 notify_job_total_pages(snum, jobid, new_data->page_count);
429 }
430
431 /****************************************************************************
432  Store a job structure back to the database.
433 ****************************************************************************/
434
435 static BOOL pjob_store(int snum, uint32 jobid, struct printjob *pjob)
436 {
437         TDB_DATA old_data, new_data;
438         BOOL ret;
439         struct tdb_print_db *pdb = get_print_db_byname(lp_const_servicename(snum));
440
441         if (!pdb)
442                 return False;
443
444         /* Get old data */
445
446         old_data = tdb_fetch(pdb->tdb, print_key(jobid));
447
448         /* Store new data */
449
450         new_data.dptr = (void *)pjob;
451         new_data.dsize = sizeof(*pjob);
452         ret = (tdb_store(pdb->tdb, print_key(jobid), new_data, TDB_REPLACE) == 0);
453
454         /* Send notify updates for what has changed */
455
456         if (ret && (old_data.dsize == 0 || old_data.dsize == sizeof(*pjob))) {
457                 pjob_store_notify(
458                         snum, jobid, (struct printjob *)old_data.dptr,
459                         (struct printjob *)new_data.dptr);
460                 free(old_data.dptr);
461         }
462
463         return ret;
464 }
465
466 /****************************************************************************
467  Remove a job structure from the database.
468 ****************************************************************************/
469
470 static void pjob_delete(int snum, uint32 jobid)
471 {
472         struct printjob *pjob = print_job_find(snum, jobid);
473         uint32 job_status = 0;
474         struct tdb_print_db *pdb = get_print_db_byname(lp_const_servicename(snum));
475
476         if (!pdb)
477                 return;
478
479         if (!pjob) {
480                 DEBUG(5, ("pjob_delete(): we were asked to delete nonexistent job %u\n",
481                                         (unsigned int)jobid));
482                 return;
483         }
484
485         /* Send a notification that a job has been deleted */
486
487         job_status = map_to_spoolss_status(pjob->status);
488
489         /* We must cycle through JOB_STATUS_DELETING and
490            JOB_STATUS_DELETED for the port monitor to delete the job
491            properly. */
492         
493         job_status |= JOB_STATUS_DELETING;
494         notify_job_status(snum, jobid, job_status);
495         
496         job_status |= JOB_STATUS_DELETED;
497         notify_job_status(snum, jobid, job_status);
498
499         /* Remove from printing.tdb */
500
501         tdb_delete(pdb->tdb, print_key(jobid));
502         rap_jobid_delete(snum, jobid);
503 }
504
505 /****************************************************************************
506  Parse a file name from the system spooler to generate a jobid.
507 ****************************************************************************/
508
509 static uint32 print_parse_jobid(char *fname)
510 {
511         int jobid;
512
513         if (strncmp(fname,PRINT_SPOOL_PREFIX,strlen(PRINT_SPOOL_PREFIX)) != 0)
514                 return (uint32)-1;
515         fname += strlen(PRINT_SPOOL_PREFIX);
516
517         jobid = atoi(fname);
518         if (jobid <= 0)
519                 return (uint32)-1;
520
521         return (uint32)jobid;
522 }
523
524 /****************************************************************************
525  List a unix job in the print database.
526 ****************************************************************************/
527
528 static void print_unix_job(int snum, print_queue_struct *q)
529 {
530         uint32 jobid = q->job + UNIX_JOB_START;
531         struct printjob pj, *old_pj;
532
533         /* Preserve the timestamp on an existing unix print job */
534
535         old_pj = print_job_find(snum, jobid);
536
537         ZERO_STRUCT(pj);
538
539         pj.pid = (pid_t)-1;
540         pj.sysjob = q->job;
541         pj.fd = -1;
542         pj.starttime = old_pj ? old_pj->starttime : q->time;
543         pj.status = q->status;
544         pj.size = q->size;
545         pj.spooled = True;
546         pj.smbjob = False;
547         fstrcpy(pj.filename, "");
548         fstrcpy(pj.jobname, q->fs_file);
549         fstrcpy(pj.user, q->fs_user);
550         fstrcpy(pj.queuename, lp_const_servicename(snum));
551
552         pjob_store(snum, jobid, &pj);
553 }
554
555
556 struct traverse_struct {
557         print_queue_struct *queue;
558         int qcount, snum, maxcount, total_jobs;
559 };
560
561 /****************************************************************************
562  Utility fn to delete any jobs that are no longer active.
563 ****************************************************************************/
564
565 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
566 {
567         struct traverse_struct *ts = (struct traverse_struct *)state;
568         struct printjob pjob;
569         uint32 jobid;
570         int i;
571
572         if (data.dsize != sizeof(pjob) || key.dsize != sizeof(jobid))
573                 return 0;
574         memcpy(&jobid, key.dptr, sizeof(jobid));
575         memcpy(&pjob,  data.dptr, sizeof(pjob));
576
577         if (ts->snum != lp_servicenumber(pjob.queuename)) {
578                 /* this isn't for the queue we are looking at - this cannot happen with the split tdb's. JRA */
579                 return 0;
580         }
581
582         if (!pjob.smbjob) {
583                 /* remove a unix job if it isn't in the system queue any more */
584
585                 for (i=0;i<ts->qcount;i++) {
586                         uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
587                         if (jobid == u_jobid)
588                                 break;
589                 }
590                 if (i == ts->qcount)
591                         pjob_delete(ts->snum, jobid);
592                 else
593                         ts->total_jobs++;
594                 return 0;
595         }
596
597         /* maybe it hasn't been spooled yet */
598         if (!pjob.spooled) {
599                 /* if a job is not spooled and the process doesn't
600                    exist then kill it. This cleans up after smbd
601                    deaths */
602                 if (!process_exists(pjob.pid))
603                         pjob_delete(ts->snum, jobid);
604                 else
605                         ts->total_jobs++;
606                 return 0;
607         }
608
609         for (i=0;i<ts->qcount;i++) {
610                 uint32 curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
611                 if (jobid == curr_jobid)
612                         break;
613         }
614         
615         /* The job isn't in the system queue - we have to assume it has
616            completed, so delete the database entry. */
617
618         if (i == ts->qcount) {
619                 time_t cur_t = time(NULL);
620
621                 /* A race can occur between the time a job is spooled and
622                    when it appears in the lpq output.  This happens when
623                    the job is added to printing.tdb when another smbd
624                    running print_queue_update() has completed a lpq and
625                    is currently traversing the printing tdb and deleting jobs.
626                    A workaround is to not delete the job if it has been 
627                    submitted less than lp_lpqcachetime() seconds ago. */
628
629                 if ((cur_t - pjob.starttime) > lp_lpqcachetime())
630                         pjob_delete(ts->snum, jobid);
631                 else
632                         ts->total_jobs++;
633         }
634         else
635                 ts->total_jobs++;
636
637         return 0;
638 }
639
640 /****************************************************************************
641  Check if the print queue has been updated recently enough.
642 ****************************************************************************/
643
644 static void print_cache_flush(int snum)
645 {
646         fstring key;
647         const char *printername = lp_const_servicename(snum);
648         struct tdb_print_db *pdb = get_print_db_byname(printername);
649
650         if (!pdb)
651                 return;
652         slprintf(key, sizeof(key)-1, "CACHE/%s", printername);
653         tdb_store_int32(pdb->tdb, key, -1);
654 }
655
656 /****************************************************************************
657  Check if someone already thinks they are doing the update.
658 ****************************************************************************/
659
660 static pid_t get_updating_pid(fstring printer_name)
661 {
662         fstring keystr;
663         TDB_DATA data, key;
664         pid_t updating_pid;
665         struct tdb_print_db *pdb = get_print_db_byname(printer_name);
666
667         if (!pdb)
668                 return (pid_t)-1;
669         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
670         key.dptr = keystr;
671         key.dsize = strlen(keystr);
672
673         data = tdb_fetch(pdb->tdb, key);
674         if (!data.dptr || data.dsize != sizeof(pid_t))
675                 return (pid_t)-1;
676
677         memcpy(&updating_pid, data.dptr, sizeof(pid_t));
678         SAFE_FREE(data.dptr);
679
680         if (process_exists(updating_pid))
681                 return updating_pid;
682
683         return (pid_t)-1;
684 }
685
686 /****************************************************************************
687  Set the fact that we're doing the update, or have finished doing the update
688  in the tdb.
689 ****************************************************************************/
690
691 static void set_updating_pid(const fstring printer_name, BOOL delete)
692 {
693         fstring keystr;
694         TDB_DATA key;
695         TDB_DATA data;
696         pid_t updating_pid = sys_getpid();
697         struct tdb_print_db *pdb = get_print_db_byname(printer_name);
698
699         if (!pdb)
700                 return;
701
702         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
703         key.dptr = keystr;
704         key.dsize = strlen(keystr);
705
706         if (delete) {
707                 tdb_delete(pdb->tdb, key);
708                 return;
709         }
710         
711         data.dptr = (void *)&updating_pid;
712         data.dsize = sizeof(pid_t);
713
714         tdb_store(pdb->tdb, key, data, TDB_REPLACE);    
715 }
716
717 /****************************************************************************
718  Update the internal database from the system print queue for a queue.
719 ****************************************************************************/
720
721 static void print_queue_update(int snum)
722 {
723         int i, qcount;
724         print_queue_struct *queue = NULL;
725         print_status_struct status;
726         print_status_struct old_status;
727         struct printjob *pjob;
728         struct traverse_struct tstruct;
729         fstring keystr, printer_name, cachestr;
730         TDB_DATA data, key;
731         struct tdb_print_db *pdb;
732
733         fstrcpy(printer_name, lp_const_servicename(snum));
734         pdb = get_print_db_byname(printer_name);
735         if (!pdb)
736                 return;
737
738         /*
739          * Check to see if someone else is doing this update.
740          * This is essentially a mutex on the update.
741          */
742
743         if (get_updating_pid(printer_name) != -1)
744                 return;
745
746         /* Lock the queue for the database update */
747
748         slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", printer_name);
749         tdb_lock_bystring(pdb->tdb, keystr);
750
751         /*
752          * Ensure that no one else got in here.
753          * If the updating pid is still -1 then we are
754          * the winner.
755          */
756
757         if (get_updating_pid(printer_name) != -1) {
758                 /*
759                  * Someone else is doing the update, exit.
760                  */
761                 tdb_unlock_bystring(pdb->tdb, keystr);
762                 return;
763         }
764
765         /*
766          * We're going to do the update ourselves.
767          */
768
769         /* Tell others we're doing the update. */
770         set_updating_pid(printer_name, False);
771
772         /*
773          * Allow others to enter and notice we're doing
774          * the update.
775          */
776
777         tdb_unlock_bystring(pdb->tdb, keystr);
778
779         /*
780          * Update the cache time FIRST ! Stops others even
781          * attempting to get the lock and doing this
782          * if the lpq takes a long time.
783          */
784
785         slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", printer_name);
786         tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
787
788         /* get the current queue using the appropriate interface */
789         ZERO_STRUCT(status);
790
791         qcount = (*(current_printif->queue_get))(snum, &queue, &status);
792
793         DEBUG(3, ("%d job%s in queue for %s\n", qcount, (qcount != 1) ?
794                 "s" : "", printer_name));
795
796         /*
797           any job in the internal database that is marked as spooled
798           and doesn't exist in the system queue is considered finished
799           and removed from the database
800
801           any job in the system database but not in the internal database 
802           is added as a unix job
803
804           fill in any system job numbers as we go
805         */
806         for (i=0; i<qcount; i++) {
807                 uint32 jobid = print_parse_jobid(queue[i].fs_file);
808
809                 if (jobid == (uint32)-1) {
810                         /* assume its a unix print job */
811                         print_unix_job(snum, &queue[i]);
812                         continue;
813                 }
814
815                 /* we have an active SMB print job - update its status */
816                 pjob = print_job_find(snum, jobid);
817                 if (!pjob) {
818                         /* err, somethings wrong. Probably smbd was restarted
819                            with jobs in the queue. All we can do is treat them
820                            like unix jobs. Pity. */
821                         print_unix_job(snum, &queue[i]);
822                         continue;
823                 }
824
825                 pjob->sysjob = queue[i].job;
826                 pjob->status = queue[i].status;
827
828                 pjob_store(snum, jobid, pjob);
829         }
830
831         /* now delete any queued entries that don't appear in the
832            system queue */
833         tstruct.queue = queue;
834         tstruct.qcount = qcount;
835         tstruct.snum = snum;
836         tstruct.total_jobs = 0;
837
838         tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
839
840         SAFE_FREE(tstruct.queue);
841
842         tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
843
844         if( qcount != get_queue_status(snum, &old_status))
845                 DEBUG(10,("print_queue_update: queue status change %d jobs -> %d jobs for printer %s\n",
846                                         old_status.qcount, qcount, printer_name ));
847
848         /* store the new queue status structure */
849         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printer_name);
850         key.dptr = keystr;
851         key.dsize = strlen(keystr);
852
853         status.qcount = qcount;
854         data.dptr = (void *)&status;
855         data.dsize = sizeof(status);
856         tdb_store(pdb->tdb, key, data, TDB_REPLACE);    
857
858         /*
859          * Update the cache time again. We want to do this call
860          * as little as possible...
861          */
862
863         slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", printer_name);
864         tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
865
866         /* Delete our pid from the db. */
867         set_updating_pid(printer_name, True);
868 }
869
870 /****************************************************************************
871  Check if a jobid is valid. It is valid if it exists in the database.
872 ****************************************************************************/
873
874 BOOL print_job_exists(int snum, uint32 jobid)
875 {
876         struct tdb_print_db *pdb = get_print_db_byname(lp_const_servicename(snum));
877         if (!pdb)
878                 return False;
879         return tdb_exists(pdb->tdb, print_key(jobid));
880 }
881
882 /****************************************************************************
883  Give the fd used for a jobid.
884 ****************************************************************************/
885
886 int print_job_fd(int snum, uint32 jobid)
887 {
888         struct printjob *pjob = print_job_find(snum, jobid);
889         if (!pjob)
890                 return -1;
891         /* don't allow another process to get this info - it is meaningless */
892         if (pjob->pid != local_pid)
893                 return -1;
894         return pjob->fd;
895 }
896
897 /****************************************************************************
898  Give the filename used for a jobid.
899  Only valid for the process doing the spooling and when the job
900  has not been spooled.
901 ****************************************************************************/
902
903 char *print_job_fname(int snum, uint32 jobid)
904 {
905         struct printjob *pjob = print_job_find(snum, jobid);
906         if (!pjob || pjob->spooled || pjob->pid != local_pid)
907                 return NULL;
908         return pjob->filename;
909 }
910
911 /****************************************************************************
912  Set the place in the queue for a job.
913 ****************************************************************************/
914
915 BOOL print_job_set_place(int snum, uint32 jobid, int place)
916 {
917         DEBUG(2,("print_job_set_place not implemented yet\n"));
918         return False;
919 }
920
921 /****************************************************************************
922  Set the name of a job. Only possible for owner.
923 ****************************************************************************/
924
925 BOOL print_job_set_name(int snum, uint32 jobid, char *name)
926 {
927         struct printjob *pjob = print_job_find(snum, jobid);
928         if (!pjob || pjob->pid != local_pid)
929                 return False;
930
931         fstrcpy(pjob->jobname, name);
932         return pjob_store(snum, jobid, pjob);
933 }
934
935 /****************************************************************************
936  Delete a print job - don't update queue.
937 ****************************************************************************/
938
939 static BOOL print_job_delete1(int snum, uint32 jobid)
940 {
941         struct printjob *pjob = print_job_find(snum, jobid);
942         int result = 0;
943
944         if (!pjob)
945                 return False;
946
947         /*
948          * If already deleting just return.
949          */
950
951         if (pjob->status == LPQ_DELETING)
952                 return True;
953
954         /* Hrm - we need to be able to cope with deleting a job before it
955            has reached the spooler. */
956
957         if (pjob->sysjob == -1) {
958                 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
959         }
960
961         /* Set the tdb entry to be deleting. */
962
963         pjob->status = LPQ_DELETING;
964         pjob_store(snum, jobid, pjob);
965
966         if (pjob->spooled && pjob->sysjob != -1)
967                 result = (*(current_printif->job_delete))(snum, pjob);
968
969         /* Delete the tdb entry if the delete suceeded or the job hasn't
970            been spooled. */
971
972         if (result == 0)
973                 pjob_delete(snum, jobid);
974
975         return (result == 0);
976 }
977
978 /****************************************************************************
979  Return true if the current user owns the print job.
980 ****************************************************************************/
981
982 static BOOL is_owner(struct current_user *user, int snum, uint32 jobid)
983 {
984         struct printjob *pjob = print_job_find(snum, jobid);
985         user_struct *vuser;
986
987         if (!pjob || !user)
988                 return False;
989
990         if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
991                 return strequal(pjob->user, vuser->user.smb_name);
992         } else {
993                 return strequal(pjob->user, uidtoname(user->uid));
994         }
995 }
996
997 /****************************************************************************
998  Delete a print job.
999 ****************************************************************************/
1000
1001 BOOL print_job_delete(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1002 {
1003         BOOL owner;
1004
1005         owner = is_owner(user, snum, jobid);
1006         
1007         /* Check access against security descriptor or whether the user
1008            owns their job. */
1009
1010         if (!owner && 
1011             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1012                 DEBUG(3, ("delete denied by security descriptor\n"));
1013                 *errcode = WERR_ACCESS_DENIED;
1014                 return False;
1015         }
1016
1017         if (!print_job_delete1(snum, jobid)) 
1018                 return False;
1019
1020         /* force update the database and say the delete failed if the
1021            job still exists */
1022
1023         print_queue_update(snum);
1024
1025         return !print_job_exists(snum, jobid);
1026 }
1027
1028 /****************************************************************************
1029  Pause a job.
1030 ****************************************************************************/
1031
1032 BOOL print_job_pause(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1033 {
1034         struct printjob *pjob = print_job_find(snum, jobid);
1035         int ret = -1;
1036         
1037         if (!pjob || !user) 
1038                 return False;
1039
1040         if (!pjob->spooled || pjob->sysjob == -1) 
1041                 return False;
1042
1043         if (!is_owner(user, snum, jobid) &&
1044             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1045                 DEBUG(3, ("pause denied by security descriptor\n"));
1046                 *errcode = WERR_ACCESS_DENIED;
1047                 return False;
1048         }
1049
1050         /* need to pause the spooled entry */
1051         ret = (*(current_printif->job_pause))(snum, pjob);
1052
1053         if (ret != 0) {
1054                 *errcode = WERR_INVALID_PARAM;
1055                 return False;
1056         }
1057
1058         /* force update the database */
1059         print_cache_flush(snum);
1060
1061         /* Send a printer notify message */
1062
1063         notify_job_status(snum, jobid, JOB_STATUS_PAUSED);
1064
1065         /* how do we tell if this succeeded? */
1066
1067         return True;
1068 }
1069
1070 /****************************************************************************
1071  Resume a job.
1072 ****************************************************************************/
1073
1074 BOOL print_job_resume(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1075 {
1076         struct printjob *pjob = print_job_find(snum, jobid);
1077         int ret;
1078         
1079         if (!pjob || !user)
1080                 return False;
1081
1082         if (!pjob->spooled || pjob->sysjob == -1)
1083                 return False;
1084
1085         if (!is_owner(user, snum, jobid) &&
1086             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1087                 DEBUG(3, ("resume denied by security descriptor\n"));
1088                 *errcode = WERR_ACCESS_DENIED;
1089                 return False;
1090         }
1091
1092         ret = (*(current_printif->job_resume))(snum, pjob);
1093
1094         if (ret != 0) {
1095                 *errcode = WERR_INVALID_PARAM;
1096                 return False;
1097         }
1098
1099         /* force update the database */
1100         print_cache_flush(snum);
1101
1102         /* Send a printer notify message */
1103
1104         notify_job_status(snum, jobid, JOB_STATUS_QUEUED);
1105
1106         return True;
1107 }
1108
1109 /****************************************************************************
1110  Write to a print file.
1111 ****************************************************************************/
1112
1113 int print_job_write(int snum, uint32 jobid, const char *buf, int size)
1114 {
1115         int return_code;
1116         struct printjob *pjob = print_job_find(snum, jobid);
1117
1118         if (!pjob)
1119                 return -1;
1120         /* don't allow another process to get this info - it is meaningless */
1121         if (pjob->pid != local_pid)
1122                 return -1;
1123
1124         return_code = write(pjob->fd, buf, size);
1125         if (return_code>0) {
1126                 pjob->size += size;
1127                 pjob_store(snum, jobid, pjob);
1128         }
1129         return return_code;
1130 }
1131
1132 /****************************************************************************
1133  Check if the print queue has been updated recently enough.
1134 ****************************************************************************/
1135
1136 static BOOL print_cache_expired(int snum)
1137 {
1138         fstring key;
1139         time_t last_qscan_time, time_now = time(NULL);
1140         const char *printername = lp_const_servicename(snum);
1141         struct tdb_print_db *pdb = get_print_db_byname(printername);
1142
1143         if (!pdb)
1144                 return False;
1145
1146         slprintf(key, sizeof(key), "CACHE/%s", printername);
1147         last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1148
1149         /*
1150          * Invalidate the queue for 3 reasons.
1151          * (1). last queue scan time == -1.
1152          * (2). Current time - last queue scan time > allowed cache time.
1153          * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1154          * This last test picks up machines for which the clock has been moved
1155          * forward, an lpq scan done and then the clock moved back. Otherwise
1156          * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1157          */
1158
1159         if (last_qscan_time == ((time_t)-1) || (time_now - last_qscan_time) >= lp_lpqcachetime() ||
1160                         last_qscan_time > (time_now + MAX_CACHE_VALID_TIME)) {
1161                 DEBUG(3, ("print cache expired for queue %s \
1162 (last_qscan_time = %d, time now = %d, qcachetime = %d)\n", printername,
1163                         (int)last_qscan_time, (int)time_now, (int)lp_lpqcachetime() ));
1164                 return True;
1165         }
1166         return False;
1167 }
1168
1169 /****************************************************************************
1170  Get the queue status - do not update if db is out of date.
1171 ****************************************************************************/
1172
1173 static int get_queue_status(int snum, print_status_struct *status)
1174 {
1175         fstring keystr;
1176         TDB_DATA data, key;
1177         const char *printername = lp_const_servicename(snum);
1178         struct tdb_print_db *pdb = get_print_db_byname(printername);
1179         if (!pdb)
1180                 return 0;
1181
1182         ZERO_STRUCTP(status);
1183         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printername);
1184         key.dptr = keystr;
1185         key.dsize = strlen(keystr);
1186         data = tdb_fetch(pdb->tdb, key);
1187         if (data.dptr) {
1188                 if (data.dsize == sizeof(print_status_struct)) {
1189                         memcpy(status, data.dptr, sizeof(print_status_struct));
1190                 }
1191                 SAFE_FREE(data.dptr);
1192         }
1193         return status->qcount;
1194 }
1195
1196 /****************************************************************************
1197  Determine the number of jobs in a queue.
1198 ****************************************************************************/
1199
1200 int print_queue_length(int snum, print_status_struct *pstatus)
1201 {
1202         print_status_struct status;
1203         int len;
1204  
1205         /* make sure the database is up to date */
1206         if (print_cache_expired(snum))
1207                 print_queue_update(snum);
1208  
1209         /* also fetch the queue status */
1210         memset(&status, 0, sizeof(status));
1211         len = get_queue_status(snum, &status);
1212         if (pstatus)
1213                 *pstatus = status;
1214         return len;
1215 }
1216
1217 /****************************************************************************
1218  Determine the number of jobs in all queues. This is very expensive. Don't
1219  call ! JRA.
1220 ****************************************************************************/
1221
1222 static int get_total_jobs(void)
1223 {
1224         int total_jobs;
1225         int snum;
1226         int services = lp_numservices();
1227
1228         for (snum = 0; snum < services; snum++) {
1229                 struct tdb_print_db *pdb;
1230                 int jobs;
1231
1232                 if (!lp_print_ok(snum))
1233                         continue;
1234
1235                 pdb = get_print_db_byname(lp_const_servicename(snum));
1236                 if (!pdb)
1237                         continue;
1238
1239                 /* make sure the database is up to date */
1240                 if (print_cache_expired(snum))
1241                         print_queue_update(snum);
1242
1243                 jobs = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
1244                 if (jobs > 0)
1245                         total_jobs += jobs;
1246         }
1247         return total_jobs;
1248 }
1249
1250 /***************************************************************************
1251  Start spooling a job - return the jobid.
1252 ***************************************************************************/
1253
1254 uint32 print_job_start(struct current_user *user, int snum, char *jobname)
1255 {
1256         uint32 jobid;
1257         char *path;
1258         struct printjob pjob;
1259         int next_jobid;
1260         user_struct *vuser;
1261         int njobs = 0;
1262         const char *printername = lp_const_servicename(snum);
1263         struct tdb_print_db *pdb = get_print_db_byname(printername);
1264
1265         errno = 0;
1266
1267         if (!pdb)
1268                 return (uint32)-1;
1269
1270         if (!print_access_check(user, snum, PRINTER_ACCESS_USE)) {
1271                 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
1272                 return (uint32)-1;
1273         }
1274
1275         if (!print_time_access_check(snum)) {
1276                 DEBUG(3, ("print_job_start: job start denied by time check\n"));
1277                 return (uint32)-1;
1278         }
1279
1280         path = lp_pathname(snum);
1281
1282         /* see if we have sufficient disk space */
1283         if (lp_minprintspace(snum)) {
1284                 SMB_BIG_UINT dspace, dsize;
1285                 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
1286                     dspace < 2*(SMB_BIG_UINT)lp_minprintspace(snum)) {
1287                         DEBUG(3, ("print_job_start: disk space check failed.\n"));
1288                         errno = ENOSPC;
1289                         return (uint32)-1;
1290                 }
1291         }
1292
1293         /* for autoloaded printers, check that the printcap entry still exists */
1294         if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum), NULL)) {
1295                 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
1296                 errno = ENOENT;
1297                 return (uint32)-1;
1298         }
1299
1300         /* Insure the maximum queue size is not violated */
1301         if (lp_maxprintjobs(snum) && (njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
1302                 DEBUG(3, ("print_job_start: number of jobs (%d) larger than max printjobs per queue (%d).\n",
1303                         njobs, lp_maxprintjobs(snum) ));
1304                 errno = ENOSPC;
1305                 return (uint32)-1;
1306         }
1307
1308         /* Insure the maximum print jobs in the system is not violated */
1309         if (lp_totalprintjobs() && get_total_jobs() > lp_totalprintjobs()) {
1310                 DEBUG(3, ("print_job_start: number of jobs (%d) larger than max printjobs per system (%d).\n",
1311                         njobs, lp_totalprintjobs() ));
1312                 errno = ENOSPC;
1313                 return (uint32)-1;
1314         }
1315
1316         /* create the database entry */
1317         ZERO_STRUCT(pjob);
1318         pjob.pid = local_pid;
1319         pjob.sysjob = -1;
1320         pjob.fd = -1;
1321         pjob.starttime = time(NULL);
1322         pjob.status = LPQ_SPOOLING;
1323         pjob.size = 0;
1324         pjob.spooled = False;
1325         pjob.smbjob = True;
1326
1327         fstrcpy(pjob.jobname, jobname);
1328
1329         if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
1330                 fstrcpy(pjob.user, vuser->user.smb_name);
1331         } else {
1332                 fstrcpy(pjob.user, uidtoname(user->uid));
1333         }
1334
1335         fstrcpy(pjob.queuename, lp_const_servicename(snum));
1336
1337         /* lock the database */
1338         tdb_lock_bystring(pdb->tdb, "INFO/nextjob");
1339
1340         next_jobid = tdb_fetch_int32(pdb->tdb, "INFO/nextjob");
1341         if (next_jobid == -1)
1342                 next_jobid = 1;
1343
1344         for (jobid = NEXT_JOBID(next_jobid); jobid != next_jobid; jobid = NEXT_JOBID(jobid)) {
1345                 if (!print_job_exists(snum, jobid))
1346                         break;
1347         }
1348         if (jobid == next_jobid || !pjob_store(snum, jobid, &pjob)) {
1349                 DEBUG(3, ("print_job_start: either jobid (%d)==next_jobid(%d) or pjob_store failed.\n",
1350                                 jobid, next_jobid ));
1351                 jobid = -1;
1352                 goto fail;
1353         }
1354
1355         if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
1356                 DEBUG(3, ("print_job_start: failed to store INFO/nextjob.\n"));
1357                 jobid = -1;
1358                 goto fail;
1359         }
1360
1361         /* we have a job entry - now create the spool file */
1362         slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX", 
1363                  path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
1364         pjob.fd = smb_mkstemp(pjob.filename);
1365
1366         if (pjob.fd == -1) {
1367                 if (errno == EACCES) {
1368                         /* Common setup error, force a report. */
1369                         DEBUG(0, ("print_job_start: insufficient permissions \
1370 to open spool file %s.\n", pjob.filename));
1371                 } else {
1372                         /* Normal case, report at level 3 and above. */
1373                         DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
1374                         DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
1375                 }
1376                 goto fail;
1377         }
1378
1379         pjob_store(snum, jobid, &pjob);
1380
1381         tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
1382
1383         /*
1384          * If the printer is marked as postscript output a leading
1385          * file identifier to ensure the file is treated as a raw
1386          * postscript file.
1387          * This has a similar effect as CtrlD=0 in WIN.INI file.
1388          * tim@fsg.com 09/06/94
1389          */
1390         if (lp_postscript(snum)) {
1391                 print_job_write(snum, jobid, "%!\n",3);
1392         }
1393
1394         return jobid;
1395
1396  fail:
1397         if (jobid != -1)
1398                 pjob_delete(snum, jobid);
1399
1400         tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
1401
1402         DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
1403         return -1;
1404 }
1405
1406 /****************************************************************************
1407  Update the number of pages spooled to jobid
1408 ****************************************************************************/
1409
1410 void print_job_endpage(int snum, uint32 jobid)
1411 {
1412         struct printjob *pjob = print_job_find(snum, jobid);
1413         if (!pjob)
1414                 return;
1415         /* don't allow another process to get this info - it is meaningless */
1416         if (pjob->pid != local_pid)
1417                 return;
1418
1419         pjob->page_count++;
1420         pjob_store(snum, jobid, pjob);
1421 }
1422
1423 /****************************************************************************
1424  Print a file - called on closing the file. This spools the job.
1425  If normal close is false then we're tearing down the jobs - treat as an
1426  error.
1427 ****************************************************************************/
1428
1429 BOOL print_job_end(int snum, uint32 jobid, BOOL normal_close)
1430 {
1431         struct printjob *pjob = print_job_find(snum, jobid);
1432         int ret;
1433         SMB_STRUCT_STAT sbuf;
1434
1435         if (!pjob)
1436                 return False;
1437
1438         if (pjob->spooled || pjob->pid != local_pid)
1439                 return False;
1440
1441         if (normal_close && (sys_fstat(pjob->fd, &sbuf) == 0)) {
1442                 pjob->size = sbuf.st_size;
1443                 close(pjob->fd);
1444                 pjob->fd = -1;
1445         } else {
1446
1447                 /* 
1448                  * Not a normal close or we couldn't stat the job file,
1449                  * so something has gone wrong. Cleanup.
1450                  */
1451                 close(pjob->fd);
1452                 pjob->fd = -1;
1453                 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
1454                 goto fail;
1455         }
1456
1457         /* Technically, this is not quite right. If the printer has a separator
1458          * page turned on, the NT spooler prints the separator page even if the
1459          * print job is 0 bytes. 010215 JRR */
1460         if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
1461                 /* don't bother spooling empty files or something being deleted. */
1462                 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
1463                         pjob->filename, pjob->size ? "deleted" : "zero length" ));
1464                 unlink(pjob->filename);
1465                 pjob_delete(snum, jobid);
1466                 return True;
1467         }
1468
1469         ret = (*(current_printif->job_submit))(snum, pjob);
1470
1471         if (ret)
1472                 goto fail;
1473
1474         /* The print job has been sucessfully handed over to the back-end */
1475         
1476         pjob->spooled = True;
1477         pjob->status = LPQ_QUEUED;
1478         pjob_store(snum, jobid, pjob);
1479         
1480         /* make sure the database is up to date */
1481         if (print_cache_expired(snum))
1482                 print_queue_update(snum);
1483         
1484         return True;
1485
1486 fail:
1487
1488         /* The print job was not succesfully started. Cleanup */
1489         /* Still need to add proper error return propagation! 010122:JRR */
1490         unlink(pjob->filename);
1491         pjob_delete(snum, jobid);
1492         return False;
1493 }
1494
1495 /****************************************************************************
1496  Utility fn to enumerate the print queue.
1497 ****************************************************************************/
1498
1499 static int traverse_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1500 {
1501         struct traverse_struct *ts = (struct traverse_struct *)state;
1502         struct printjob pjob;
1503         int i;
1504         uint32 jobid;
1505
1506         if (data.dsize != sizeof(pjob) || key.dsize != sizeof(int))
1507                 return 0;
1508         memcpy(&jobid, key.dptr, sizeof(jobid));
1509         memcpy(&pjob,  data.dptr, sizeof(pjob));
1510
1511         /* maybe it isn't for this queue */
1512         if (ts->snum != lp_servicenumber(pjob.queuename))
1513                 return 0;
1514
1515         if (ts->qcount >= ts->maxcount)
1516                 return 0;
1517
1518         i = ts->qcount;
1519
1520         ts->queue[i].job = jobid;
1521         ts->queue[i].size = pjob.size;
1522         ts->queue[i].page_count = pjob.page_count;
1523         ts->queue[i].status = pjob.status;
1524         ts->queue[i].priority = 1;
1525         ts->queue[i].time = pjob.starttime;
1526         fstrcpy(ts->queue[i].fs_user, pjob.user);
1527         fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1528
1529         ts->qcount++;
1530
1531         return 0;
1532 }
1533
1534 struct traverse_count_struct {
1535         int snum, count;
1536 };
1537
1538 /****************************************************************************
1539  Utility fn to count the number of entries in the print queue.
1540 ****************************************************************************/
1541
1542 static int traverse_count_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1543 {
1544         struct traverse_count_struct *ts = (struct traverse_count_struct *)state;
1545         struct printjob pjob;
1546         uint32 jobid;
1547
1548         if (data.dsize != sizeof(pjob) || key.dsize != sizeof(int))
1549                 return 0;
1550         memcpy(&jobid, key.dptr, sizeof(jobid));
1551         memcpy(&pjob,  data.dptr, sizeof(pjob));
1552
1553         /* maybe it isn't for this queue - this cannot happen with the tdb/printer code. JRA */
1554         if (ts->snum != lp_servicenumber(pjob.queuename))
1555                 return 0;
1556
1557         ts->count++;
1558
1559         return 0;
1560 }
1561
1562 /****************************************************************************
1563  Sort print jobs by submittal time.
1564 ****************************************************************************/
1565
1566 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1567 {
1568         /* Silly cases */
1569
1570         if (!j1 && !j2)
1571                 return 0;
1572         if (!j1)
1573                 return -1;
1574         if (!j2)
1575                 return 1;
1576
1577         /* Sort on job start time */
1578
1579         if (j1->time == j2->time)
1580                 return 0;
1581         return (j1->time > j2->time) ? 1 : -1;
1582 }
1583
1584 /****************************************************************************
1585  Get a printer queue listing.
1586 ****************************************************************************/
1587
1588 int print_queue_status(int snum, 
1589                        print_queue_struct **queue,
1590                        print_status_struct *status)
1591 {
1592         struct traverse_struct tstruct;
1593         struct traverse_count_struct tsc;
1594         fstring keystr;
1595         TDB_DATA data, key;
1596         const char *printername = lp_const_servicename(snum);
1597         struct tdb_print_db *pdb = get_print_db_byname(printername);
1598
1599         *queue = NULL;
1600         
1601         if (!pdb)
1602                 return 0;
1603
1604         /* make sure the database is up to date */
1605         if (print_cache_expired(snum))
1606                 print_queue_update(snum);
1607
1608         /*
1609          * Fetch the queue status.  We must do this first, as there may
1610          * be no jobs in the queue.
1611          */
1612         ZERO_STRUCTP(status);
1613         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printername);
1614         key.dptr = keystr;
1615         key.dsize = strlen(keystr);
1616         data = tdb_fetch(pdb->tdb, key);
1617         if (data.dptr) {
1618                 if (data.dsize == sizeof(*status)) {
1619                         memcpy(status, data.dptr, sizeof(*status));
1620                 }
1621                 SAFE_FREE(data.dptr);
1622         }
1623
1624         /*
1625          * Now, fetch the print queue information.  We first count the number
1626          * of entries, and then only retrieve the queue if necessary.
1627          */
1628         tsc.count = 0;
1629         tsc.snum = snum;
1630         
1631         tdb_traverse(pdb->tdb, traverse_count_fn_queue, (void *)&tsc);
1632
1633         if (tsc.count == 0)
1634                 return 0;
1635
1636         /* Allocate the queue size. */
1637         if ((tstruct.queue = (print_queue_struct *)
1638              malloc(sizeof(print_queue_struct)*tsc.count)) == NULL)
1639                 return 0;
1640
1641         /*
1642          * Fill in the queue.
1643          * We need maxcount as the queue size may have changed between
1644          * the two calls to tdb_traverse.
1645          */
1646         tstruct.qcount = 0;
1647         tstruct.maxcount = tsc.count;
1648         tstruct.snum = snum;
1649
1650         tdb_traverse(pdb->tdb, traverse_fn_queue, (void *)&tstruct);
1651
1652         /* Sort the queue by submission time otherwise they are displayed
1653            in hash order. */
1654
1655         qsort(tstruct.queue, tstruct.qcount, sizeof(print_queue_struct),
1656               QSORT_CAST(printjob_comp));
1657
1658         *queue = tstruct.queue;
1659         return tstruct.qcount;
1660 }
1661
1662 /****************************************************************************
1663  Turn a queue name into a snum.
1664 ****************************************************************************/
1665
1666 int print_queue_snum(const char *qname)
1667 {
1668         int snum = lp_servicenumber(qname);
1669         if (snum == -1 || !lp_print_ok(snum))
1670                 return -1;
1671         return snum;
1672 }
1673
1674 /****************************************************************************
1675  Pause a queue.
1676 ****************************************************************************/
1677
1678 BOOL print_queue_pause(struct current_user *user, int snum, WERROR *errcode)
1679 {
1680         int ret;
1681         
1682         if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
1683                 *errcode = WERR_ACCESS_DENIED;
1684                 return False;
1685         }
1686
1687         ret = (*(current_printif->queue_pause))(snum);
1688
1689         if (ret != 0) {
1690                 *errcode = WERR_INVALID_PARAM;
1691                 return False;
1692         }
1693
1694         /* force update the database */
1695         print_cache_flush(snum);
1696
1697         /* Send a printer notify message */
1698
1699         notify_printer_status(snum, PRINTER_STATUS_PAUSED);
1700
1701         return True;
1702 }
1703
1704 /****************************************************************************
1705  Resume a queue.
1706 ****************************************************************************/
1707
1708 BOOL print_queue_resume(struct current_user *user, int snum, WERROR *errcode)
1709 {
1710         int ret;
1711
1712         if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
1713                 *errcode = WERR_ACCESS_DENIED;
1714                 return False;
1715         }
1716
1717         ret = (*(current_printif->queue_resume))(snum);
1718
1719         if (ret != 0) {
1720                 *errcode = WERR_INVALID_PARAM;
1721                 return False;
1722         }
1723
1724         /* make sure the database is up to date */
1725         if (print_cache_expired(snum))
1726                 print_queue_update(snum);
1727
1728         /* Send a printer notify message */
1729
1730         notify_printer_status(snum, PRINTER_STATUS_OK);
1731
1732         return True;
1733 }
1734
1735 /****************************************************************************
1736  Purge a queue - implemented by deleting all jobs that we can delete.
1737 ****************************************************************************/
1738
1739 BOOL print_queue_purge(struct current_user *user, int snum, WERROR *errcode)
1740 {
1741         print_queue_struct *queue;
1742         print_status_struct status;
1743         int njobs, i;
1744         BOOL can_job_admin;
1745
1746         /* Force and update so the count is accurate (i.e. not a cached count) */
1747         print_queue_update(snum);
1748         
1749         can_job_admin = print_access_check(user, snum, JOB_ACCESS_ADMINISTER);
1750         njobs = print_queue_status(snum, &queue, &status);
1751
1752         for (i=0;i<njobs;i++) {
1753                 BOOL owner = is_owner(user, snum, queue[i].job);
1754
1755                 if (owner || can_job_admin) {
1756                         print_job_delete1(snum, queue[i].job);
1757                 }
1758         }
1759
1760         SAFE_FREE(queue);
1761
1762         return True;
1763 }