Lots of fixes for error paths where tdb_fetch() data need freeing.
[sharpe/samba-autobuild/.git] / source3 / 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         SAFE_FREE(data.dptr);
75         /* Not found - create and store mapping. */
76         rap_jobid = ++next_rap_jobid;
77         if (rap_jobid == 0)
78                 rap_jobid = ++next_rap_jobid;
79         data.dptr = (char *)&rap_jobid;
80         data.dsize = sizeof(rap_jobid);
81         tdb_store(rap_tdb, key, data, TDB_REPLACE);
82         tdb_store(rap_tdb, data, key, TDB_REPLACE);
83         return rap_jobid;
84 }
85
86 BOOL rap_to_pjobid(uint16 rap_jobid, int *psnum, uint32 *pjobid)
87 {
88         TDB_DATA data, key;
89         char jinfo[8];
90
91         if (!rap_tdb)
92                 return False;
93
94         key.dptr = (char *)&rap_jobid;
95         key.dsize = sizeof(rap_jobid);
96         data = tdb_fetch(rap_tdb, key);
97         if (data.dptr && data.dsize == sizeof(jinfo)) {
98                 *psnum = IVAL(&jinfo,0);
99                 *pjobid = IVAL(&jinfo,4);
100                 SAFE_FREE(data.dptr);
101                 return True;
102         }
103         SAFE_FREE(data.dptr);
104         return False;
105 }
106
107 static void rap_jobid_delete(int snum, uint32 jobid)
108 {
109         TDB_DATA key, data;
110         uint16 rap_jobid;
111         char jinfo[8];
112
113         if (!rap_tdb)
114                 return;
115
116         SIVAL(&jinfo,0,(int32)snum);
117         SIVAL(&jinfo,4,jobid);
118
119         key.dptr = (char *)&jinfo;
120         key.dsize = sizeof(jinfo);
121         data = tdb_fetch(rap_tdb, key);
122         if (!data.dptr || (data.dsize != sizeof(uint16))) {
123                 SAFE_FREE(data.dptr);
124                 return;
125         }
126
127         memcpy(&rap_jobid, data.dptr, sizeof(uint16));
128         SAFE_FREE(data.dptr);
129         data.dptr = (char *)&rap_jobid;
130         data.dsize = sizeof(rap_jobid);
131         tdb_delete(rap_tdb, key);
132         tdb_delete(rap_tdb, data);
133 }
134
135 static pid_t local_pid;
136
137 static int get_queue_status(int, print_status_struct *);
138
139 /* There can be this many printing tdb's open, plus any locked ones. */
140 #define MAX_PRINT_DBS_OPEN 1
141
142 struct tdb_print_db {
143         struct tdb_print_db *next, *prev;
144         TDB_CONTEXT *tdb;
145         int ref_count;
146         fstring printer_name;
147 };
148
149 static struct tdb_print_db *print_db_head;
150
151 /****************************************************************************
152   Function to find or create the printer specific job tdb given a printername.
153   Limits the number of tdb's open to MAX_PRINT_DBS_OPEN.
154 ****************************************************************************/
155
156 static struct tdb_print_db *get_print_db_byname(const char *printername)
157 {
158         struct tdb_print_db *p = NULL, *last_entry = NULL;
159         int num_open = 0;
160         pstring printdb_path;
161         BOOL done_become_root = False;
162
163         for (p = print_db_head, last_entry = print_db_head; p; p = p->next) {
164                 /* Ensure the list terminates... JRA. */
165                 SMB_ASSERT(p->next != print_db_head);
166
167                 if (p->tdb && strequal(p->printer_name, printername)) {
168                         DLIST_PROMOTE(print_db_head, p);
169                         p->ref_count++;
170                         return p;
171                 }
172                 num_open++;
173                 last_entry = p;
174         }
175
176         /* Not found. */
177         if (num_open >= MAX_PRINT_DBS_OPEN) {
178                 /* Try and recycle the last entry. */
179                 DLIST_PROMOTE(print_db_head, last_entry);
180
181                 for (p = print_db_head; p; p = p->next) {
182                         if (p->ref_count)
183                                 continue;
184                         if (p->tdb) {
185                                 if (tdb_close(print_db_head->tdb)) {
186                                         DEBUG(0,("get_print_db: Failed to close tdb for printer %s\n",
187                                                                 print_db_head->printer_name ));
188                                         return NULL;
189                                 }
190                         }
191                         p->tdb = NULL;
192                         p->ref_count = 0;
193                         memset(p->printer_name, '\0', sizeof(p->printer_name));
194                         break;
195                 }
196                 if (p) {
197                         DLIST_PROMOTE(print_db_head, p);
198                         p = print_db_head;
199                 }
200         }
201        
202         if (!p) {
203                 /* Create one. */
204                 p = (struct tdb_print_db *)malloc(sizeof(struct tdb_print_db));
205                 if (!p) {
206                         DEBUG(0,("get_print_db: malloc fail !\n"));
207                         return NULL;
208                 }
209                 ZERO_STRUCTP(p);
210                 DLIST_ADD(print_db_head, p);
211         }
212
213         pstrcpy(printdb_path, lock_path("printing/"));
214         pstrcat(printdb_path, printername);
215         pstrcat(printdb_path, ".tdb");
216
217         if (geteuid() != 0) {
218                 become_root();
219                 done_become_root = True;
220         }
221
222         p->tdb = tdb_open_log(printdb_path, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
223
224         if (done_become_root)
225                 unbecome_root();
226
227         if (!p->tdb) {
228                 DEBUG(0,("get_print_db: Failed to open printer backend database %s.\n",
229                                         printdb_path ));
230                 DLIST_REMOVE(print_db_head, p);
231                 SAFE_FREE(p);
232                 return NULL;
233         }
234         fstrcpy(p->printer_name, printername);
235         p->ref_count++;
236         return p;
237 }
238
239 /***************************************************************************
240  Remove a reference count.
241 ****************************************************************************/
242
243 static void release_print_db( struct tdb_print_db *pdb)
244 {
245         pdb->ref_count--;
246         SMB_ASSERT(pdb->ref_count >= 0);
247 }
248
249 /***************************************************************************
250  Close all open print db entries.
251 ****************************************************************************/
252
253 static void close_all_print_db(void)
254 {
255         struct tdb_print_db *p = NULL, *next_p = NULL;
256
257         for (p = print_db_head; p; p = next_p) {
258                 next_p = p->next;
259
260                 if (p->tdb)
261                         tdb_close(p->tdb);
262                 DLIST_REMOVE(print_db_head, p);
263                 ZERO_STRUCTP(p);
264                 SAFE_FREE(p);
265         }
266 }
267
268 /****************************************************************************
269  Initialise the printing backend. Called once at startup before the fork().
270 ****************************************************************************/
271
272 BOOL print_backend_init(void)
273 {
274         char *sversion = "INFO/version";
275         pstring printing_path;
276         int services = lp_numservices();
277         int snum;
278
279         if (local_pid == sys_getpid())
280                 return True;
281
282         unlink(lock_path("printing.tdb"));
283         pstrcpy(printing_path,lock_path("printing"));
284         mkdir(printing_path,0755);
285
286         local_pid = sys_getpid();
287
288         /* handle a Samba upgrade */
289
290         for (snum = 0; snum < services; snum++) {
291                 struct tdb_print_db *pdb;
292                 if (!lp_print_ok(snum))
293                         continue;
294
295                 pdb = get_print_db_byname(lp_const_servicename(snum));
296                 if (!pdb)
297                         continue;
298                 if (tdb_lock_bystring(pdb->tdb, sversion, 0) == -1) {
299                         DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
300                         release_print_db(pdb);
301                         return False;
302                 }
303                 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
304                         tdb_traverse(pdb->tdb, tdb_traverse_delete_fn, NULL);
305                         tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
306                 }
307                 tdb_unlock_bystring(pdb->tdb, sversion);
308                 release_print_db(pdb);
309         }
310
311         close_all_print_db(); /* Don't leave any open. */
312
313         /* select the appropriate printing interface... */
314 #ifdef HAVE_CUPS
315         if (strcmp(lp_printcapname(), "cups") == 0)
316                 current_printif = &cups_printif;
317 #endif /* HAVE_CUPS */
318
319         /* do NT print initialization... */
320         return nt_printing_init();
321 }
322
323 /****************************************************************************
324  Shut down printing backend. Called once at shutdown to close the tdb.
325 ****************************************************************************/
326
327 void printing_end(void)
328 {
329         close_all_print_db(); /* Don't leave any open. */
330 }
331
332 /****************************************************************************
333  Useful function to generate a tdb key.
334 ****************************************************************************/
335
336 static TDB_DATA print_key(uint32 jobid)
337 {
338         static uint32 j;
339         TDB_DATA ret;
340
341         j = jobid;
342         ret.dptr = (void *)&j;
343         ret.dsize = sizeof(j);
344         return ret;
345 }
346
347 /***********************************************************************
348  unpack a pjob from a tdb buffer 
349 ***********************************************************************/
350  
351 int unpack_pjob( char* buf, int buflen, struct printjob *pjob )
352 {
353         int     len = 0;
354         int     used;
355         
356         if ( !buf || !pjob )
357                 return -1;
358                 
359         len += tdb_unpack(buf+len, buflen-len, "dddddddddffff",
360                                 &pjob->pid,
361                                 &pjob->sysjob,
362                                 &pjob->fd,
363                                 &pjob->starttime,
364                                 &pjob->status,
365                                 &pjob->size,
366                                 &pjob->page_count,
367                                 &pjob->spooled,
368                                 &pjob->smbjob,
369                                 pjob->filename,
370                                 pjob->jobname,
371                                 pjob->user,
372                                 pjob->queuename);
373                                 
374         if ( len == -1 )
375                 return -1;
376                 
377         if ( (used = unpack_devicemode(&pjob->nt_devmode, buf+len, buflen-len)) == -1 )
378                 return -1;
379         
380         len += used;
381         
382         return len;
383
384 }
385
386 /****************************************************************************
387  Useful function to find a print job in the database.
388 ****************************************************************************/
389
390 static struct printjob *print_job_find(int snum, uint32 jobid)
391 {
392         static struct printjob  pjob;
393         TDB_DATA                ret;
394         struct tdb_print_db     *pdb = get_print_db_byname(lp_const_servicename(snum));
395         
396
397         if (!pdb)
398                 return NULL;
399
400         ret = tdb_fetch(pdb->tdb, print_key(jobid));
401         release_print_db(pdb);
402
403         if (!ret.dptr)
404                 return NULL;
405         
406         if ( pjob.nt_devmode )
407                 free_nt_devicemode( &pjob.nt_devmode );
408                 
409         ZERO_STRUCT( pjob );
410         
411         if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
412                 SAFE_FREE(ret.dptr);
413                 return NULL;
414         }
415         
416         SAFE_FREE(ret.dptr);    
417         return &pjob;
418 }
419
420 /* Convert a unix jobid to a smb jobid */
421
422 static uint32 sysjob_to_jobid_value;
423
424 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
425                                TDB_DATA data, void *state)
426 {
427         struct printjob *pjob;
428         int *sysjob = (int *)state;
429
430         if (!data.dptr || data.dsize == 0)
431                 return 0;
432
433         pjob = (struct printjob *)data.dptr;
434         if (key.dsize != sizeof(uint32))
435                 return 0;
436
437         if (*sysjob == pjob->sysjob) {
438                 uint32 *jobid = (uint32 *)key.dptr;
439
440                 sysjob_to_jobid_value = *jobid;
441                 return 1;
442         }
443
444         return 0;
445 }
446
447 /****************************************************************************
448  This is a *horribly expensive call as we have to iterate through all the
449  current printer tdb's. Don't do this often ! JRA.
450 ****************************************************************************/
451
452 uint32 sysjob_to_jobid(int unix_jobid)
453 {
454         int services = lp_numservices();
455         int snum;
456
457         sysjob_to_jobid_value = (uint32)-1;
458
459         for (snum = 0; snum < services; snum++) {
460                 struct tdb_print_db *pdb;
461                 if (!lp_print_ok(snum))
462                         continue;
463                 pdb = get_print_db_byname(lp_const_servicename(snum));
464                 if (pdb)
465                         tdb_traverse(pdb->tdb, unixjob_traverse_fn, &unix_jobid);
466                 release_print_db(pdb);
467                 if (sysjob_to_jobid_value != (uint32)-1)
468                         return sysjob_to_jobid_value;
469         }
470         return (uint32)-1;
471 }
472
473 /****************************************************************************
474  Send notifications based on what has changed after a pjob_store.
475 ****************************************************************************/
476
477 static struct {
478         uint32 lpq_status;
479         uint32 spoolss_status;
480 } lpq_to_spoolss_status_map[] = {
481         { LPQ_QUEUED, JOB_STATUS_QUEUED },
482         { LPQ_PAUSED, JOB_STATUS_PAUSED },
483         { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
484         { LPQ_PRINTING, JOB_STATUS_PRINTING },
485         { LPQ_DELETING, JOB_STATUS_DELETING },
486         { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
487         { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
488         { LPQ_PRINTED, JOB_STATUS_PRINTED },
489         { LPQ_DELETED, JOB_STATUS_DELETED },
490         { LPQ_BLOCKED, JOB_STATUS_BLOCKED },
491         { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
492         { -1, 0 }
493 };
494
495 /* Convert a lpq status value stored in printing.tdb into the
496    appropriate win32 API constant. */
497
498 static uint32 map_to_spoolss_status(uint32 lpq_status)
499 {
500         int i = 0;
501
502         while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
503                 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
504                         return lpq_to_spoolss_status_map[i].spoolss_status;
505                 i++;
506         }
507
508         return 0;
509 }
510
511 static void pjob_store_notify(int snum, uint32 jobid, struct printjob *old_data,
512                               struct printjob *new_data)
513 {
514         BOOL new_job = False;
515
516         if (!old_data)
517                 new_job = True;
518
519         /* Notify the job name first */
520
521         if (new_job || !strequal(old_data->jobname, new_data->jobname))
522                 notify_job_name(snum, jobid, new_data->jobname);
523
524         /* Job attributes that can't be changed.  We only send
525            notification for these on a new job. */
526
527         if (new_job) {
528                 notify_job_submitted(snum, jobid, new_data->starttime);
529                 notify_job_username(snum, jobid, new_data->user);
530         }
531
532         /* Job attributes of a new job or attributes that can be
533            modified. */
534
535         if (new_job || old_data->status != new_data->status)
536                 notify_job_status(snum, jobid, map_to_spoolss_status(new_data->status));
537
538         if (new_job || old_data->size != new_data->size)
539                 notify_job_total_bytes(snum, jobid, new_data->size);
540
541         if (new_job || old_data->page_count != new_data->page_count)
542                 notify_job_total_pages(snum, jobid, new_data->page_count);
543 }
544
545 /****************************************************************************
546  Store a job structure back to the database.
547 ****************************************************************************/
548
549 static BOOL pjob_store(int snum, uint32 jobid, struct printjob *pjob)
550 {
551         TDB_DATA                old_data, new_data;
552         BOOL                    ret = False;
553         struct tdb_print_db     *pdb = get_print_db_byname(lp_const_servicename(snum));
554         char                    *buf = NULL;
555         int                     len, newlen, buflen;
556         
557
558         if (!pdb)
559                 return False;
560
561         /* Get old data */
562
563         old_data = tdb_fetch(pdb->tdb, print_key(jobid));
564
565         /* Doh!  Now we have to pack/unpack data since the NT_DEVICEMODE was added */
566
567         newlen = 0;
568         
569         do {
570                 len = 0;
571                 buflen = newlen;
572                 len += tdb_pack(buf+len, buflen-len, "dddddddddffff",
573                                 pjob->pid,
574                                 pjob->sysjob,
575                                 pjob->fd,
576                                 pjob->starttime,
577                                 pjob->status,
578                                 pjob->size,
579                                 pjob->page_count,
580                                 pjob->spooled,
581                                 pjob->smbjob,
582                                 pjob->filename,
583                                 pjob->jobname,
584                                 pjob->user,
585                                 pjob->queuename);
586
587                 len += pack_devicemode(pjob->nt_devmode, buf+len, buflen-len);
588         
589                 if (buflen != len) {
590                         char *tb;
591
592                         tb = (char *)Realloc(buf, len);
593                         if (!tb) {
594                                 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
595                                 goto done;
596                         }
597                         else 
598                                 buf = tb;
599                         newlen = len;
600                 }
601         } while ( buflen != len );
602                 
603         
604         /* Store new data */
605
606         new_data.dptr = buf;
607         new_data.dsize = len;
608         ret = (tdb_store(pdb->tdb, print_key(jobid), new_data, TDB_REPLACE) == 0);
609
610         release_print_db(pdb);
611
612         /* Send notify updates for what has changed */
613
614         if ( ret && (old_data.dsize == 0 || old_data.dsize == sizeof(*pjob)) )
615                 pjob_store_notify( snum, jobid, (struct printjob *)old_data.dptr, pjob );
616
617 done:
618         SAFE_FREE( old_data.dptr );
619         SAFE_FREE( buf );
620
621         return ret;
622 }
623
624 /****************************************************************************
625  Remove a job structure from the database.
626 ****************************************************************************/
627
628 static void pjob_delete(int snum, uint32 jobid)
629 {
630         struct printjob *pjob = print_job_find(snum, jobid);
631         uint32 job_status = 0;
632         struct tdb_print_db *pdb = get_print_db_byname(lp_const_servicename(snum));
633
634         if (!pdb)
635                 return;
636
637         if (!pjob) {
638                 DEBUG(5, ("pjob_delete(): we were asked to delete nonexistent job %u\n",
639                                         (unsigned int)jobid));
640                 release_print_db(pdb);
641                 return;
642         }
643
644         /* Send a notification that a job has been deleted */
645
646         job_status = map_to_spoolss_status(pjob->status);
647
648         /* We must cycle through JOB_STATUS_DELETING and
649            JOB_STATUS_DELETED for the port monitor to delete the job
650            properly. */
651         
652         job_status |= JOB_STATUS_DELETING;
653         notify_job_status(snum, jobid, job_status);
654         
655         job_status |= JOB_STATUS_DELETED;
656         notify_job_status(snum, jobid, job_status);
657
658         /* Remove from printing.tdb */
659
660         tdb_delete(pdb->tdb, print_key(jobid));
661         release_print_db(pdb);
662         rap_jobid_delete(snum, jobid);
663 }
664
665 /****************************************************************************
666  Parse a file name from the system spooler to generate a jobid.
667 ****************************************************************************/
668
669 static uint32 print_parse_jobid(char *fname)
670 {
671         int jobid;
672
673         if (strncmp(fname,PRINT_SPOOL_PREFIX,strlen(PRINT_SPOOL_PREFIX)) != 0)
674                 return (uint32)-1;
675         fname += strlen(PRINT_SPOOL_PREFIX);
676
677         jobid = atoi(fname);
678         if (jobid <= 0)
679                 return (uint32)-1;
680
681         return (uint32)jobid;
682 }
683
684 /****************************************************************************
685  List a unix job in the print database.
686 ****************************************************************************/
687
688 static void print_unix_job(int snum, print_queue_struct *q)
689 {
690         uint32 jobid = q->job + UNIX_JOB_START;
691         struct printjob pj, *old_pj;
692
693         /* Preserve the timestamp on an existing unix print job */
694
695         old_pj = print_job_find(snum, jobid);
696
697         ZERO_STRUCT(pj);
698
699         pj.pid = (pid_t)-1;
700         pj.sysjob = q->job;
701         pj.fd = -1;
702         pj.starttime = old_pj ? old_pj->starttime : q->time;
703         pj.status = q->status;
704         pj.size = q->size;
705         pj.spooled = True;
706         pj.smbjob = False;
707         fstrcpy(pj.filename, "");
708         fstrcpy(pj.jobname, q->fs_file);
709         fstrcpy(pj.user, q->fs_user);
710         fstrcpy(pj.queuename, lp_const_servicename(snum));
711
712         pjob_store(snum, jobid, &pj);
713 }
714
715
716 struct traverse_struct {
717         print_queue_struct *queue;
718         int qcount, snum, maxcount, total_jobs;
719 };
720
721 /****************************************************************************
722  Utility fn to delete any jobs that are no longer active.
723 ****************************************************************************/
724
725 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
726 {
727         struct traverse_struct *ts = (struct traverse_struct *)state;
728         struct printjob pjob;
729         uint32 jobid;
730         int i;
731
732         if (  key.dsize != sizeof(jobid) )
733                 return 0;
734                 
735         memcpy(&jobid, key.dptr, sizeof(jobid));
736         if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
737                 return 0;
738         free_nt_devicemode( &pjob.nt_devmode );
739
740
741         if (ts->snum != lp_servicenumber(pjob.queuename)) {
742                 /* this isn't for the queue we are looking at - this cannot happen with the split tdb's. JRA */
743                 return 0;
744         }
745
746         if (!pjob.smbjob) {
747                 /* remove a unix job if it isn't in the system queue any more */
748
749                 for (i=0;i<ts->qcount;i++) {
750                         uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
751                         if (jobid == u_jobid)
752                                 break;
753                 }
754                 if (i == ts->qcount)
755                         pjob_delete(ts->snum, jobid);
756                 else
757                         ts->total_jobs++;
758                 return 0;
759         }
760
761         /* maybe it hasn't been spooled yet */
762         if (!pjob.spooled) {
763                 /* if a job is not spooled and the process doesn't
764                    exist then kill it. This cleans up after smbd
765                    deaths */
766                 if (!process_exists(pjob.pid))
767                         pjob_delete(ts->snum, jobid);
768                 else
769                         ts->total_jobs++;
770                 return 0;
771         }
772
773         for (i=0;i<ts->qcount;i++) {
774                 uint32 curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
775                 if (jobid == curr_jobid)
776                         break;
777         }
778         
779         /* The job isn't in the system queue - we have to assume it has
780            completed, so delete the database entry. */
781
782         if (i == ts->qcount) {
783                 time_t cur_t = time(NULL);
784
785                 /* A race can occur between the time a job is spooled and
786                    when it appears in the lpq output.  This happens when
787                    the job is added to printing.tdb when another smbd
788                    running print_queue_update() has completed a lpq and
789                    is currently traversing the printing tdb and deleting jobs.
790                    A workaround is to not delete the job if it has been 
791                    submitted less than lp_lpqcachetime() seconds ago. */
792
793                 if ((cur_t - pjob.starttime) > lp_lpqcachetime())
794                         pjob_delete(ts->snum, jobid);
795                 else
796                         ts->total_jobs++;
797         }
798         else
799                 ts->total_jobs++;
800
801         return 0;
802 }
803
804 /****************************************************************************
805  Check if the print queue has been updated recently enough.
806 ****************************************************************************/
807
808 static void print_cache_flush(int snum)
809 {
810         fstring key;
811         const char *printername = lp_const_servicename(snum);
812         struct tdb_print_db *pdb = get_print_db_byname(printername);
813
814         if (!pdb)
815                 return;
816         slprintf(key, sizeof(key)-1, "CACHE/%s", printername);
817         tdb_store_int32(pdb->tdb, key, -1);
818         release_print_db(pdb);
819 }
820
821 /****************************************************************************
822  Check if someone already thinks they are doing the update.
823 ****************************************************************************/
824
825 static pid_t get_updating_pid(fstring printer_name)
826 {
827         fstring keystr;
828         TDB_DATA data, key;
829         pid_t updating_pid;
830         struct tdb_print_db *pdb = get_print_db_byname(printer_name);
831
832         if (!pdb)
833                 return (pid_t)-1;
834         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
835         key.dptr = keystr;
836         key.dsize = strlen(keystr);
837
838         data = tdb_fetch(pdb->tdb, key);
839         release_print_db(pdb);
840         if (!data.dptr || data.dsize != sizeof(pid_t)) {
841                 SAFE_FREE(data.dptr);
842                 return (pid_t)-1;
843         }
844
845         memcpy(&updating_pid, data.dptr, sizeof(pid_t));
846         SAFE_FREE(data.dptr);
847
848         if (process_exists(updating_pid))
849                 return updating_pid;
850
851         return (pid_t)-1;
852 }
853
854 /****************************************************************************
855  Set the fact that we're doing the update, or have finished doing the update
856  in the tdb.
857 ****************************************************************************/
858
859 static void set_updating_pid(const fstring printer_name, BOOL delete)
860 {
861         fstring keystr;
862         TDB_DATA key;
863         TDB_DATA data;
864         pid_t updating_pid = sys_getpid();
865         struct tdb_print_db *pdb = get_print_db_byname(printer_name);
866
867         if (!pdb)
868                 return;
869
870         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
871         key.dptr = keystr;
872         key.dsize = strlen(keystr);
873
874         if (delete) {
875                 tdb_delete(pdb->tdb, key);
876                 release_print_db(pdb);
877                 return;
878         }
879         
880         data.dptr = (void *)&updating_pid;
881         data.dsize = sizeof(pid_t);
882
883         tdb_store(pdb->tdb, key, data, TDB_REPLACE);    
884         release_print_db(pdb);
885 }
886
887 /****************************************************************************
888  Update the internal database from the system print queue for a queue.
889 ****************************************************************************/
890
891 static void print_queue_update(int snum)
892 {
893         int i, qcount;
894         print_queue_struct *queue = NULL;
895         print_status_struct status;
896         print_status_struct old_status;
897         struct printjob *pjob;
898         struct traverse_struct tstruct;
899         fstring keystr, printer_name, cachestr;
900         TDB_DATA data, key;
901         struct tdb_print_db *pdb;
902
903         fstrcpy(printer_name, lp_const_servicename(snum));
904         pdb = get_print_db_byname(printer_name);
905         if (!pdb)
906                 return;
907
908         /*
909          * Check to see if someone else is doing this update.
910          * This is essentially a mutex on the update.
911          */
912
913         if (get_updating_pid(printer_name) != -1) {
914                 release_print_db(pdb);
915                 return;
916         }
917
918         /* Lock the queue for the database update */
919
920         slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", printer_name);
921         /* Only wait 10 seconds for this. */
922         if (tdb_lock_bystring(pdb->tdb, keystr, 10) == -1) {
923                 DEBUG(0,("print_queue_update: Failed to lock printer %s database\n", printer_name));
924                 release_print_db(pdb);
925                 return;
926         }
927
928         /*
929          * Ensure that no one else got in here.
930          * If the updating pid is still -1 then we are
931          * the winner.
932          */
933
934         if (get_updating_pid(printer_name) != -1) {
935                 /*
936                  * Someone else is doing the update, exit.
937                  */
938                 tdb_unlock_bystring(pdb->tdb, keystr);
939                 release_print_db(pdb);
940                 return;
941         }
942
943         /*
944          * We're going to do the update ourselves.
945          */
946
947         /* Tell others we're doing the update. */
948         set_updating_pid(printer_name, False);
949
950         /*
951          * Allow others to enter and notice we're doing
952          * the update.
953          */
954
955         tdb_unlock_bystring(pdb->tdb, keystr);
956
957         /*
958          * Update the cache time FIRST ! Stops others even
959          * attempting to get the lock and doing this
960          * if the lpq takes a long time.
961          */
962
963         slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", printer_name);
964         tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
965
966         /* get the current queue using the appropriate interface */
967         ZERO_STRUCT(status);
968
969         qcount = (*(current_printif->queue_get))(snum, &queue, &status);
970
971         DEBUG(3, ("%d job%s in queue for %s\n", qcount, (qcount != 1) ?
972                 "s" : "", printer_name));
973
974         /*
975           any job in the internal database that is marked as spooled
976           and doesn't exist in the system queue is considered finished
977           and removed from the database
978
979           any job in the system database but not in the internal database 
980           is added as a unix job
981
982           fill in any system job numbers as we go
983         */
984         for (i=0; i<qcount; i++) {
985                 uint32 jobid = print_parse_jobid(queue[i].fs_file);
986
987                 if (jobid == (uint32)-1) {
988                         /* assume its a unix print job */
989                         print_unix_job(snum, &queue[i]);
990                         continue;
991                 }
992
993                 /* we have an active SMB print job - update its status */
994                 pjob = print_job_find(snum, jobid);
995                 if (!pjob) {
996                         /* err, somethings wrong. Probably smbd was restarted
997                            with jobs in the queue. All we can do is treat them
998                            like unix jobs. Pity. */
999                         print_unix_job(snum, &queue[i]);
1000                         continue;
1001                 }
1002
1003                 pjob->sysjob = queue[i].job;
1004                 pjob->status = queue[i].status;
1005
1006                 pjob_store(snum, jobid, pjob);
1007         }
1008
1009         /* now delete any queued entries that don't appear in the
1010            system queue */
1011         tstruct.queue = queue;
1012         tstruct.qcount = qcount;
1013         tstruct.snum = snum;
1014         tstruct.total_jobs = 0;
1015
1016         tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1017
1018         SAFE_FREE(tstruct.queue);
1019
1020         tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1021
1022         if( qcount != get_queue_status(snum, &old_status))
1023                 DEBUG(10,("print_queue_update: queue status change %d jobs -> %d jobs for printer %s\n",
1024                                         old_status.qcount, qcount, printer_name ));
1025
1026         /* store the new queue status structure */
1027         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printer_name);
1028         key.dptr = keystr;
1029         key.dsize = strlen(keystr);
1030
1031         status.qcount = qcount;
1032         data.dptr = (void *)&status;
1033         data.dsize = sizeof(status);
1034         tdb_store(pdb->tdb, key, data, TDB_REPLACE);    
1035
1036         /*
1037          * Update the cache time again. We want to do this call
1038          * as little as possible...
1039          */
1040
1041         slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", printer_name);
1042         tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1043
1044         /* Delete our pid from the db. */
1045         set_updating_pid(printer_name, True);
1046         release_print_db(pdb);
1047 }
1048
1049 /****************************************************************************
1050  Fetch and clean the pid_t record list for all pids interested in notify
1051  messages. data needs freeing on exit.
1052 ****************************************************************************/
1053
1054 #define NOTIFY_PID_LIST_KEY "NOTIFY_PID_LIST"
1055 #define PRINT_SERVER_ENTRY_NAME "___PRINT_SERVER_ENTRY___"
1056
1057 static TDB_DATA get_printer_notify_pid_list(TDB_CONTEXT *tdb, const char *printer_name, BOOL cleanlist)
1058 {
1059         TDB_DATA data;
1060         size_t i;
1061
1062         ZERO_STRUCT(data);
1063
1064         data = tdb_fetch_by_string( tdb, NOTIFY_PID_LIST_KEY );
1065
1066         if (!data.dptr) {
1067                 ZERO_STRUCT(data);
1068                 return data;
1069         }
1070
1071         if (data.dsize % 8) {
1072                 DEBUG(0,("get_printer_notify_pid_list: Size of record for printer %s not a multiple of 8 !\n", printer_name ));
1073                 tdb_delete_by_string(tdb, NOTIFY_PID_LIST_KEY );
1074                 SAFE_FREE(data.dptr);
1075                 ZERO_STRUCT(data);
1076                 return data;
1077         }
1078
1079         if (!cleanlist)
1080                 return data;
1081
1082         /*
1083          * Weed out all dead entries.
1084          */
1085
1086         for( i = 0; i < data.dsize; i += 8) {
1087                 pid_t pid = (pid_t)IVAL(data.dptr, i);
1088
1089                 if (pid == sys_getpid())
1090                         continue;
1091
1092                 /* Entry is dead if process doesn't exist or refcount is zero. */
1093
1094                 while ((i < data.dsize) && ((IVAL(data.dptr, i + 4) == 0) || !process_exists(pid))) {
1095
1096                         /* Refcount == zero is a logic error and should never happen. */
1097                         if (IVAL(data.dptr, i + 4) == 0) {
1098                                 DEBUG(0,("get_printer_notify_pid_list: Refcount == 0 for pid = %u printer %s !\n",
1099                                                         (unsigned int)pid, printer_name ));
1100                         }
1101
1102                         if (data.dsize - i > 8)
1103                                 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1104                         data.dsize -= 8;
1105                 }
1106         }
1107
1108         return data;
1109 }
1110
1111 /****************************************************************************
1112  Return a malloced list of pid_t's that are interested in getting update
1113  messages on this print queue. Used in printing/notify to send the messages.
1114 ****************************************************************************/
1115
1116 BOOL print_notify_pid_list(const char *printername, TALLOC_CTX *mem_ctx, size_t *p_num_pids, pid_t **pp_pid_list)
1117 {
1118         struct tdb_print_db *pdb = NULL;
1119         TDB_CONTEXT *tdb = NULL;
1120         TDB_DATA data;
1121         BOOL ret = True;
1122         size_t i, num_pids, offset;
1123         pid_t *pid_list;
1124
1125         *p_num_pids = 0;
1126         *pp_pid_list = NULL;
1127
1128         if (strequal(printername, PRINT_SERVER_ENTRY_NAME)) {
1129                 pdb = NULL;
1130                 tdb = conn_tdb_ctx();
1131         } else {
1132                 pdb = get_print_db_byname(printername);
1133                 if (!pdb)
1134                         return False;
1135                 tdb = pdb->tdb;
1136         }
1137
1138         if (tdb_read_lock_bystring(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1139                 DEBUG(0,("print_notify_pid_list: Failed to lock printer %s database\n",
1140                                         printername));
1141                 if (pdb)
1142                         release_print_db(pdb);
1143                 return False;
1144         }
1145
1146         data = get_printer_notify_pid_list( tdb, printername, True );
1147
1148         if (!data.dptr) {
1149                 ret = True;
1150                 goto done;
1151         }
1152
1153         num_pids = data.dsize / 8;
1154
1155         if ((pid_list = (pid_t *)talloc(mem_ctx, sizeof(pid_t) * num_pids)) == NULL) {
1156                 ret = False;
1157                 goto done;
1158         }
1159
1160         for( i = 0, offset = 0; offset < data.dsize; offset += 8, i++)
1161                 pid_list[i] = (pid_t)IVAL(data.dptr, offset);
1162
1163         *pp_pid_list = pid_list;
1164         *p_num_pids = num_pids;
1165
1166         ret = True;
1167
1168   done:
1169
1170         tdb_read_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1171         if (pdb)
1172                 release_print_db(pdb);
1173         SAFE_FREE(data.dptr);
1174         return ret;
1175 }
1176
1177 /****************************************************************************
1178  Create/Update an entry in the print tdb that will allow us to send notify
1179  updates only to interested smbd's. 
1180 ****************************************************************************/
1181
1182 BOOL print_notify_register_pid(int snum)
1183 {
1184         TDB_DATA data;
1185         struct tdb_print_db *pdb = NULL;
1186         TDB_CONTEXT *tdb = NULL;
1187         const char *printername;
1188         uint32 mypid = (uint32)sys_getpid();
1189         BOOL ret = False;
1190         size_t i;
1191
1192         if (snum != -1) {
1193                 printername = lp_const_servicename(snum);
1194                 pdb = get_print_db_byname(printername);
1195                 if (!pdb)
1196                         return False;
1197                 tdb = pdb->tdb;
1198         } else {
1199                 printername = PRINT_SERVER_ENTRY_NAME;
1200                 pdb = NULL;
1201                 tdb = conn_tdb_ctx();
1202         }
1203
1204         if (tdb_lock_bystring(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1205                 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1206                                         printername));
1207                 if (pdb)
1208                         release_print_db(pdb);
1209                 return False;
1210         }
1211
1212         data = get_printer_notify_pid_list( tdb, printername, True );
1213
1214         /* Add ourselves and increase the refcount. */
1215
1216         for (i = 0; i < data.dsize; i += 8) {
1217                 if (IVAL(data.dptr,i) == mypid) {
1218                         uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1219                         SIVAL(data.dptr, i+4, new_refcount);
1220                         break;
1221                 }
1222         }
1223
1224         if (i == data.dsize) {
1225                 /* We weren't in the list. Realloc. */
1226                 data.dptr = Realloc(data.dptr, data.dsize + 8);
1227                 if (!data.dptr) {
1228                         DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1229                                                 printername));
1230                         goto done;
1231                 }
1232                 data.dsize += 8;
1233                 SIVAL(data.dptr,data.dsize - 8,mypid);
1234                 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1235         }
1236
1237         /* Store back the record. */
1238         if (tdb_store_by_string(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1239                 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1240 list for printer %s\n", printername));
1241                 goto done;
1242         }
1243
1244         ret = True;
1245
1246  done:
1247
1248         tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1249         if (pdb)
1250                 release_print_db(pdb);
1251         SAFE_FREE(data.dptr);
1252         return ret;
1253 }
1254
1255 /****************************************************************************
1256  Update an entry in the print tdb that will allow us to send notify
1257  updates only to interested smbd's. 
1258 ****************************************************************************/
1259
1260 BOOL print_notify_deregister_pid(int snum)
1261 {
1262         TDB_DATA data;
1263         struct tdb_print_db *pdb = NULL;
1264         TDB_CONTEXT *tdb = NULL;
1265         const char *printername;
1266         uint32 mypid = (uint32)sys_getpid();
1267         size_t i;
1268         BOOL ret = False;
1269
1270         if (snum != -1) {
1271                 printername = lp_const_servicename(snum);
1272                 pdb = get_print_db_byname(printername);
1273                 if (!pdb)
1274                         return False;
1275                 tdb = pdb->tdb;
1276         } else {
1277                 printername = PRINT_SERVER_ENTRY_NAME;
1278                 pdb = NULL;
1279                 tdb = conn_tdb_ctx();
1280         }
1281
1282         if (tdb_lock_bystring(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1283                 DEBUG(0,("print_notify_register_pid: Failed to lock \
1284 printer %s database\n", printername));
1285                 if (pdb)
1286                         release_print_db(pdb);
1287                 return False;
1288         }
1289
1290         data = get_printer_notify_pid_list( tdb, printername, True );
1291
1292         /* Reduce refcount. Remove ourselves if zero. */
1293
1294         for (i = 0; i < data.dsize; ) {
1295                 if (IVAL(data.dptr,i) == mypid) {
1296                         uint32 refcount = IVAL(data.dptr, i+4);
1297
1298                         refcount--;
1299
1300                         if (refcount == 0) {
1301                                 if (data.dsize - i > 8)
1302                                         memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1303                                 data.dsize -= 8;
1304                                 continue;
1305                         }
1306                         SIVAL(data.dptr, i+4, refcount);
1307                 }
1308
1309                 i += 8;
1310         }
1311
1312         if (data.dsize == 0)
1313                 SAFE_FREE(data.dptr);
1314
1315         /* Store back the record. */
1316         if (tdb_store_by_string(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1317                 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1318 list for printer %s\n", printername));
1319                 goto done;
1320         }
1321
1322         ret = True;
1323
1324   done:
1325
1326         tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1327         if (pdb)
1328                 release_print_db(pdb);
1329         SAFE_FREE(data.dptr);
1330         return ret;
1331 }
1332
1333 /****************************************************************************
1334  Check if a jobid is valid. It is valid if it exists in the database.
1335 ****************************************************************************/
1336
1337 BOOL print_job_exists(int snum, uint32 jobid)
1338 {
1339         struct tdb_print_db *pdb = get_print_db_byname(lp_const_servicename(snum));
1340         BOOL ret;
1341
1342         if (!pdb)
1343                 return False;
1344         ret = tdb_exists(pdb->tdb, print_key(jobid));
1345         release_print_db(pdb);
1346         return ret;
1347 }
1348
1349 /****************************************************************************
1350  Give the fd used for a jobid.
1351 ****************************************************************************/
1352
1353 int print_job_fd(int snum, uint32 jobid)
1354 {
1355         struct printjob *pjob = print_job_find(snum, jobid);
1356         if (!pjob)
1357                 return -1;
1358         /* don't allow another process to get this info - it is meaningless */
1359         if (pjob->pid != local_pid)
1360                 return -1;
1361         return pjob->fd;
1362 }
1363
1364 /****************************************************************************
1365  Give the filename used for a jobid.
1366  Only valid for the process doing the spooling and when the job
1367  has not been spooled.
1368 ****************************************************************************/
1369
1370 char *print_job_fname(int snum, uint32 jobid)
1371 {
1372         struct printjob *pjob = print_job_find(snum, jobid);
1373         if (!pjob || pjob->spooled || pjob->pid != local_pid)
1374                 return NULL;
1375         return pjob->filename;
1376 }
1377
1378
1379 /****************************************************************************
1380  Give the filename used for a jobid.
1381  Only valid for the process doing the spooling and when the job
1382  has not been spooled.
1383 ****************************************************************************/
1384
1385 NT_DEVICEMODE *print_job_devmode(int snum, uint32 jobid)
1386 {
1387         struct printjob *pjob = print_job_find(snum, jobid);
1388         
1389         if ( !pjob )
1390                 return NULL;
1391                 
1392         return pjob->nt_devmode;
1393 }
1394
1395 /****************************************************************************
1396  Set the place in the queue for a job.
1397 ****************************************************************************/
1398
1399 BOOL print_job_set_place(int snum, uint32 jobid, int place)
1400 {
1401         DEBUG(2,("print_job_set_place not implemented yet\n"));
1402         return False;
1403 }
1404
1405 /****************************************************************************
1406  Set the name of a job. Only possible for owner.
1407 ****************************************************************************/
1408
1409 BOOL print_job_set_name(int snum, uint32 jobid, char *name)
1410 {
1411         struct printjob *pjob = print_job_find(snum, jobid);
1412         if (!pjob || pjob->pid != local_pid)
1413                 return False;
1414
1415         fstrcpy(pjob->jobname, name);
1416         return pjob_store(snum, jobid, pjob);
1417 }
1418
1419 /****************************************************************************
1420  Delete a print job - don't update queue.
1421 ****************************************************************************/
1422
1423 static BOOL print_job_delete1(int snum, uint32 jobid)
1424 {
1425         struct printjob *pjob = print_job_find(snum, jobid);
1426         int result = 0;
1427
1428         if (!pjob)
1429                 return False;
1430
1431         /*
1432          * If already deleting just return.
1433          */
1434
1435         if (pjob->status == LPQ_DELETING)
1436                 return True;
1437
1438         /* Hrm - we need to be able to cope with deleting a job before it
1439            has reached the spooler. */
1440
1441         if (pjob->sysjob == -1) {
1442                 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
1443         }
1444
1445         /* Set the tdb entry to be deleting. */
1446
1447         pjob->status = LPQ_DELETING;
1448         pjob_store(snum, jobid, pjob);
1449
1450         if (pjob->spooled && pjob->sysjob != -1)
1451                 result = (*(current_printif->job_delete))(snum, pjob);
1452
1453         /* Delete the tdb entry if the delete suceeded or the job hasn't
1454            been spooled. */
1455
1456         if (result == 0)
1457                 pjob_delete(snum, jobid);
1458
1459         return (result == 0);
1460 }
1461
1462 /****************************************************************************
1463  Return true if the current user owns the print job.
1464 ****************************************************************************/
1465
1466 static BOOL is_owner(struct current_user *user, int snum, uint32 jobid)
1467 {
1468         struct printjob *pjob = print_job_find(snum, jobid);
1469         user_struct *vuser;
1470
1471         if (!pjob || !user)
1472                 return False;
1473
1474         if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
1475                 return strequal(pjob->user, vuser->user.smb_name);
1476         } else {
1477                 return strequal(pjob->user, uidtoname(user->uid));
1478         }
1479 }
1480
1481 /****************************************************************************
1482  Delete a print job.
1483 ****************************************************************************/
1484
1485 BOOL print_job_delete(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1486 {
1487         BOOL    owner, deleted;
1488         char    *fname;
1489
1490         *errcode = WERR_OK;
1491                 
1492         owner = is_owner(user, snum, jobid);
1493         
1494         /* Check access against security descriptor or whether the user
1495            owns their job. */
1496
1497         if (!owner && 
1498             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1499                 DEBUG(3, ("delete denied by security descriptor\n"));
1500                 *errcode = WERR_ACCESS_DENIED;
1501
1502                 /* BEGIN_ADMIN_LOG */
1503                 sys_adminlog( LOG_ERR, (char *)
1504                          "Permission denied-- user not allowed to delete, \
1505 pause, or resume print job. User name: %s. Printer name: %s.",
1506                                 uidtoname(user->uid), PRINTERNAME(snum) );
1507                 /* END_ADMIN_LOG */
1508
1509                 return False;
1510         }
1511
1512         /* 
1513          * get the spooled filename of the print job
1514          * if this works, then the file has not been spooled
1515          * to the underlying print system.  Just delete the 
1516          * spool file & return.
1517          */
1518          
1519         if ( (fname = print_job_fname( snum, jobid )) != NULL )
1520         {
1521                 /* remove the spool file */
1522                 DEBUG(10,("print_job_delete: Removing spool file [%s]\n", fname ));
1523                 if ( unlink( fname ) == -1 ) {
1524                         *errcode = map_werror_from_unix(errno);
1525                         return False;
1526                 }
1527                 
1528                 return True;
1529         }
1530         
1531         if (!print_job_delete1(snum, jobid)) {
1532                 *errcode = WERR_ACCESS_DENIED;
1533                 return False;
1534         }
1535
1536         /* force update the database and say the delete failed if the
1537            job still exists */
1538
1539         print_queue_update(snum);
1540         
1541         deleted = !print_job_exists(snum, jobid);
1542         if ( !deleted )
1543                 *errcode = WERR_ACCESS_DENIED;
1544
1545         return deleted;
1546 }
1547
1548 /****************************************************************************
1549  Pause a job.
1550 ****************************************************************************/
1551
1552 BOOL print_job_pause(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1553 {
1554         struct printjob *pjob = print_job_find(snum, jobid);
1555         int ret = -1;
1556         
1557         if (!pjob || !user) 
1558                 return False;
1559
1560         if (!pjob->spooled || pjob->sysjob == -1) 
1561                 return False;
1562
1563         if (!is_owner(user, snum, jobid) &&
1564             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1565                 DEBUG(3, ("pause denied by security descriptor\n"));
1566
1567                 /* BEGIN_ADMIN_LOG */
1568                 sys_adminlog( LOG_ERR, (char *)
1569                         "Permission denied-- user not allowed to delete, \
1570 pause, or resume print job. User name: %s. Printer name: %s.",
1571                                 uidtoname(user->uid), PRINTERNAME(snum) );
1572                 /* END_ADMIN_LOG */
1573
1574                 *errcode = WERR_ACCESS_DENIED;
1575                 return False;
1576         }
1577
1578         /* need to pause the spooled entry */
1579         ret = (*(current_printif->job_pause))(snum, pjob);
1580
1581         if (ret != 0) {
1582                 *errcode = WERR_INVALID_PARAM;
1583                 return False;
1584         }
1585
1586         /* force update the database */
1587         print_cache_flush(snum);
1588
1589         /* Send a printer notify message */
1590
1591         notify_job_status(snum, jobid, JOB_STATUS_PAUSED);
1592
1593         /* how do we tell if this succeeded? */
1594
1595         return True;
1596 }
1597
1598 /****************************************************************************
1599  Resume a job.
1600 ****************************************************************************/
1601
1602 BOOL print_job_resume(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1603 {
1604         struct printjob *pjob = print_job_find(snum, jobid);
1605         int ret;
1606         
1607         if (!pjob || !user)
1608                 return False;
1609
1610         if (!pjob->spooled || pjob->sysjob == -1)
1611                 return False;
1612
1613         if (!is_owner(user, snum, jobid) &&
1614             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1615                 DEBUG(3, ("resume denied by security descriptor\n"));
1616                 *errcode = WERR_ACCESS_DENIED;
1617
1618                 /* BEGIN_ADMIN_LOG */
1619                 sys_adminlog( LOG_ERR, (char *)
1620                          "Permission denied-- user not allowed to delete, \
1621 pause, or resume print job. User name: %s. Printer name: %s.",
1622                         uidtoname(user->uid), PRINTERNAME(snum) );
1623                 /* END_ADMIN_LOG */
1624                 return False;
1625         }
1626
1627         ret = (*(current_printif->job_resume))(snum, pjob);
1628
1629         if (ret != 0) {
1630                 *errcode = WERR_INVALID_PARAM;
1631                 return False;
1632         }
1633
1634         /* force update the database */
1635         print_cache_flush(snum);
1636
1637         /* Send a printer notify message */
1638
1639         notify_job_status(snum, jobid, JOB_STATUS_QUEUED);
1640
1641         return True;
1642 }
1643
1644 /****************************************************************************
1645  Write to a print file.
1646 ****************************************************************************/
1647
1648 int print_job_write(int snum, uint32 jobid, const char *buf, int size)
1649 {
1650         int return_code;
1651         struct printjob *pjob = print_job_find(snum, jobid);
1652
1653         if (!pjob)
1654                 return -1;
1655         /* don't allow another process to get this info - it is meaningless */
1656         if (pjob->pid != local_pid)
1657                 return -1;
1658
1659         return_code = write(pjob->fd, buf, size);
1660         if (return_code>0) {
1661                 pjob->size += size;
1662                 pjob_store(snum, jobid, pjob);
1663         }
1664         return return_code;
1665 }
1666
1667 /****************************************************************************
1668  Check if the print queue has been updated recently enough.
1669 ****************************************************************************/
1670
1671 static BOOL print_cache_expired(int snum)
1672 {
1673         fstring key;
1674         time_t last_qscan_time, time_now = time(NULL);
1675         const char *printername = lp_const_servicename(snum);
1676         struct tdb_print_db *pdb = get_print_db_byname(printername);
1677
1678         if (!pdb)
1679                 return False;
1680
1681         slprintf(key, sizeof(key), "CACHE/%s", printername);
1682         last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1683
1684         /*
1685          * Invalidate the queue for 3 reasons.
1686          * (1). last queue scan time == -1.
1687          * (2). Current time - last queue scan time > allowed cache time.
1688          * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1689          * This last test picks up machines for which the clock has been moved
1690          * forward, an lpq scan done and then the clock moved back. Otherwise
1691          * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1692          */
1693
1694         if (last_qscan_time == ((time_t)-1) || (time_now - last_qscan_time) >= lp_lpqcachetime() ||
1695                         last_qscan_time > (time_now + MAX_CACHE_VALID_TIME)) {
1696                 DEBUG(3, ("print cache expired for queue %s \
1697 (last_qscan_time = %d, time now = %d, qcachetime = %d)\n", printername,
1698                         (int)last_qscan_time, (int)time_now, (int)lp_lpqcachetime() ));
1699                 release_print_db(pdb);
1700                 return True;
1701         }
1702         release_print_db(pdb);
1703         return False;
1704 }
1705
1706 /****************************************************************************
1707  Get the queue status - do not update if db is out of date.
1708 ****************************************************************************/
1709
1710 static int get_queue_status(int snum, print_status_struct *status)
1711 {
1712         fstring keystr;
1713         TDB_DATA data, key;
1714         const char *printername = lp_const_servicename(snum);
1715         struct tdb_print_db *pdb = get_print_db_byname(printername);
1716         if (!pdb)
1717                 return 0;
1718
1719         ZERO_STRUCTP(status);
1720         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printername);
1721         key.dptr = keystr;
1722         key.dsize = strlen(keystr);
1723         data = tdb_fetch(pdb->tdb, key);
1724         release_print_db(pdb);
1725         if (data.dptr) {
1726                 if (data.dsize == sizeof(print_status_struct))
1727                         memcpy(status, data.dptr, sizeof(print_status_struct));
1728                 SAFE_FREE(data.dptr);
1729         }
1730         return status->qcount;
1731 }
1732
1733 /****************************************************************************
1734  Determine the number of jobs in a queue.
1735 ****************************************************************************/
1736
1737 int print_queue_length(int snum, print_status_struct *pstatus)
1738 {
1739         print_status_struct status;
1740         int len;
1741  
1742         /* make sure the database is up to date */
1743         if (print_cache_expired(snum))
1744                 print_queue_update(snum);
1745  
1746         /* also fetch the queue status */
1747         memset(&status, 0, sizeof(status));
1748         len = get_queue_status(snum, &status);
1749         if (pstatus)
1750                 *pstatus = status;
1751         return len;
1752 }
1753
1754 /***************************************************************************
1755  Start spooling a job - return the jobid.
1756 ***************************************************************************/
1757
1758 uint32 print_job_start(struct current_user *user, int snum, char *jobname, NT_DEVICEMODE *nt_devmode )
1759 {
1760         uint32 jobid;
1761         char *path;
1762         struct printjob pjob;
1763         int next_jobid;
1764         user_struct *vuser;
1765         int njobs = 0;
1766         const char *printername = lp_const_servicename(snum);
1767         struct tdb_print_db *pdb = get_print_db_byname(printername);
1768         BOOL pdb_locked = False;
1769
1770         errno = 0;
1771
1772         if (!pdb)
1773                 return (uint32)-1;
1774
1775         if (!print_access_check(user, snum, PRINTER_ACCESS_USE)) {
1776                 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
1777                 release_print_db(pdb);
1778                 return (uint32)-1;
1779         }
1780
1781         if (!print_time_access_check(snum)) {
1782                 DEBUG(3, ("print_job_start: job start denied by time check\n"));
1783                 release_print_db(pdb);
1784                 return (uint32)-1;
1785         }
1786
1787         path = lp_pathname(snum);
1788
1789         /* see if we have sufficient disk space */
1790         if (lp_minprintspace(snum)) {
1791                 SMB_BIG_UINT dspace, dsize;
1792                 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
1793                     dspace < 2*(SMB_BIG_UINT)lp_minprintspace(snum)) {
1794                         DEBUG(3, ("print_job_start: disk space check failed.\n"));
1795                         release_print_db(pdb);
1796                         errno = ENOSPC;
1797                         return (uint32)-1;
1798                 }
1799         }
1800
1801         /* for autoloaded printers, check that the printcap entry still exists */
1802         if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum), NULL)) {
1803                 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
1804                 release_print_db(pdb);
1805                 errno = ENOENT;
1806                 return (uint32)-1;
1807         }
1808
1809         /* Insure the maximum queue size is not violated */
1810         if ((njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
1811                 DEBUG(3, ("print_job_start: number of jobs (%d) larger than max printjobs per queue (%d).\n",
1812                         njobs, lp_maxprintjobs(snum) ));
1813                 release_print_db(pdb);
1814                 errno = ENOSPC;
1815                 return (uint32)-1;
1816         }
1817
1818         /* Lock the database - only wait 20 seconds. */
1819         if (tdb_lock_bystring(pdb->tdb, "INFO/nextjob", 20) == -1) {
1820                 DEBUG(0,("print_job_start: failed to lock printing database %s\n", printername ));
1821                 release_print_db(pdb);
1822                 return (uint32)-1;
1823         }
1824
1825         pdb_locked = True;
1826
1827         next_jobid = tdb_fetch_int32(pdb->tdb, "INFO/nextjob");
1828         if (next_jobid == -1)
1829                 next_jobid = 1;
1830
1831         for (jobid = NEXT_JOBID(next_jobid); jobid != next_jobid; jobid = NEXT_JOBID(jobid)) {
1832                 if (!print_job_exists(snum, jobid))
1833                         break;
1834         }
1835                                 
1836         if (jobid == next_jobid) {
1837                 DEBUG(3, ("print_job_start: jobid (%d)==next_jobid(%d).\n",
1838                                 jobid, next_jobid ));
1839                 jobid = -1;
1840                 goto fail;
1841         }
1842
1843         /* Store a dummy placeholder. This must be quick as we have the lock. */
1844         {
1845                 TDB_DATA dum;
1846                 dum.dptr = NULL;
1847                 dum.dsize = 0;
1848                 if (tdb_store(pdb->tdb, print_key(jobid), dum, TDB_INSERT) == -1) {
1849                         DEBUG(3, ("print_job_start: jobid (%d) failed to store placeholder.\n",
1850                                 jobid ));
1851                         jobid = -1;
1852                         goto fail;
1853                 }
1854         }
1855
1856         if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
1857                 DEBUG(3, ("print_job_start: failed to store INFO/nextjob.\n"));
1858                 jobid = -1;
1859                 goto fail;
1860         }
1861
1862         /* We've finished with the INFO/nextjob lock. */
1863         tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
1864         pdb_locked = False;
1865
1866         /* create the database entry */
1867         
1868         ZERO_STRUCT(pjob);
1869         
1870         pjob.pid = local_pid;
1871         pjob.sysjob = -1;
1872         pjob.fd = -1;
1873         pjob.starttime = time(NULL);
1874         pjob.status = LPQ_SPOOLING;
1875         pjob.size = 0;
1876         pjob.spooled = False;
1877         pjob.smbjob = True;
1878         pjob.nt_devmode = nt_devmode;
1879         
1880         fstrcpy(pjob.jobname, jobname);
1881
1882         if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
1883                 fstrcpy(pjob.user, vuser->user.smb_name);
1884         } else {
1885                 fstrcpy(pjob.user, uidtoname(user->uid));
1886         }
1887
1888         fstrcpy(pjob.queuename, lp_const_servicename(snum));
1889
1890         /* we have a job entry - now create the spool file */
1891         slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX", 
1892                  path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
1893         pjob.fd = smb_mkstemp(pjob.filename);
1894
1895         if (pjob.fd == -1) {
1896                 if (errno == EACCES) {
1897                         /* Common setup error, force a report. */
1898                         DEBUG(0, ("print_job_start: insufficient permissions \
1899 to open spool file %s.\n", pjob.filename));
1900                 } else {
1901                         /* Normal case, report at level 3 and above. */
1902                         DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
1903                         DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
1904                 }
1905                 goto fail;
1906         }
1907
1908         pjob_store(snum, jobid, &pjob);
1909
1910         release_print_db(pdb);
1911
1912         return jobid;
1913
1914  fail:
1915         if (jobid != -1)
1916                 pjob_delete(snum, jobid);
1917
1918         if (pdb_locked)
1919                 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
1920         release_print_db(pdb);
1921
1922         DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
1923         return -1;
1924 }
1925
1926 /****************************************************************************
1927  Update the number of pages spooled to jobid
1928 ****************************************************************************/
1929
1930 void print_job_endpage(int snum, uint32 jobid)
1931 {
1932         struct printjob *pjob = print_job_find(snum, jobid);
1933         if (!pjob)
1934                 return;
1935         /* don't allow another process to get this info - it is meaningless */
1936         if (pjob->pid != local_pid)
1937                 return;
1938
1939         pjob->page_count++;
1940         pjob_store(snum, jobid, pjob);
1941 }
1942
1943 /****************************************************************************
1944  Print a file - called on closing the file. This spools the job.
1945  If normal close is false then we're tearing down the jobs - treat as an
1946  error.
1947 ****************************************************************************/
1948
1949 BOOL print_job_end(int snum, uint32 jobid, BOOL normal_close)
1950 {
1951         struct printjob *pjob = print_job_find(snum, jobid);
1952         int ret;
1953         SMB_STRUCT_STAT sbuf;
1954
1955         if (!pjob)
1956                 return False;
1957
1958         if (pjob->spooled || pjob->pid != local_pid)
1959                 return False;
1960
1961         if (normal_close && (sys_fstat(pjob->fd, &sbuf) == 0)) {
1962                 pjob->size = sbuf.st_size;
1963                 close(pjob->fd);
1964                 pjob->fd = -1;
1965         } else {
1966
1967                 /* 
1968                  * Not a normal close or we couldn't stat the job file,
1969                  * so something has gone wrong. Cleanup.
1970                  */
1971                 close(pjob->fd);
1972                 pjob->fd = -1;
1973                 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
1974                 goto fail;
1975         }
1976
1977         /* Technically, this is not quite right. If the printer has a separator
1978          * page turned on, the NT spooler prints the separator page even if the
1979          * print job is 0 bytes. 010215 JRR */
1980         if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
1981                 /* don't bother spooling empty files or something being deleted. */
1982                 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
1983                         pjob->filename, pjob->size ? "deleted" : "zero length" ));
1984                 unlink(pjob->filename);
1985                 pjob_delete(snum, jobid);
1986                 return True;
1987         }
1988
1989         ret = (*(current_printif->job_submit))(snum, pjob);
1990
1991         if (ret)
1992                 goto fail;
1993
1994         /* The print job has been sucessfully handed over to the back-end */
1995         
1996         pjob->spooled = True;
1997         pjob->status = LPQ_QUEUED;
1998         pjob_store(snum, jobid, pjob);
1999         
2000         /* make sure the database is up to date */
2001         if (print_cache_expired(snum))
2002                 print_queue_update(snum);
2003         
2004         return True;
2005
2006 fail:
2007
2008         /* The print job was not succesfully started. Cleanup */
2009         /* Still need to add proper error return propagation! 010122:JRR */
2010         unlink(pjob->filename);
2011         pjob_delete(snum, jobid);
2012         return False;
2013 }
2014
2015 /****************************************************************************
2016  Utility fn to enumerate the print queue.
2017 ****************************************************************************/
2018
2019 static int traverse_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
2020 {
2021         struct traverse_struct *ts = (struct traverse_struct *)state;
2022         struct printjob pjob;
2023         int i;
2024         uint32 jobid;
2025
2026         /* sanity checks */
2027         
2028         if ( key.dsize != sizeof(jobid) )
2029                 return 0;
2030                 
2031         memcpy(&jobid, key.dptr, sizeof(jobid));
2032         
2033         if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
2034                 return 0;
2035         free_nt_devicemode( &pjob.nt_devmode );
2036
2037         /* maybe it isn't for this queue */
2038         if (ts->snum != lp_servicenumber(pjob.queuename))
2039                 return 0;
2040
2041         if (ts->qcount >= ts->maxcount)
2042                 return 0;
2043
2044         i = ts->qcount;
2045
2046         ts->queue[i].job = jobid;
2047         ts->queue[i].size = pjob.size;
2048         ts->queue[i].page_count = pjob.page_count;
2049         ts->queue[i].status = pjob.status;
2050         ts->queue[i].priority = 1;
2051         ts->queue[i].time = pjob.starttime;
2052         fstrcpy(ts->queue[i].fs_user, pjob.user);
2053         fstrcpy(ts->queue[i].fs_file, pjob.jobname);
2054
2055         ts->qcount++;
2056
2057         return 0;
2058 }
2059
2060 struct traverse_count_struct {
2061         int snum, count;
2062 };
2063
2064 /****************************************************************************
2065  Utility fn to count the number of entries in the print queue.
2066 ****************************************************************************/
2067
2068 static int traverse_count_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
2069 {
2070         struct traverse_count_struct *ts = (struct traverse_count_struct *)state;
2071         struct printjob pjob;
2072         uint32 jobid;
2073
2074         /* sanity checks */
2075         
2076         if (  key.dsize != sizeof(jobid) )
2077                 return 0;
2078                 
2079         memcpy(&jobid, key.dptr, sizeof(jobid));
2080         
2081         if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
2082                 return 0;
2083                 
2084         free_nt_devicemode( &pjob.nt_devmode );
2085
2086         /* maybe it isn't for this queue - this cannot happen with the tdb/printer code. JRA */
2087         if (ts->snum != lp_servicenumber(pjob.queuename))
2088                 return 0;
2089
2090         ts->count++;
2091
2092         return 0;
2093 }
2094
2095 /****************************************************************************
2096  Sort print jobs by submittal time.
2097 ****************************************************************************/
2098
2099 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
2100 {
2101         /* Silly cases */
2102
2103         if (!j1 && !j2)
2104                 return 0;
2105         if (!j1)
2106                 return -1;
2107         if (!j2)
2108                 return 1;
2109
2110         /* Sort on job start time */
2111
2112         if (j1->time == j2->time)
2113                 return 0;
2114         return (j1->time > j2->time) ? 1 : -1;
2115 }
2116
2117 /****************************************************************************
2118  Get a printer queue listing.
2119 ****************************************************************************/
2120
2121 int print_queue_status(int snum, 
2122                        print_queue_struct **queue,
2123                        print_status_struct *status)
2124 {
2125         struct traverse_struct tstruct;
2126         struct traverse_count_struct tsc;
2127         fstring keystr;
2128         TDB_DATA data, key;
2129         const char *printername = lp_const_servicename(snum);
2130         struct tdb_print_db *pdb = get_print_db_byname(printername);
2131
2132         *queue = NULL;
2133         
2134         if (!pdb)
2135                 return 0;
2136
2137         /* make sure the database is up to date */
2138         if (print_cache_expired(snum))
2139                 print_queue_update(snum);
2140
2141         /*
2142          * Fetch the queue status.  We must do this first, as there may
2143          * be no jobs in the queue.
2144          */
2145         ZERO_STRUCTP(status);
2146         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printername);
2147         key.dptr = keystr;
2148         key.dsize = strlen(keystr);
2149         data = tdb_fetch(pdb->tdb, key);
2150         if (data.dptr) {
2151                 if (data.dsize == sizeof(*status)) {
2152                         memcpy(status, data.dptr, sizeof(*status));
2153                 }
2154                 SAFE_FREE(data.dptr);
2155         }
2156
2157         /*
2158          * Now, fetch the print queue information.  We first count the number
2159          * of entries, and then only retrieve the queue if necessary.
2160          */
2161         tsc.count = 0;
2162         tsc.snum = snum;
2163         
2164         tdb_traverse(pdb->tdb, traverse_count_fn_queue, (void *)&tsc);
2165
2166         if (tsc.count == 0) {
2167                 release_print_db(pdb);
2168                 return 0;
2169         }
2170
2171         /* Allocate the queue size. */
2172         if ((tstruct.queue = (print_queue_struct *)
2173              malloc(sizeof(print_queue_struct)*tsc.count)) == NULL) {
2174                 release_print_db(pdb);
2175                 return 0;
2176         }
2177
2178         /*
2179          * Fill in the queue.
2180          * We need maxcount as the queue size may have changed between
2181          * the two calls to tdb_traverse.
2182          */
2183         tstruct.qcount = 0;
2184         tstruct.maxcount = tsc.count;
2185         tstruct.snum = snum;
2186
2187         tdb_traverse(pdb->tdb, traverse_fn_queue, (void *)&tstruct);
2188         release_print_db(pdb);
2189
2190         /* Sort the queue by submission time otherwise they are displayed
2191            in hash order. */
2192
2193         qsort(tstruct.queue, tstruct.qcount, sizeof(print_queue_struct),
2194               QSORT_CAST(printjob_comp));
2195
2196         *queue = tstruct.queue;
2197         return tstruct.qcount;
2198 }
2199
2200 /****************************************************************************
2201  Turn a queue name into a snum.
2202 ****************************************************************************/
2203
2204 int print_queue_snum(const char *qname)
2205 {
2206         int snum = lp_servicenumber(qname);
2207         if (snum == -1 || !lp_print_ok(snum))
2208                 return -1;
2209         return snum;
2210 }
2211
2212 /****************************************************************************
2213  Pause a queue.
2214 ****************************************************************************/
2215
2216 BOOL print_queue_pause(struct current_user *user, int snum, WERROR *errcode)
2217 {
2218         int ret;
2219         
2220         if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
2221                 *errcode = WERR_ACCESS_DENIED;
2222                 return False;
2223         }
2224
2225         ret = (*(current_printif->queue_pause))(snum);
2226
2227         if (ret != 0) {
2228                 *errcode = WERR_INVALID_PARAM;
2229                 return False;
2230         }
2231
2232         /* force update the database */
2233         print_cache_flush(snum);
2234
2235         /* Send a printer notify message */
2236
2237         notify_printer_status(snum, PRINTER_STATUS_PAUSED);
2238
2239         return True;
2240 }
2241
2242 /****************************************************************************
2243  Resume a queue.
2244 ****************************************************************************/
2245
2246 BOOL print_queue_resume(struct current_user *user, int snum, WERROR *errcode)
2247 {
2248         int ret;
2249
2250         if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
2251                 *errcode = WERR_ACCESS_DENIED;
2252                 return False;
2253         }
2254
2255         ret = (*(current_printif->queue_resume))(snum);
2256
2257         if (ret != 0) {
2258                 *errcode = WERR_INVALID_PARAM;
2259                 return False;
2260         }
2261
2262         /* make sure the database is up to date */
2263         if (print_cache_expired(snum))
2264                 print_queue_update(snum);
2265
2266         /* Send a printer notify message */
2267
2268         notify_printer_status(snum, PRINTER_STATUS_OK);
2269
2270         return True;
2271 }
2272
2273 /****************************************************************************
2274  Purge a queue - implemented by deleting all jobs that we can delete.
2275 ****************************************************************************/
2276
2277 BOOL print_queue_purge(struct current_user *user, int snum, WERROR *errcode)
2278 {
2279         print_queue_struct *queue;
2280         print_status_struct status;
2281         int njobs, i;
2282         BOOL can_job_admin;
2283
2284         /* Force and update so the count is accurate (i.e. not a cached count) */
2285         print_queue_update(snum);
2286         
2287         can_job_admin = print_access_check(user, snum, JOB_ACCESS_ADMINISTER);
2288         njobs = print_queue_status(snum, &queue, &status);
2289
2290         for (i=0;i<njobs;i++) {
2291                 BOOL owner = is_owner(user, snum, queue[i].job);
2292
2293                 if (owner || can_job_admin) {
2294                         print_job_delete1(snum, queue[i].job);
2295                 }
2296         }
2297
2298         SAFE_FREE(queue);
2299
2300         return True;
2301 }