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