s3: Fix a long-standing problem with recycled PIDs
[sfrench/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 3 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, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "printing.h"
24
25 extern struct current_user current_user;
26 extern userdom_struct current_user_info;
27
28 /* Current printer interface */
29 static bool remove_from_jobs_changed(const char* sharename, uint32 jobid);
30
31 /*
32    the printing backend revolves around a tdb database that stores the
33    SMB view of the print queue
34
35    The key for this database is a jobid - a internally generated number that
36    uniquely identifies a print job
37
38    reading the print queue involves two steps:
39      - possibly running lpq and updating the internal database from that
40      - reading entries from the database
41
42    jobids are assigned when a job starts spooling.
43 */
44
45 static TDB_CONTEXT *rap_tdb;
46 static uint16 next_rap_jobid;
47 struct rap_jobid_key {
48         fstring sharename;
49         uint32  jobid;
50 };
51
52 /***************************************************************************
53  Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
54  bit RPC jobids.... JRA.
55 ***************************************************************************/
56
57 uint16 pjobid_to_rap(const char* sharename, uint32 jobid)
58 {
59         uint16 rap_jobid;
60         TDB_DATA data, key;
61         struct rap_jobid_key jinfo;
62         uint8 buf[2];
63
64         DEBUG(10,("pjobid_to_rap: called.\n"));
65
66         if (!rap_tdb) {
67                 /* Create the in-memory tdb. */
68                 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
69                 if (!rap_tdb)
70                         return 0;
71         }
72
73         ZERO_STRUCT( jinfo );
74         fstrcpy( jinfo.sharename, sharename );
75         jinfo.jobid = jobid;
76         key.dptr = (uint8 *)&jinfo;
77         key.dsize = sizeof(jinfo);
78
79         data = tdb_fetch(rap_tdb, key);
80         if (data.dptr && data.dsize == sizeof(uint16)) {
81                 rap_jobid = SVAL(data.dptr, 0);
82                 SAFE_FREE(data.dptr);
83                 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
84                         (unsigned int)jobid, (unsigned int)rap_jobid));
85                 return rap_jobid;
86         }
87         SAFE_FREE(data.dptr);
88         /* Not found - create and store mapping. */
89         rap_jobid = ++next_rap_jobid;
90         if (rap_jobid == 0)
91                 rap_jobid = ++next_rap_jobid;
92         SSVAL(buf,0,rap_jobid);
93         data.dptr = buf;
94         data.dsize = sizeof(rap_jobid);
95         tdb_store(rap_tdb, key, data, TDB_REPLACE);
96         tdb_store(rap_tdb, data, key, TDB_REPLACE);
97
98         DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
99                 (unsigned int)jobid, (unsigned int)rap_jobid));
100         return rap_jobid;
101 }
102
103 bool rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
104 {
105         TDB_DATA data, key;
106         uint8 buf[2];
107
108         DEBUG(10,("rap_to_pjobid called.\n"));
109
110         if (!rap_tdb)
111                 return False;
112
113         SSVAL(buf,0,rap_jobid);
114         key.dptr = buf;
115         key.dsize = sizeof(rap_jobid);
116         data = tdb_fetch(rap_tdb, key);
117         if ( data.dptr && data.dsize == sizeof(struct rap_jobid_key) )
118         {
119                 struct rap_jobid_key *jinfo = (struct rap_jobid_key*)data.dptr;
120                 if (sharename != NULL) {
121                         fstrcpy( sharename, jinfo->sharename );
122                 }
123                 *pjobid = jinfo->jobid;
124                 DEBUG(10,("rap_to_pjobid: jobid %u maps to RAP jobid %u\n",
125                         (unsigned int)*pjobid, (unsigned int)rap_jobid));
126                 SAFE_FREE(data.dptr);
127                 return True;
128         }
129
130         DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
131                 (unsigned int)rap_jobid));
132         SAFE_FREE(data.dptr);
133         return False;
134 }
135
136 static void rap_jobid_delete(const char* sharename, uint32 jobid)
137 {
138         TDB_DATA key, data;
139         uint16 rap_jobid;
140         struct rap_jobid_key jinfo;
141         uint8 buf[2];
142
143         DEBUG(10,("rap_jobid_delete: called.\n"));
144
145         if (!rap_tdb)
146                 return;
147
148         ZERO_STRUCT( jinfo );
149         fstrcpy( jinfo.sharename, sharename );
150         jinfo.jobid = jobid;
151         key.dptr = (uint8 *)&jinfo;
152         key.dsize = sizeof(jinfo);
153
154         data = tdb_fetch(rap_tdb, key);
155         if (!data.dptr || (data.dsize != sizeof(uint16))) {
156                 DEBUG(10,("rap_jobid_delete: cannot find jobid %u\n",
157                         (unsigned int)jobid ));
158                 SAFE_FREE(data.dptr);
159                 return;
160         }
161
162         DEBUG(10,("rap_jobid_delete: deleting jobid %u\n",
163                 (unsigned int)jobid ));
164
165         rap_jobid = SVAL(data.dptr, 0);
166         SAFE_FREE(data.dptr);
167         SSVAL(buf,0,rap_jobid);
168         data.dptr = buf;
169         data.dsize = sizeof(rap_jobid);
170         tdb_delete(rap_tdb, key);
171         tdb_delete(rap_tdb, data);
172 }
173
174 static int get_queue_status(const char* sharename, print_status_struct *);
175
176 /****************************************************************************
177  Initialise the printing backend. Called once at startup before the fork().
178 ****************************************************************************/
179
180 bool print_backend_init(struct messaging_context *msg_ctx)
181 {
182         const char *sversion = "INFO/version";
183         int services = lp_numservices();
184         int snum;
185
186         unlink(cache_path("printing.tdb"));
187         mkdir(cache_path("printing"),0755);
188
189         /* handle a Samba upgrade */
190
191         for (snum = 0; snum < services; snum++) {
192                 struct tdb_print_db *pdb;
193                 if (!lp_print_ok(snum))
194                         continue;
195
196                 pdb = get_print_db_byname(lp_const_servicename(snum));
197                 if (!pdb)
198                         continue;
199                 if (tdb_lock_bystring(pdb->tdb, sversion) == -1) {
200                         DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
201                         release_print_db(pdb);
202                         return False;
203                 }
204                 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
205                         tdb_wipe_all(pdb->tdb);
206                         tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
207                 }
208                 tdb_unlock_bystring(pdb->tdb, sversion);
209                 release_print_db(pdb);
210         }
211
212         close_all_print_db(); /* Don't leave any open. */
213
214         /* do NT print initialization... */
215         return nt_printing_init(msg_ctx);
216 }
217
218 /****************************************************************************
219  Shut down printing backend. Called once at shutdown to close the tdb.
220 ****************************************************************************/
221
222 void printing_end(void)
223 {
224         close_all_print_db(); /* Don't leave any open. */
225 }
226
227 /****************************************************************************
228  Retrieve the set of printing functions for a given service.  This allows
229  us to set the printer function table based on the value of the 'printing'
230  service parameter.
231
232  Use the generic interface as the default and only use cups interface only
233  when asked for (and only when supported)
234 ****************************************************************************/
235
236 static struct printif *get_printer_fns_from_type( enum printing_types type )
237 {
238         struct printif *printer_fns = &generic_printif;
239
240 #ifdef HAVE_CUPS
241         if ( type == PRINT_CUPS ) {
242                 printer_fns = &cups_printif;
243         }
244 #endif /* HAVE_CUPS */
245
246 #ifdef HAVE_IPRINT
247         if ( type == PRINT_IPRINT ) {
248                 printer_fns = &iprint_printif;
249         }
250 #endif /* HAVE_IPRINT */
251
252         printer_fns->type = type;
253
254         return printer_fns;
255 }
256
257 static struct printif *get_printer_fns( int snum )
258 {
259         return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
260 }
261
262
263 /****************************************************************************
264  Useful function to generate a tdb key.
265 ****************************************************************************/
266
267 static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
268 {
269         TDB_DATA ret;
270
271         SIVAL(tmp, 0, jobid);
272         ret.dptr = (uint8 *)tmp;
273         ret.dsize = sizeof(*tmp);
274         return ret;
275 }
276
277 /***********************************************************************
278  unpack a pjob from a tdb buffer
279 ***********************************************************************/
280
281 int unpack_pjob( uint8 *buf, int buflen, struct printjob *pjob )
282 {
283         int     len = 0;
284         int     used;
285         uint32 pjpid, pjsysjob, pjfd, pjstarttime, pjstatus;
286         uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
287
288         if ( !buf || !pjob )
289                 return -1;
290
291         len += tdb_unpack(buf+len, buflen-len, "dddddddddffff",
292                                 &pjpid,
293                                 &pjsysjob,
294                                 &pjfd,
295                                 &pjstarttime,
296                                 &pjstatus,
297                                 &pjsize,
298                                 &pjpage_count,
299                                 &pjspooled,
300                                 &pjsmbjob,
301                                 pjob->filename,
302                                 pjob->jobname,
303                                 pjob->user,
304                                 pjob->queuename);
305
306         if ( len == -1 )
307                 return -1;
308
309         if ( (used = unpack_devicemode(&pjob->nt_devmode, buf+len, buflen-len)) == -1 )
310                 return -1;
311
312         len += used;
313
314         pjob->pid = pjpid;
315         pjob->sysjob = pjsysjob;
316         pjob->fd = pjfd;
317         pjob->starttime = pjstarttime;
318         pjob->status = pjstatus;
319         pjob->size = pjsize;
320         pjob->page_count = pjpage_count;
321         pjob->spooled = pjspooled;
322         pjob->smbjob = pjsmbjob;
323
324         return len;
325
326 }
327
328 /****************************************************************************
329  Useful function to find a print job in the database.
330 ****************************************************************************/
331
332 static struct printjob *print_job_find(const char *sharename, uint32 jobid)
333 {
334         static struct printjob  pjob;
335         uint32_t tmp;
336         TDB_DATA                ret;
337         struct tdb_print_db     *pdb = get_print_db_byname(sharename);
338
339         DEBUG(10,("print_job_find: looking up job %u for share %s\n",
340                         (unsigned int)jobid, sharename ));
341
342         if (!pdb) {
343                 return NULL;
344         }
345
346         ret = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
347         release_print_db(pdb);
348
349         if (!ret.dptr) {
350                 DEBUG(10,("print_job_find: failed to find jobid %u.\n", (unsigned int)jobid ));
351                 return NULL;
352         }
353
354         if ( pjob.nt_devmode ) {
355                 free_nt_devicemode( &pjob.nt_devmode );
356         }
357
358         ZERO_STRUCT( pjob );
359
360         if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
361                 DEBUG(10,("print_job_find: failed to unpack jobid %u.\n", (unsigned int)jobid ));
362                 SAFE_FREE(ret.dptr);
363                 return NULL;
364         }
365
366         SAFE_FREE(ret.dptr);
367
368         DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
369                         (int)pjob.sysjob, (unsigned int)jobid ));
370
371         return &pjob;
372 }
373
374 /* Convert a unix jobid to a smb jobid */
375
376 struct unixjob_traverse_state {
377         int sysjob;
378         uint32 sysjob_to_jobid_value;
379 };
380
381 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
382                                TDB_DATA data, void *private_data)
383 {
384         struct printjob *pjob;
385         struct unixjob_traverse_state *state =
386                 (struct unixjob_traverse_state *)private_data;
387
388         if (!data.dptr || data.dsize == 0)
389                 return 0;
390
391         pjob = (struct printjob *)data.dptr;
392         if (key.dsize != sizeof(uint32))
393                 return 0;
394
395         if (state->sysjob == pjob->sysjob) {
396                 uint32 jobid = IVAL(key.dptr,0);
397
398                 state->sysjob_to_jobid_value = jobid;
399                 return 1;
400         }
401
402         return 0;
403 }
404
405 /****************************************************************************
406  This is a *horribly expensive call as we have to iterate through all the
407  current printer tdb's. Don't do this often ! JRA.
408 ****************************************************************************/
409
410 uint32 sysjob_to_jobid(int unix_jobid)
411 {
412         int services = lp_numservices();
413         int snum;
414         struct unixjob_traverse_state state;
415
416         state.sysjob = unix_jobid;
417         state.sysjob_to_jobid_value = (uint32)-1;
418
419         for (snum = 0; snum < services; snum++) {
420                 struct tdb_print_db *pdb;
421                 if (!lp_print_ok(snum))
422                         continue;
423                 pdb = get_print_db_byname(lp_const_servicename(snum));
424                 if (!pdb) {
425                         continue;
426                 }
427                 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
428                 release_print_db(pdb);
429                 if (state.sysjob_to_jobid_value != (uint32)-1)
430                         return state.sysjob_to_jobid_value;
431         }
432         return (uint32)-1;
433 }
434
435 /****************************************************************************
436  Send notifications based on what has changed after a pjob_store.
437 ****************************************************************************/
438
439 static const struct {
440         uint32 lpq_status;
441         uint32 spoolss_status;
442 } lpq_to_spoolss_status_map[] = {
443         { LPQ_QUEUED, JOB_STATUS_QUEUED },
444         { LPQ_PAUSED, JOB_STATUS_PAUSED },
445         { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
446         { LPQ_PRINTING, JOB_STATUS_PRINTING },
447         { LPQ_DELETING, JOB_STATUS_DELETING },
448         { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
449         { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
450         { LPQ_PRINTED, JOB_STATUS_PRINTED },
451         { LPQ_DELETED, JOB_STATUS_DELETED },
452         { LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
453         { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
454         { -1, 0 }
455 };
456
457 /* Convert a lpq status value stored in printing.tdb into the
458    appropriate win32 API constant. */
459
460 static uint32 map_to_spoolss_status(uint32 lpq_status)
461 {
462         int i = 0;
463
464         while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
465                 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
466                         return lpq_to_spoolss_status_map[i].spoolss_status;
467                 i++;
468         }
469
470         return 0;
471 }
472
473 static void pjob_store_notify(const char* sharename, uint32 jobid, struct printjob *old_data,
474                               struct printjob *new_data)
475 {
476         bool new_job = False;
477
478         if (!old_data)
479                 new_job = True;
480
481         /* Job attributes that can't be changed.  We only send
482            notification for these on a new job. */
483
484         /* ACHTUNG!  Due to a bug in Samba's spoolss parsing of the
485            NOTIFY_INFO_DATA buffer, we *have* to send the job submission
486            time first or else we'll end up with potential alignment
487            errors.  I don't think the systemtime should be spooled as
488            a string, but this gets us around that error.
489            --jerry (i'll feel dirty for this) */
490
491         if (new_job) {
492                 notify_job_submitted(sharename, jobid, new_data->starttime);
493                 notify_job_username(sharename, jobid, new_data->user);
494         }
495
496         if (new_job || !strequal(old_data->jobname, new_data->jobname))
497                 notify_job_name(sharename, jobid, new_data->jobname);
498
499         /* Job attributes of a new job or attributes that can be
500            modified. */
501
502         if (new_job || !strequal(old_data->jobname, new_data->jobname))
503                 notify_job_name(sharename, jobid, new_data->jobname);
504
505         if (new_job || old_data->status != new_data->status)
506                 notify_job_status(sharename, jobid, map_to_spoolss_status(new_data->status));
507
508         if (new_job || old_data->size != new_data->size)
509                 notify_job_total_bytes(sharename, jobid, new_data->size);
510
511         if (new_job || old_data->page_count != new_data->page_count)
512                 notify_job_total_pages(sharename, jobid, new_data->page_count);
513 }
514
515 /****************************************************************************
516  Store a job structure back to the database.
517 ****************************************************************************/
518
519 static bool pjob_store(const char* sharename, uint32 jobid, struct printjob *pjob)
520 {
521         uint32_t tmp;
522         TDB_DATA                old_data, new_data;
523         bool                    ret = False;
524         struct tdb_print_db     *pdb = get_print_db_byname(sharename);
525         uint8                   *buf = NULL;
526         int                     len, newlen, buflen;
527
528
529         if (!pdb)
530                 return False;
531
532         /* Get old data */
533
534         old_data = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
535
536         /* Doh!  Now we have to pack/unpack data since the NT_DEVICEMODE was added */
537
538         newlen = 0;
539
540         do {
541                 len = 0;
542                 buflen = newlen;
543                 len += tdb_pack(buf+len, buflen-len, "dddddddddffff",
544                                 (uint32)pjob->pid,
545                                 (uint32)pjob->sysjob,
546                                 (uint32)pjob->fd,
547                                 (uint32)pjob->starttime,
548                                 (uint32)pjob->status,
549                                 (uint32)pjob->size,
550                                 (uint32)pjob->page_count,
551                                 (uint32)pjob->spooled,
552                                 (uint32)pjob->smbjob,
553                                 pjob->filename,
554                                 pjob->jobname,
555                                 pjob->user,
556                                 pjob->queuename);
557
558                 len += pack_devicemode(pjob->nt_devmode, buf+len, buflen-len);
559
560                 if (buflen != len) {
561                         buf = (uint8 *)SMB_REALLOC(buf, len);
562                         if (!buf) {
563                                 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
564                                 goto done;
565                         }
566                         newlen = len;
567                 }
568         } while ( buflen != len );
569
570
571         /* Store new data */
572
573         new_data.dptr = buf;
574         new_data.dsize = len;
575         ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
576                          TDB_REPLACE) == 0);
577
578         release_print_db(pdb);
579
580         /* Send notify updates for what has changed */
581
582         if ( ret ) {
583                 struct printjob old_pjob;
584
585                 if ( old_data.dsize )
586                 {
587                         if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
588                         {
589                                 pjob_store_notify( sharename, jobid, &old_pjob , pjob );
590                                 free_nt_devicemode( &old_pjob.nt_devmode );
591                         }
592                 }
593                 else {
594                         /* new job */
595                         pjob_store_notify( sharename, jobid, NULL, pjob );
596                 }
597         }
598
599 done:
600         SAFE_FREE( old_data.dptr );
601         SAFE_FREE( buf );
602
603         return ret;
604 }
605
606 /****************************************************************************
607  Remove a job structure from the database.
608 ****************************************************************************/
609
610 void pjob_delete(const char* sharename, uint32 jobid)
611 {
612         uint32_t tmp;
613         struct printjob *pjob;
614         uint32 job_status = 0;
615         struct tdb_print_db *pdb;
616
617         pdb = get_print_db_byname( sharename );
618
619         if (!pdb)
620                 return;
621
622         pjob = print_job_find( sharename, jobid );
623
624         if (!pjob) {
625                 DEBUG(5, ("pjob_delete: we were asked to delete nonexistent job %u\n",
626                                         (unsigned int)jobid));
627                 release_print_db(pdb);
628                 return;
629         }
630
631         /* We must cycle through JOB_STATUS_DELETING and
632            JOB_STATUS_DELETED for the port monitor to delete the job
633            properly. */
634
635         job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
636         notify_job_status(sharename, jobid, job_status);
637
638         /* Remove from printing.tdb */
639
640         tdb_delete(pdb->tdb, print_key(jobid, &tmp));
641         remove_from_jobs_changed(sharename, jobid);
642         release_print_db( pdb );
643         rap_jobid_delete(sharename, jobid);
644 }
645
646 /****************************************************************************
647  Parse a file name from the system spooler to generate a jobid.
648 ****************************************************************************/
649
650 static uint32 print_parse_jobid(char *fname)
651 {
652         int jobid;
653
654         if (strncmp(fname,PRINT_SPOOL_PREFIX,strlen(PRINT_SPOOL_PREFIX)) != 0)
655                 return (uint32)-1;
656         fname += strlen(PRINT_SPOOL_PREFIX);
657
658         jobid = atoi(fname);
659         if (jobid <= 0)
660                 return (uint32)-1;
661
662         return (uint32)jobid;
663 }
664
665 /****************************************************************************
666  List a unix job in the print database.
667 ****************************************************************************/
668
669 static void print_unix_job(const char *sharename, print_queue_struct *q, uint32 jobid)
670 {
671         struct printjob pj, *old_pj;
672
673         if (jobid == (uint32)-1)
674                 jobid = q->job + UNIX_JOB_START;
675
676         /* Preserve the timestamp on an existing unix print job */
677
678         old_pj = print_job_find(sharename, jobid);
679
680         ZERO_STRUCT(pj);
681
682         pj.pid = (pid_t)-1;
683         pj.sysjob = q->job;
684         pj.fd = -1;
685         pj.starttime = old_pj ? old_pj->starttime : q->time;
686         pj.status = q->status;
687         pj.size = q->size;
688         pj.spooled = True;
689         fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
690         if (jobid < UNIX_JOB_START) {
691                 pj.smbjob = True;
692                 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
693         } else {
694                 pj.smbjob = False;
695                 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
696         }
697         fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
698         fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
699
700         pjob_store(sharename, jobid, &pj);
701 }
702
703
704 struct traverse_struct {
705         print_queue_struct *queue;
706         int qcount, snum, maxcount, total_jobs;
707         const char *sharename;
708         time_t lpq_time;
709         const char *lprm_command;
710         struct printif *print_if;
711 };
712
713 /****************************************************************************
714  Utility fn to delete any jobs that are no longer active.
715 ****************************************************************************/
716
717 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
718 {
719         struct traverse_struct *ts = (struct traverse_struct *)state;
720         struct printjob pjob;
721         uint32 jobid;
722         int i = 0;
723
724         if (  key.dsize != sizeof(jobid) )
725                 return 0;
726
727         jobid = IVAL(key.dptr, 0);
728         if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
729                 return 0;
730         free_nt_devicemode( &pjob.nt_devmode );
731
732
733         if (!pjob.smbjob) {
734                 /* remove a unix job if it isn't in the system queue any more */
735
736                 for (i=0;i<ts->qcount;i++) {
737                         uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
738                         if (jobid == u_jobid)
739                                 break;
740                 }
741                 if (i == ts->qcount) {
742                         DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
743                                                 (unsigned int)jobid ));
744                         pjob_delete(ts->sharename, jobid);
745                         return 0;
746                 }
747
748                 /* need to continue the the bottom of the function to
749                    save the correct attributes */
750         }
751
752         /* maybe it hasn't been spooled yet */
753         if (!pjob.spooled) {
754                 /* if a job is not spooled and the process doesn't
755                    exist then kill it. This cleans up after smbd
756                    deaths */
757                 if (!process_exists_by_pid(pjob.pid)) {
758                         DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
759                                                 (unsigned int)jobid, (unsigned int)pjob.pid ));
760                         pjob_delete(ts->sharename, jobid);
761                 } else
762                         ts->total_jobs++;
763                 return 0;
764         }
765
766         /* this check only makes sense for jobs submitted from Windows clients */
767
768         if ( pjob.smbjob ) {
769                 for (i=0;i<ts->qcount;i++) {
770                         uint32 curr_jobid;
771
772                         if ( pjob.status == LPQ_DELETED )
773                                 continue;
774
775                         curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
776
777                         if (jobid == curr_jobid) {
778
779                                 /* try to clean up any jobs that need to be deleted */
780
781                                 if ( pjob.status == LPQ_DELETING ) {
782                                         int result;
783
784                                         result = (*(ts->print_if->job_delete))(
785                                                 ts->sharename, ts->lprm_command, &pjob );
786
787                                         if ( result != 0 ) {
788                                                 /* if we can't delete, then reset the job status */
789                                                 pjob.status = LPQ_QUEUED;
790                                                 pjob_store(ts->sharename, jobid, &pjob);
791                                         }
792                                         else {
793                                                 /* if we deleted the job, the remove the tdb record */
794                                                 pjob_delete(ts->sharename, jobid);
795                                                 pjob.status = LPQ_DELETED;
796                                         }
797
798                                 }
799
800                                 break;
801                         }
802                 }
803         }
804
805         /* The job isn't in the system queue - we have to assume it has
806            completed, so delete the database entry. */
807
808         if (i == ts->qcount) {
809
810                 /* A race can occur between the time a job is spooled and
811                    when it appears in the lpq output.  This happens when
812                    the job is added to printing.tdb when another smbd
813                    running print_queue_update() has completed a lpq and
814                    is currently traversing the printing tdb and deleting jobs.
815                    Don't delete the job if it was submitted after the lpq_time. */
816
817                 if (pjob.starttime < ts->lpq_time) {
818                         DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
819                                                 (unsigned int)jobid,
820                                                 (unsigned int)pjob.starttime,
821                                                 (unsigned int)ts->lpq_time ));
822                         pjob_delete(ts->sharename, jobid);
823                 } else
824                         ts->total_jobs++;
825                 return 0;
826         }
827
828         /* Save the pjob attributes we will store.
829            FIXME!!! This is the only place where queue->job
830            represents the SMB jobid      --jerry */
831
832         ts->queue[i].job = jobid;
833         ts->queue[i].size = pjob.size;
834         ts->queue[i].page_count = pjob.page_count;
835         ts->queue[i].status = pjob.status;
836         ts->queue[i].priority = 1;
837         ts->queue[i].time = pjob.starttime;
838         fstrcpy(ts->queue[i].fs_user, pjob.user);
839         fstrcpy(ts->queue[i].fs_file, pjob.jobname);
840
841         ts->total_jobs++;
842
843         return 0;
844 }
845
846 /****************************************************************************
847  Check if the print queue has been updated recently enough.
848 ****************************************************************************/
849
850 static void print_cache_flush(const char *sharename)
851 {
852         fstring key;
853         struct tdb_print_db *pdb = get_print_db_byname(sharename);
854
855         if (!pdb)
856                 return;
857         slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
858         tdb_store_int32(pdb->tdb, key, -1);
859         release_print_db(pdb);
860 }
861
862 /****************************************************************************
863  Check if someone already thinks they are doing the update.
864 ****************************************************************************/
865
866 static pid_t get_updating_pid(const char *sharename)
867 {
868         fstring keystr;
869         TDB_DATA data, key;
870         pid_t updating_pid;
871         struct tdb_print_db *pdb = get_print_db_byname(sharename);
872
873         if (!pdb)
874                 return (pid_t)-1;
875         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
876         key = string_tdb_data(keystr);
877
878         data = tdb_fetch(pdb->tdb, key);
879         release_print_db(pdb);
880         if (!data.dptr || data.dsize != sizeof(pid_t)) {
881                 SAFE_FREE(data.dptr);
882                 return (pid_t)-1;
883         }
884
885         updating_pid = IVAL(data.dptr, 0);
886         SAFE_FREE(data.dptr);
887
888         if (process_exists_by_pid(updating_pid))
889                 return updating_pid;
890
891         return (pid_t)-1;
892 }
893
894 /****************************************************************************
895  Set the fact that we're doing the update, or have finished doing the update
896  in the tdb.
897 ****************************************************************************/
898
899 static void set_updating_pid(const fstring sharename, bool updating)
900 {
901         fstring keystr;
902         TDB_DATA key;
903         TDB_DATA data;
904         pid_t updating_pid = sys_getpid();
905         uint8 buffer[4];
906
907         struct tdb_print_db *pdb = get_print_db_byname(sharename);
908
909         if (!pdb)
910                 return;
911
912         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
913         key = string_tdb_data(keystr);
914
915         DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
916                 updating ? "" : "not ",
917                 sharename ));
918
919         if ( !updating ) {
920                 tdb_delete(pdb->tdb, key);
921                 release_print_db(pdb);
922                 return;
923         }
924
925         SIVAL( buffer, 0, updating_pid);
926         data.dptr = buffer;
927         data.dsize = 4;         /* we always assume this is a 4 byte value */
928
929         tdb_store(pdb->tdb, key, data, TDB_REPLACE);
930         release_print_db(pdb);
931 }
932
933 /****************************************************************************
934  Sort print jobs by submittal time.
935 ****************************************************************************/
936
937 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
938 {
939         /* Silly cases */
940
941         if (!j1 && !j2)
942                 return 0;
943         if (!j1)
944                 return -1;
945         if (!j2)
946                 return 1;
947
948         /* Sort on job start time */
949
950         if (j1->time == j2->time)
951                 return 0;
952         return (j1->time > j2->time) ? 1 : -1;
953 }
954
955 /****************************************************************************
956  Store the sorted queue representation for later portmon retrieval.
957  Skip deleted jobs
958 ****************************************************************************/
959
960 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
961 {
962         TDB_DATA data;
963         int max_reported_jobs = lp_max_reported_jobs(pts->snum);
964         print_queue_struct *queue = pts->queue;
965         size_t len;
966         size_t i;
967         unsigned int qcount;
968
969         if (max_reported_jobs && (max_reported_jobs < pts->qcount))
970                 pts->qcount = max_reported_jobs;
971         qcount = 0;
972
973         /* Work out the size. */
974         data.dsize = 0;
975         data.dsize += tdb_pack(NULL, 0, "d", qcount);
976
977         for (i = 0; i < pts->qcount; i++) {
978                 if ( queue[i].status == LPQ_DELETED )
979                         continue;
980
981                 qcount++;
982                 data.dsize += tdb_pack(NULL, 0, "ddddddff",
983                                 (uint32)queue[i].job,
984                                 (uint32)queue[i].size,
985                                 (uint32)queue[i].page_count,
986                                 (uint32)queue[i].status,
987                                 (uint32)queue[i].priority,
988                                 (uint32)queue[i].time,
989                                 queue[i].fs_user,
990                                 queue[i].fs_file);
991         }
992
993         if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
994                 return;
995
996         len = 0;
997         len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
998         for (i = 0; i < pts->qcount; i++) {
999                 if ( queue[i].status == LPQ_DELETED )
1000                         continue;
1001
1002                 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
1003                                 (uint32)queue[i].job,
1004                                 (uint32)queue[i].size,
1005                                 (uint32)queue[i].page_count,
1006                                 (uint32)queue[i].status,
1007                                 (uint32)queue[i].priority,
1008                                 (uint32)queue[i].time,
1009                                 queue[i].fs_user,
1010                                 queue[i].fs_file);
1011         }
1012
1013         tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
1014                   TDB_REPLACE);
1015         SAFE_FREE(data.dptr);
1016         return;
1017 }
1018
1019 static TDB_DATA get_jobs_changed_data(struct tdb_print_db *pdb)
1020 {
1021         TDB_DATA data;
1022
1023         ZERO_STRUCT(data);
1024
1025         data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
1026         if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1027                 SAFE_FREE(data.dptr);
1028                 ZERO_STRUCT(data);
1029         }
1030
1031         return data;
1032 }
1033
1034 static void check_job_changed(const char *sharename, TDB_DATA data, uint32 jobid)
1035 {
1036         unsigned int i;
1037         unsigned int job_count = data.dsize / 4;
1038
1039         for (i = 0; i < job_count; i++) {
1040                 uint32 ch_jobid;
1041
1042                 ch_jobid = IVAL(data.dptr, i*4);
1043                 if (ch_jobid == jobid)
1044                         remove_from_jobs_changed(sharename, jobid);
1045         }
1046 }
1047
1048 /****************************************************************************
1049  Check if the print queue has been updated recently enough.
1050 ****************************************************************************/
1051
1052 static bool print_cache_expired(const char *sharename, bool check_pending)
1053 {
1054         fstring key;
1055         time_t last_qscan_time, time_now = time(NULL);
1056         struct tdb_print_db *pdb = get_print_db_byname(sharename);
1057         bool result = False;
1058
1059         if (!pdb)
1060                 return False;
1061
1062         snprintf(key, sizeof(key), "CACHE/%s", sharename);
1063         last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1064
1065         /*
1066          * Invalidate the queue for 3 reasons.
1067          * (1). last queue scan time == -1.
1068          * (2). Current time - last queue scan time > allowed cache time.
1069          * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1070          * This last test picks up machines for which the clock has been moved
1071          * forward, an lpq scan done and then the clock moved back. Otherwise
1072          * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1073          */
1074
1075         if (last_qscan_time == ((time_t)-1)
1076                 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1077                 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1078         {
1079                 uint32 u;
1080                 time_t msg_pending_time;
1081
1082                 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1083                         "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1084                         sharename, (int)last_qscan_time, (int)time_now,
1085                         (int)lp_lpqcachetime() ));
1086
1087                 /* check if another smbd has already sent a message to update the
1088                    queue.  Give the pending message one minute to clear and
1089                    then send another message anyways.  Make sure to check for
1090                    clocks that have been run forward and then back again. */
1091
1092                 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1093
1094                 if ( check_pending
1095                         && tdb_fetch_uint32( pdb->tdb, key, &u )
1096                         && (msg_pending_time=u) > 0
1097                         && msg_pending_time <= time_now
1098                         && (time_now - msg_pending_time) < 60 )
1099                 {
1100                         DEBUG(4,("print_cache_expired: message already pending for %s.  Accepting cache\n",
1101                                 sharename));
1102                         goto done;
1103                 }
1104
1105                 result = True;
1106         }
1107
1108 done:
1109         release_print_db(pdb);
1110         return result;
1111 }
1112
1113 /****************************************************************************
1114  main work for updating the lpq cahe for a printer queue
1115 ****************************************************************************/
1116
1117 static void print_queue_update_internal( const char *sharename,
1118                                          struct printif *current_printif,
1119                                          char *lpq_command, char *lprm_command )
1120 {
1121         int i, qcount;
1122         print_queue_struct *queue = NULL;
1123         print_status_struct status;
1124         print_status_struct old_status;
1125         struct printjob *pjob;
1126         struct traverse_struct tstruct;
1127         TDB_DATA data, key;
1128         TDB_DATA jcdata;
1129         fstring keystr, cachestr;
1130         struct tdb_print_db *pdb = get_print_db_byname(sharename);
1131
1132         if (!pdb) {
1133                 return;
1134         }
1135
1136         DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1137                 sharename, current_printif->type, lpq_command));
1138
1139         /*
1140          * Update the cache time FIRST ! Stops others even
1141          * attempting to get the lock and doing this
1142          * if the lpq takes a long time.
1143          */
1144
1145         slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1146         tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1147
1148         /* get the current queue using the appropriate interface */
1149         ZERO_STRUCT(status);
1150
1151         qcount = (*(current_printif->queue_get))(sharename,
1152                 current_printif->type,
1153                 lpq_command, &queue, &status);
1154
1155         DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1156                 qcount, (qcount != 1) ? "s" : "", sharename));
1157
1158         /* Sort the queue by submission time otherwise they are displayed
1159            in hash order. */
1160
1161         TYPESAFE_QSORT(queue, qcount, printjob_comp);
1162
1163         /*
1164           any job in the internal database that is marked as spooled
1165           and doesn't exist in the system queue is considered finished
1166           and removed from the database
1167
1168           any job in the system database but not in the internal database
1169           is added as a unix job
1170
1171           fill in any system job numbers as we go
1172         */
1173
1174         jcdata = get_jobs_changed_data(pdb);
1175
1176         for (i=0; i<qcount; i++) {
1177                 uint32 jobid = print_parse_jobid(queue[i].fs_file);
1178
1179                 if (jobid == (uint32)-1) {
1180                         /* assume its a unix print job */
1181                         print_unix_job(sharename, &queue[i], jobid);
1182                         continue;
1183                 }
1184
1185                 /* we have an active SMB print job - update its status */
1186                 pjob = print_job_find(sharename, jobid);
1187                 if (!pjob) {
1188                         /* err, somethings wrong. Probably smbd was restarted
1189                            with jobs in the queue. All we can do is treat them
1190                            like unix jobs. Pity. */
1191                         print_unix_job(sharename, &queue[i], jobid);
1192                         continue;
1193                 }
1194
1195                 pjob->sysjob = queue[i].job;
1196
1197                 /* don't reset the status on jobs to be deleted */
1198
1199                 if ( pjob->status != LPQ_DELETING )
1200                         pjob->status = queue[i].status;
1201
1202                 pjob_store(sharename, jobid, pjob);
1203
1204                 check_job_changed(sharename, jcdata, jobid);
1205         }
1206
1207         SAFE_FREE(jcdata.dptr);
1208
1209         /* now delete any queued entries that don't appear in the
1210            system queue */
1211         tstruct.queue = queue;
1212         tstruct.qcount = qcount;
1213         tstruct.snum = -1;
1214         tstruct.total_jobs = 0;
1215         tstruct.lpq_time = time(NULL);
1216         tstruct.sharename = sharename;
1217         tstruct.lprm_command = lprm_command;
1218         tstruct.print_if = current_printif;
1219
1220         tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1221
1222         /* Store the linearised queue, max jobs only. */
1223         store_queue_struct(pdb, &tstruct);
1224
1225         SAFE_FREE(tstruct.queue);
1226
1227         DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1228                                 sharename, tstruct.total_jobs ));
1229
1230         tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1231
1232         get_queue_status(sharename, &old_status);
1233         if (old_status.qcount != qcount)
1234                 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1235                                         old_status.qcount, qcount, sharename));
1236
1237         /* store the new queue status structure */
1238         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1239         key = string_tdb_data(keystr);
1240
1241         status.qcount = qcount;
1242         data.dptr = (uint8 *)&status;
1243         data.dsize = sizeof(status);
1244         tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1245
1246         /*
1247          * Update the cache time again. We want to do this call
1248          * as little as possible...
1249          */
1250
1251         slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1252         tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1253
1254         /* clear the msg pending record for this queue */
1255
1256         snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1257
1258         if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1259                 /* log a message but continue on */
1260
1261                 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1262                         sharename));
1263         }
1264
1265         release_print_db( pdb );
1266
1267         return;
1268 }
1269
1270 /****************************************************************************
1271  Update the internal database from the system print queue for a queue.
1272  obtain a lock on the print queue before proceeding (needed when mutiple
1273  smbd processes maytry to update the lpq cache concurrently).
1274 ****************************************************************************/
1275
1276 static void print_queue_update_with_lock( const char *sharename,
1277                                           struct printif *current_printif,
1278                                           char *lpq_command, char *lprm_command )
1279 {
1280         fstring keystr;
1281         struct tdb_print_db *pdb;
1282
1283         DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1284         pdb = get_print_db_byname(sharename);
1285         if (!pdb)
1286                 return;
1287
1288         if ( !print_cache_expired(sharename, False) ) {
1289                 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1290                 release_print_db(pdb);
1291                 return;
1292         }
1293
1294         /*
1295          * Check to see if someone else is doing this update.
1296          * This is essentially a mutex on the update.
1297          */
1298
1299         if (get_updating_pid(sharename) != -1) {
1300                 release_print_db(pdb);
1301                 return;
1302         }
1303
1304         /* Lock the queue for the database update */
1305
1306         slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1307         /* Only wait 10 seconds for this. */
1308         if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) == -1) {
1309                 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1310                 release_print_db(pdb);
1311                 return;
1312         }
1313
1314         /*
1315          * Ensure that no one else got in here.
1316          * If the updating pid is still -1 then we are
1317          * the winner.
1318          */
1319
1320         if (get_updating_pid(sharename) != -1) {
1321                 /*
1322                  * Someone else is doing the update, exit.
1323                  */
1324                 tdb_unlock_bystring(pdb->tdb, keystr);
1325                 release_print_db(pdb);
1326                 return;
1327         }
1328
1329         /*
1330          * We're going to do the update ourselves.
1331          */
1332
1333         /* Tell others we're doing the update. */
1334         set_updating_pid(sharename, True);
1335
1336         /*
1337          * Allow others to enter and notice we're doing
1338          * the update.
1339          */
1340
1341         tdb_unlock_bystring(pdb->tdb, keystr);
1342
1343         /* do the main work now */
1344
1345         print_queue_update_internal( sharename, current_printif,
1346                 lpq_command, lprm_command );
1347
1348         /* Delete our pid from the db. */
1349         set_updating_pid(sharename, False);
1350         release_print_db(pdb);
1351 }
1352
1353 /****************************************************************************
1354 this is the receive function of the background lpq updater
1355 ****************************************************************************/
1356 static void print_queue_receive(struct messaging_context *msg,
1357                                 void *private_data,
1358                                 uint32_t msg_type,
1359                                 struct server_id server_id,
1360                                 DATA_BLOB *data)
1361 {
1362         fstring sharename;
1363         char *lpqcommand = NULL, *lprmcommand = NULL;
1364         int printing_type;
1365         size_t len;
1366
1367         len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1368                 sharename,
1369                 &printing_type,
1370                 &lpqcommand,
1371                 &lprmcommand );
1372
1373         if ( len == -1 ) {
1374                 SAFE_FREE(lpqcommand);
1375                 SAFE_FREE(lprmcommand);
1376                 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1377                 return;
1378         }
1379
1380         print_queue_update_with_lock(sharename,
1381                 get_printer_fns_from_type((enum printing_types)printing_type),
1382                 lpqcommand, lprmcommand );
1383
1384         SAFE_FREE(lpqcommand);
1385         SAFE_FREE(lprmcommand);
1386         return;
1387 }
1388
1389 static void printing_pause_fd_handler(struct tevent_context *ev,
1390                                       struct tevent_fd *fde,
1391                                       uint16_t flags,
1392                                       void *private_data)
1393 {
1394         /*
1395          * If pause_pipe[1] is closed it means the parent smbd
1396          * and children exited or aborted.
1397          */
1398         exit_server_cleanly(NULL);
1399 }
1400
1401 static void add_child_pid(pid_t pid)
1402 {
1403         extern struct child_pid *children;
1404         struct child_pid *child;
1405         extern int num_children;
1406
1407         child = SMB_MALLOC_P(struct child_pid);
1408         if (child == NULL) {
1409                 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
1410                 return;
1411         }
1412         child->pid = pid;
1413         DLIST_ADD(children, child);
1414         num_children += 1;
1415 }
1416
1417 static pid_t background_lpq_updater_pid = -1;
1418
1419 /****************************************************************************
1420 main thread of the background lpq updater
1421 ****************************************************************************/
1422 void start_background_queue(void)
1423 {
1424         /* Use local variables for this as we don't
1425          * need to save the parent side of this, just
1426          * ensure it closes when the process exits.
1427          */
1428         int pause_pipe[2];
1429
1430         DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
1431
1432         if (pipe(pause_pipe) == -1) {
1433                 DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
1434                 exit(1);
1435         }
1436
1437         background_lpq_updater_pid = sys_fork();
1438
1439         if (background_lpq_updater_pid == -1) {
1440                 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
1441                 exit(1);
1442         }
1443
1444         /* Track the printing pid along with other smbd children */
1445         add_child_pid(background_lpq_updater_pid);
1446
1447         if(background_lpq_updater_pid == 0) {
1448                 struct tevent_fd *fde;
1449                 int ret;
1450
1451                 /* Child. */
1452                 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
1453
1454                 close(pause_pipe[0]);
1455                 pause_pipe[0] = -1;
1456
1457                 if (!NT_STATUS_IS_OK(reinit_after_fork(smbd_messaging_context(),
1458                                                        smbd_event_context(),
1459                                                        true))) {
1460                         DEBUG(0,("reinit_after_fork() failed\n"));
1461                         smb_panic("reinit_after_fork() failed");
1462                 }
1463
1464                 smbd_setup_sig_term_handler();
1465                 smbd_setup_sig_hup_handler();
1466
1467                 if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_SMBD
1468                                             |FLAG_MSG_PRINT_GENERAL)) {
1469                         exit(1);
1470                 }
1471
1472                 if (!locking_init()) {
1473                         exit(1);
1474                 }
1475
1476                 messaging_register(smbd_messaging_context(), NULL,
1477                                    MSG_PRINTER_UPDATE, print_queue_receive);
1478
1479                 fde = tevent_add_fd(smbd_event_context(), smbd_event_context(),
1480                                     pause_pipe[1], TEVENT_FD_READ,
1481                                     printing_pause_fd_handler,
1482                                     NULL);
1483                 if (!fde) {
1484                         DEBUG(0,("tevent_add_fd() failed for pause_pipe\n"));
1485                         smb_panic("tevent_add_fd() failed for pause_pipe");
1486                 }
1487
1488                 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
1489                 ret = tevent_loop_wait(smbd_event_context());
1490                 /* should not be reached */
1491                 DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
1492                          ret, (ret == 0) ? "out of events" : strerror(errno)));
1493                 exit(1);
1494         }
1495
1496         close(pause_pipe[1]);
1497 }
1498
1499 /****************************************************************************
1500 update the internal database from the system print queue for a queue
1501 ****************************************************************************/
1502
1503 static void print_queue_update(int snum, bool force)
1504 {
1505         fstring key;
1506         fstring sharename;
1507         char *lpqcommand = NULL;
1508         char *lprmcommand = NULL;
1509         uint8 *buffer = NULL;
1510         size_t len = 0;
1511         size_t newlen;
1512         struct tdb_print_db *pdb;
1513         int type;
1514         struct printif *current_printif;
1515         TALLOC_CTX *ctx = talloc_tos();
1516
1517         fstrcpy( sharename, lp_const_servicename(snum));
1518
1519         /* don't strip out characters like '$' from the printername */
1520
1521         lpqcommand = talloc_string_sub2(ctx,
1522                         lp_lpqcommand(snum),
1523                         "%p",
1524                         PRINTERNAME(snum),
1525                         false, false, false);
1526         if (!lpqcommand) {
1527                 return;
1528         }
1529         lpqcommand = talloc_sub_advanced(ctx,
1530                         lp_servicename(snum),
1531                         current_user_info.unix_name,
1532                         "",
1533                         current_user.ut.gid,
1534                         get_current_username(),
1535                         current_user_info.domain,
1536                         lpqcommand);
1537         if (!lpqcommand) {
1538                 return;
1539         }
1540
1541         lprmcommand = talloc_string_sub2(ctx,
1542                         lp_lprmcommand(snum),
1543                         "%p",
1544                         PRINTERNAME(snum),
1545                         false, false, false);
1546         if (!lprmcommand) {
1547                 return;
1548         }
1549         lprmcommand = talloc_sub_advanced(ctx,
1550                         lp_servicename(snum),
1551                         current_user_info.unix_name,
1552                         "",
1553                         current_user.ut.gid,
1554                         get_current_username(),
1555                         current_user_info.domain,
1556                         lprmcommand);
1557         if (!lprmcommand) {
1558                 return;
1559         }
1560
1561         /*
1562          * Make sure that the background queue process exists.
1563          * Otherwise just do the update ourselves
1564          */
1565
1566         if ( force || background_lpq_updater_pid == -1 ) {
1567                 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1568                 current_printif = get_printer_fns( snum );
1569                 print_queue_update_with_lock( sharename, current_printif, lpqcommand, lprmcommand );
1570
1571                 return;
1572         }
1573
1574         type = lp_printing(snum);
1575
1576         /* get the length */
1577
1578         len = tdb_pack( NULL, 0, "fdPP",
1579                 sharename,
1580                 type,
1581                 lpqcommand,
1582                 lprmcommand );
1583
1584         buffer = SMB_XMALLOC_ARRAY( uint8, len );
1585
1586         /* now pack the buffer */
1587         newlen = tdb_pack( buffer, len, "fdPP",
1588                 sharename,
1589                 type,
1590                 lpqcommand,
1591                 lprmcommand );
1592
1593         SMB_ASSERT( newlen == len );
1594
1595         DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1596                 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1597                 sharename, type, lpqcommand, lprmcommand ));
1598
1599         /* here we set a msg pending record for other smbd processes
1600            to throttle the number of duplicate print_queue_update msgs
1601            sent.  */
1602
1603         pdb = get_print_db_byname(sharename);
1604         if (!pdb) {
1605                 SAFE_FREE(buffer);
1606                 return;
1607         }
1608
1609         snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1610
1611         if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1612                 /* log a message but continue on */
1613
1614                 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1615                         sharename));
1616         }
1617
1618         release_print_db( pdb );
1619
1620         /* finally send the message */
1621
1622         messaging_send_buf(smbd_messaging_context(),
1623                            pid_to_procid(background_lpq_updater_pid),
1624                            MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1625
1626         SAFE_FREE( buffer );
1627
1628         return;
1629 }
1630
1631 /****************************************************************************
1632  Create/Update an entry in the print tdb that will allow us to send notify
1633  updates only to interested smbd's.
1634 ****************************************************************************/
1635
1636 bool print_notify_register_pid(int snum)
1637 {
1638         TDB_DATA data;
1639         struct tdb_print_db *pdb = NULL;
1640         TDB_CONTEXT *tdb = NULL;
1641         const char *printername;
1642         uint32 mypid = (uint32)sys_getpid();
1643         bool ret = False;
1644         size_t i;
1645
1646         /* if (snum == -1), then the change notify request was
1647            on a print server handle and we need to register on
1648            all print queus */
1649
1650         if (snum == -1)
1651         {
1652                 int num_services = lp_numservices();
1653                 int idx;
1654
1655                 for ( idx=0; idx<num_services; idx++ ) {
1656                         if (lp_snum_ok(idx) && lp_print_ok(idx) )
1657                                 print_notify_register_pid(idx);
1658                 }
1659
1660                 return True;
1661         }
1662         else /* register for a specific printer */
1663         {
1664                 printername = lp_const_servicename(snum);
1665                 pdb = get_print_db_byname(printername);
1666                 if (!pdb)
1667                         return False;
1668                 tdb = pdb->tdb;
1669         }
1670
1671         if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1672                 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1673                                         printername));
1674                 if (pdb)
1675                         release_print_db(pdb);
1676                 return False;
1677         }
1678
1679         data = get_printer_notify_pid_list( tdb, printername, True );
1680
1681         /* Add ourselves and increase the refcount. */
1682
1683         for (i = 0; i < data.dsize; i += 8) {
1684                 if (IVAL(data.dptr,i) == mypid) {
1685                         uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1686                         SIVAL(data.dptr, i+4, new_refcount);
1687                         break;
1688                 }
1689         }
1690
1691         if (i == data.dsize) {
1692                 /* We weren't in the list. Realloc. */
1693                 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1694                 if (!data.dptr) {
1695                         DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1696                                                 printername));
1697                         goto done;
1698                 }
1699                 data.dsize += 8;
1700                 SIVAL(data.dptr,data.dsize - 8,mypid);
1701                 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1702         }
1703
1704         /* Store back the record. */
1705         if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1706                 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1707 list for printer %s\n", printername));
1708                 goto done;
1709         }
1710
1711         ret = True;
1712
1713  done:
1714
1715         tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1716         if (pdb)
1717                 release_print_db(pdb);
1718         SAFE_FREE(data.dptr);
1719         return ret;
1720 }
1721
1722 /****************************************************************************
1723  Update an entry in the print tdb that will allow us to send notify
1724  updates only to interested smbd's.
1725 ****************************************************************************/
1726
1727 bool print_notify_deregister_pid(int snum)
1728 {
1729         TDB_DATA data;
1730         struct tdb_print_db *pdb = NULL;
1731         TDB_CONTEXT *tdb = NULL;
1732         const char *printername;
1733         uint32 mypid = (uint32)sys_getpid();
1734         size_t i;
1735         bool ret = False;
1736
1737         /* if ( snum == -1 ), we are deregister a print server handle
1738            which means to deregister on all print queues */
1739
1740         if (snum == -1)
1741         {
1742                 int num_services = lp_numservices();
1743                 int idx;
1744
1745                 for ( idx=0; idx<num_services; idx++ ) {
1746                         if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1747                                 print_notify_deregister_pid(idx);
1748                 }
1749
1750                 return True;
1751         }
1752         else /* deregister a specific printer */
1753         {
1754                 printername = lp_const_servicename(snum);
1755                 pdb = get_print_db_byname(printername);
1756                 if (!pdb)
1757                         return False;
1758                 tdb = pdb->tdb;
1759         }
1760
1761         if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1762                 DEBUG(0,("print_notify_register_pid: Failed to lock \
1763 printer %s database\n", printername));
1764                 if (pdb)
1765                         release_print_db(pdb);
1766                 return False;
1767         }
1768
1769         data = get_printer_notify_pid_list( tdb, printername, True );
1770
1771         /* Reduce refcount. Remove ourselves if zero. */
1772
1773         for (i = 0; i < data.dsize; ) {
1774                 if (IVAL(data.dptr,i) == mypid) {
1775                         uint32 refcount = IVAL(data.dptr, i+4);
1776
1777                         refcount--;
1778
1779                         if (refcount == 0) {
1780                                 if (data.dsize - i > 8)
1781                                         memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1782                                 data.dsize -= 8;
1783                                 continue;
1784                         }
1785                         SIVAL(data.dptr, i+4, refcount);
1786                 }
1787
1788                 i += 8;
1789         }
1790
1791         if (data.dsize == 0)
1792                 SAFE_FREE(data.dptr);
1793
1794         /* Store back the record. */
1795         if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1796                 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1797 list for printer %s\n", printername));
1798                 goto done;
1799         }
1800
1801         ret = True;
1802
1803   done:
1804
1805         tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1806         if (pdb)
1807                 release_print_db(pdb);
1808         SAFE_FREE(data.dptr);
1809         return ret;
1810 }
1811
1812 /****************************************************************************
1813  Check if a jobid is valid. It is valid if it exists in the database.
1814 ****************************************************************************/
1815
1816 bool print_job_exists(const char* sharename, uint32 jobid)
1817 {
1818         struct tdb_print_db *pdb = get_print_db_byname(sharename);
1819         bool ret;
1820         uint32_t tmp;
1821
1822         if (!pdb)
1823                 return False;
1824         ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
1825         release_print_db(pdb);
1826         return ret;
1827 }
1828
1829 /****************************************************************************
1830  Give the fd used for a jobid.
1831 ****************************************************************************/
1832
1833 int print_job_fd(const char* sharename, uint32 jobid)
1834 {
1835         struct printjob *pjob = print_job_find(sharename, jobid);
1836         if (!pjob)
1837                 return -1;
1838         /* don't allow another process to get this info - it is meaningless */
1839         if (pjob->pid != sys_getpid())
1840                 return -1;
1841         return pjob->fd;
1842 }
1843
1844 /****************************************************************************
1845  Give the filename used for a jobid.
1846  Only valid for the process doing the spooling and when the job
1847  has not been spooled.
1848 ****************************************************************************/
1849
1850 char *print_job_fname(const char* sharename, uint32 jobid)
1851 {
1852         struct printjob *pjob = print_job_find(sharename, jobid);
1853         if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
1854                 return NULL;
1855         return pjob->filename;
1856 }
1857
1858
1859 /****************************************************************************
1860  Give the filename used for a jobid.
1861  Only valid for the process doing the spooling and when the job
1862  has not been spooled.
1863 ****************************************************************************/
1864
1865 NT_DEVICEMODE *print_job_devmode(const char* sharename, uint32 jobid)
1866 {
1867         struct printjob *pjob = print_job_find(sharename, jobid);
1868
1869         if ( !pjob )
1870                 return NULL;
1871
1872         return pjob->nt_devmode;
1873 }
1874
1875 /****************************************************************************
1876  Set the place in the queue for a job.
1877 ****************************************************************************/
1878
1879 bool print_job_set_place(const char *sharename, uint32 jobid, int place)
1880 {
1881         DEBUG(2,("print_job_set_place not implemented yet\n"));
1882         return False;
1883 }
1884
1885 /****************************************************************************
1886  Set the name of a job. Only possible for owner.
1887 ****************************************************************************/
1888
1889 bool print_job_set_name(const char *sharename, uint32 jobid, char *name)
1890 {
1891         struct printjob *pjob;
1892
1893         pjob = print_job_find(sharename, jobid);
1894         if (!pjob || pjob->pid != sys_getpid())
1895                 return False;
1896
1897         fstrcpy(pjob->jobname, name);
1898         return pjob_store(sharename, jobid, pjob);
1899 }
1900
1901 /***************************************************************************
1902  Remove a jobid from the 'jobs changed' list.
1903 ***************************************************************************/
1904
1905 static bool remove_from_jobs_changed(const char* sharename, uint32 jobid)
1906 {
1907         struct tdb_print_db *pdb = get_print_db_byname(sharename);
1908         TDB_DATA data, key;
1909         size_t job_count, i;
1910         bool ret = False;
1911         bool gotlock = False;
1912
1913         if (!pdb) {
1914                 return False;
1915         }
1916
1917         ZERO_STRUCT(data);
1918
1919         key = string_tdb_data("INFO/jobs_changed");
1920
1921         if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
1922                 goto out;
1923
1924         gotlock = True;
1925
1926         data = tdb_fetch(pdb->tdb, key);
1927
1928         if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
1929                 goto out;
1930
1931         job_count = data.dsize / 4;
1932         for (i = 0; i < job_count; i++) {
1933                 uint32 ch_jobid;
1934
1935                 ch_jobid = IVAL(data.dptr, i*4);
1936                 if (ch_jobid == jobid) {
1937                         if (i < job_count -1 )
1938                                 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
1939                         data.dsize -= 4;
1940                         if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
1941                                 goto out;
1942                         break;
1943                 }
1944         }
1945
1946         ret = True;
1947   out:
1948
1949         if (gotlock)
1950                 tdb_chainunlock(pdb->tdb, key);
1951         SAFE_FREE(data.dptr);
1952         release_print_db(pdb);
1953         if (ret)
1954                 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
1955         else
1956                 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
1957         return ret;
1958 }
1959
1960 /****************************************************************************
1961  Delete a print job - don't update queue.
1962 ****************************************************************************/
1963
1964 static bool print_job_delete1(int snum, uint32 jobid)
1965 {
1966         const char* sharename = lp_const_servicename(snum);
1967         struct printjob *pjob = print_job_find(sharename, jobid);
1968         int result = 0;
1969         struct printif *current_printif = get_printer_fns( snum );
1970
1971         if (!pjob)
1972                 return False;
1973
1974         /*
1975          * If already deleting just return.
1976          */
1977
1978         if (pjob->status == LPQ_DELETING)
1979                 return True;
1980
1981         /* Hrm - we need to be able to cope with deleting a job before it
1982            has reached the spooler.  Just mark it as LPQ_DELETING and
1983            let the print_queue_update() code rmeove the record */
1984
1985
1986         if (pjob->sysjob == -1) {
1987                 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
1988         }
1989
1990         /* Set the tdb entry to be deleting. */
1991
1992         pjob->status = LPQ_DELETING;
1993         pjob_store(sharename, jobid, pjob);
1994
1995         if (pjob->spooled && pjob->sysjob != -1)
1996         {
1997                 result = (*(current_printif->job_delete))(
1998                         PRINTERNAME(snum),
1999                         lp_lprmcommand(snum),
2000                         pjob);
2001
2002                 /* Delete the tdb entry if the delete succeeded or the job hasn't
2003                    been spooled. */
2004
2005                 if (result == 0) {
2006                         struct tdb_print_db *pdb = get_print_db_byname(sharename);
2007                         int njobs = 1;
2008
2009                         if (!pdb)
2010                                 return False;
2011                         pjob_delete(sharename, jobid);
2012                         /* Ensure we keep a rough count of the number of total jobs... */
2013                         tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
2014                         release_print_db(pdb);
2015                 }
2016         }
2017
2018         remove_from_jobs_changed( sharename, jobid );
2019
2020         return (result == 0);
2021 }
2022
2023 /****************************************************************************
2024  Return true if the current user owns the print job.
2025 ****************************************************************************/
2026
2027 static bool is_owner(struct auth_serversupplied_info *server_info,
2028                      const char *servicename,
2029                      uint32 jobid)
2030 {
2031         struct printjob *pjob = print_job_find(servicename, jobid);
2032
2033         if (!pjob || !server_info)
2034                 return False;
2035
2036         return strequal(pjob->user, server_info->sanitized_username);
2037 }
2038
2039 /****************************************************************************
2040  Delete a print job.
2041 ****************************************************************************/
2042
2043 bool print_job_delete(struct auth_serversupplied_info *server_info, int snum,
2044                       uint32 jobid, WERROR *errcode)
2045 {
2046         const char* sharename = lp_const_servicename( snum );
2047         struct printjob *pjob;
2048         bool    owner;
2049         char    *fname;
2050
2051         *errcode = WERR_OK;
2052
2053         owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2054
2055         /* Check access against security descriptor or whether the user
2056            owns their job. */
2057
2058         if (!owner &&
2059             !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2060                 DEBUG(3, ("delete denied by security descriptor\n"));
2061                 *errcode = WERR_ACCESS_DENIED;
2062
2063                 /* BEGIN_ADMIN_LOG */
2064                 sys_adminlog( LOG_ERR,
2065                               "Permission denied-- user not allowed to delete, \
2066 pause, or resume print job. User name: %s. Printer name: %s.",
2067                               uidtoname(server_info->utok.uid),
2068                               PRINTERNAME(snum) );
2069                 /* END_ADMIN_LOG */
2070
2071                 return False;
2072         }
2073
2074         /*
2075          * get the spooled filename of the print job
2076          * if this works, then the file has not been spooled
2077          * to the underlying print system.  Just delete the
2078          * spool file & return.
2079          */
2080
2081         if ( (fname = print_job_fname( sharename, jobid )) != NULL )
2082         {
2083                 /* remove the spool file */
2084                 DEBUG(10,("print_job_delete: Removing spool file [%s]\n", fname ));
2085                 if ( unlink( fname ) == -1 ) {
2086                         *errcode = map_werror_from_unix(errno);
2087                         return False;
2088                 }
2089         }
2090
2091         if (!print_job_delete1(snum, jobid)) {
2092                 *errcode = WERR_ACCESS_DENIED;
2093                 return False;
2094         }
2095
2096         /* force update the database and say the delete failed if the
2097            job still exists */
2098
2099         print_queue_update(snum, True);
2100
2101         pjob = print_job_find(sharename, jobid);
2102         if ( pjob && (pjob->status != LPQ_DELETING) )
2103                 *errcode = WERR_ACCESS_DENIED;
2104
2105         return (pjob == NULL );
2106 }
2107
2108 /****************************************************************************
2109  Pause a job.
2110 ****************************************************************************/
2111
2112 bool print_job_pause(struct auth_serversupplied_info *server_info, int snum,
2113                      uint32 jobid, WERROR *errcode)
2114 {
2115         const char* sharename = lp_const_servicename(snum);
2116         struct printjob *pjob;
2117         int ret = -1;
2118         struct printif *current_printif = get_printer_fns( snum );
2119
2120         pjob = print_job_find(sharename, jobid);
2121
2122         if (!pjob || !server_info) {
2123                 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2124                         (unsigned int)jobid ));
2125                 return False;
2126         }
2127
2128         if (!pjob->spooled || pjob->sysjob == -1) {
2129                 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2130                         (int)pjob->sysjob, (unsigned int)jobid ));
2131                 return False;
2132         }
2133
2134         if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2135             !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2136                 DEBUG(3, ("pause denied by security descriptor\n"));
2137
2138                 /* BEGIN_ADMIN_LOG */
2139                 sys_adminlog( LOG_ERR,
2140                         "Permission denied-- user not allowed to delete, \
2141 pause, or resume print job. User name: %s. Printer name: %s.",
2142                               uidtoname(server_info->utok.uid),
2143                               PRINTERNAME(snum) );
2144                 /* END_ADMIN_LOG */
2145
2146                 *errcode = WERR_ACCESS_DENIED;
2147                 return False;
2148         }
2149
2150         /* need to pause the spooled entry */
2151         ret = (*(current_printif->job_pause))(snum, pjob);
2152
2153         if (ret != 0) {
2154                 *errcode = WERR_INVALID_PARAM;
2155                 return False;
2156         }
2157
2158         /* force update the database */
2159         print_cache_flush(lp_const_servicename(snum));
2160
2161         /* Send a printer notify message */
2162
2163         notify_job_status(sharename, jobid, JOB_STATUS_PAUSED);
2164
2165         /* how do we tell if this succeeded? */
2166
2167         return True;
2168 }
2169
2170 /****************************************************************************
2171  Resume a job.
2172 ****************************************************************************/
2173
2174 bool print_job_resume(struct auth_serversupplied_info *server_info, int snum,
2175                       uint32 jobid, WERROR *errcode)
2176 {
2177         const char *sharename = lp_const_servicename(snum);
2178         struct printjob *pjob;
2179         int ret;
2180         struct printif *current_printif = get_printer_fns( snum );
2181
2182         pjob = print_job_find(sharename, jobid);
2183
2184         if (!pjob || !server_info) {
2185                 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2186                         (unsigned int)jobid ));
2187                 return False;
2188         }
2189
2190         if (!pjob->spooled || pjob->sysjob == -1) {
2191                 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2192                         (int)pjob->sysjob, (unsigned int)jobid ));
2193                 return False;
2194         }
2195
2196         if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2197             !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2198                 DEBUG(3, ("resume denied by security descriptor\n"));
2199                 *errcode = WERR_ACCESS_DENIED;
2200
2201                 /* BEGIN_ADMIN_LOG */
2202                 sys_adminlog( LOG_ERR,
2203                          "Permission denied-- user not allowed to delete, \
2204 pause, or resume print job. User name: %s. Printer name: %s.",
2205                               uidtoname(server_info->utok.uid),
2206                               PRINTERNAME(snum) );
2207                 /* END_ADMIN_LOG */
2208                 return False;
2209         }
2210
2211         ret = (*(current_printif->job_resume))(snum, pjob);
2212
2213         if (ret != 0) {
2214                 *errcode = WERR_INVALID_PARAM;
2215                 return False;
2216         }
2217
2218         /* force update the database */
2219         print_cache_flush(lp_const_servicename(snum));
2220
2221         /* Send a printer notify message */
2222
2223         notify_job_status(sharename, jobid, JOB_STATUS_QUEUED);
2224
2225         return True;
2226 }
2227
2228 /****************************************************************************
2229  Write to a print file.
2230 ****************************************************************************/
2231
2232 ssize_t print_job_write(int snum, uint32 jobid, const char *buf, SMB_OFF_T pos, size_t size)
2233 {
2234         const char* sharename = lp_const_servicename(snum);
2235         int return_code;
2236         struct printjob *pjob;
2237
2238         pjob = print_job_find(sharename, jobid);
2239
2240         if (!pjob)
2241                 return -1;
2242         /* don't allow another process to get this info - it is meaningless */
2243         if (pjob->pid != sys_getpid())
2244                 return -1;
2245
2246         return_code = write_data_at_offset(pjob->fd, buf, size, pos);
2247
2248         if (return_code>0) {
2249                 pjob->size += size;
2250                 pjob_store(sharename, jobid, pjob);
2251         }
2252         return return_code;
2253 }
2254
2255 /****************************************************************************
2256  Get the queue status - do not update if db is out of date.
2257 ****************************************************************************/
2258
2259 static int get_queue_status(const char* sharename, print_status_struct *status)
2260 {
2261         fstring keystr;
2262         TDB_DATA data;
2263         struct tdb_print_db *pdb = get_print_db_byname(sharename);
2264         int len;
2265
2266         if (status) {
2267                 ZERO_STRUCTP(status);
2268         }
2269
2270         if (!pdb)
2271                 return 0;
2272
2273         if (status) {
2274                 fstr_sprintf(keystr, "STATUS/%s", sharename);
2275                 data = tdb_fetch(pdb->tdb, string_tdb_data(keystr));
2276                 if (data.dptr) {
2277                         if (data.dsize == sizeof(print_status_struct))
2278                                 /* this memcpy is ok since the status struct was
2279                                    not packed before storing it in the tdb */
2280                                 memcpy(status, data.dptr, sizeof(print_status_struct));
2281                         SAFE_FREE(data.dptr);
2282                 }
2283         }
2284         len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2285         release_print_db(pdb);
2286         return (len == -1 ? 0 : len);
2287 }
2288
2289 /****************************************************************************
2290  Determine the number of jobs in a queue.
2291 ****************************************************************************/
2292
2293 int print_queue_length(int snum, print_status_struct *pstatus)
2294 {
2295         const char* sharename = lp_const_servicename( snum );
2296         print_status_struct status;
2297         int len;
2298
2299         ZERO_STRUCT( status );
2300
2301         /* make sure the database is up to date */
2302         if (print_cache_expired(lp_const_servicename(snum), True))
2303                 print_queue_update(snum, False);
2304
2305         /* also fetch the queue status */
2306         memset(&status, 0, sizeof(status));
2307         len = get_queue_status(sharename, &status);
2308
2309         if (pstatus)
2310                 *pstatus = status;
2311
2312         return len;
2313 }
2314
2315 /***************************************************************************
2316  Allocate a jobid. Hold the lock for as short a time as possible.
2317 ***************************************************************************/
2318
2319 static bool allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char *sharename, uint32 *pjobid)
2320 {
2321         int i;
2322         uint32 jobid;
2323
2324         *pjobid = (uint32)-1;
2325
2326         for (i = 0; i < 3; i++) {
2327                 /* Lock the database - only wait 20 seconds. */
2328                 if (tdb_lock_bystring_with_timeout(pdb->tdb, "INFO/nextjob", 20) == -1) {
2329                         DEBUG(0,("allocate_print_jobid: failed to lock printing database %s\n", sharename));
2330                         return False;
2331                 }
2332
2333                 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2334                         if (tdb_error(pdb->tdb) != TDB_ERR_NOEXIST) {
2335                                 DEBUG(0, ("allocate_print_jobid: failed to fetch INFO/nextjob for print queue %s\n",
2336                                         sharename));
2337                                 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2338                                 return False;
2339                         }
2340                         DEBUG(10,("allocate_print_jobid: no existing jobid in %s\n", sharename));
2341                         jobid = 0;
2342                 }
2343
2344                 DEBUG(10,("allocate_print_jobid: read jobid %u from %s\n", jobid, sharename));
2345
2346                 jobid = NEXT_JOBID(jobid);
2347
2348                 if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
2349                         DEBUG(3, ("allocate_print_jobid: failed to store INFO/nextjob.\n"));
2350                         tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2351                         return False;
2352                 }
2353
2354                 /* We've finished with the INFO/nextjob lock. */
2355                 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2356
2357                 if (!print_job_exists(sharename, jobid)) {
2358                         break;
2359                 }
2360                 DEBUG(10,("allocate_print_jobid: found jobid %u in %s\n", jobid, sharename));
2361         }
2362
2363         if (i > 2) {
2364                 DEBUG(0, ("allocate_print_jobid: failed to allocate a print job for queue %s\n",
2365                         sharename));
2366                 /* Probably full... */
2367                 errno = ENOSPC;
2368                 return False;
2369         }
2370
2371         /* Store a dummy placeholder. */
2372         {
2373                 uint32_t tmp;
2374                 TDB_DATA dum;
2375                 dum.dptr = NULL;
2376                 dum.dsize = 0;
2377                 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2378                               TDB_INSERT) == -1) {
2379                         DEBUG(3, ("allocate_print_jobid: jobid (%d) failed to store placeholder.\n",
2380                                 jobid ));
2381                         return False;
2382                 }
2383         }
2384
2385         *pjobid = jobid;
2386         return True;
2387 }
2388
2389 /***************************************************************************
2390  Append a jobid to the 'jobs changed' list.
2391 ***************************************************************************/
2392
2393 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32 jobid)
2394 {
2395         TDB_DATA data;
2396         uint32 store_jobid;
2397
2398         SIVAL(&store_jobid, 0, jobid);
2399         data.dptr = (uint8 *)&store_jobid;
2400         data.dsize = 4;
2401
2402         DEBUG(10,("add_to_jobs_changed: Added jobid %u\n", (unsigned int)jobid ));
2403
2404         return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
2405                            data) == 0);
2406 }
2407
2408 /***************************************************************************
2409  Start spooling a job - return the jobid.
2410 ***************************************************************************/
2411
2412 uint32 print_job_start(struct auth_serversupplied_info *server_info, int snum,
2413                        const char *jobname, NT_DEVICEMODE *nt_devmode )
2414 {
2415         uint32 jobid;
2416         char *path;
2417         struct printjob pjob;
2418         const char *sharename = lp_const_servicename(snum);
2419         struct tdb_print_db *pdb = get_print_db_byname(sharename);
2420         int njobs;
2421
2422         errno = 0;
2423
2424         if (!pdb)
2425                 return (uint32)-1;
2426
2427         if (!print_access_check(server_info, snum, PRINTER_ACCESS_USE)) {
2428                 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
2429                 release_print_db(pdb);
2430                 return (uint32)-1;
2431         }
2432
2433         if (!print_time_access_check(lp_servicename(snum))) {
2434                 DEBUG(3, ("print_job_start: job start denied by time check\n"));
2435                 release_print_db(pdb);
2436                 return (uint32)-1;
2437         }
2438
2439         path = lp_pathname(snum);
2440
2441         /* see if we have sufficient disk space */
2442         if (lp_minprintspace(snum)) {
2443                 uint64_t dspace, dsize;
2444                 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
2445                     dspace < 2*(uint64_t)lp_minprintspace(snum)) {
2446                         DEBUG(3, ("print_job_start: disk space check failed.\n"));
2447                         release_print_db(pdb);
2448                         errno = ENOSPC;
2449                         return (uint32)-1;
2450                 }
2451         }
2452
2453         /* for autoloaded printers, check that the printcap entry still exists */
2454         if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum))) {
2455                 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
2456                 release_print_db(pdb);
2457                 errno = ENOENT;
2458                 return (uint32)-1;
2459         }
2460
2461         /* Insure the maximum queue size is not violated */
2462         if ((njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
2463                 DEBUG(3, ("print_job_start: Queue %s number of jobs (%d) larger than max printjobs per queue (%d).\n",
2464                         sharename, njobs, lp_maxprintjobs(snum) ));
2465                 release_print_db(pdb);
2466                 errno = ENOSPC;
2467                 return (uint32)-1;
2468         }
2469
2470         DEBUG(10,("print_job_start: Queue %s number of jobs (%d), max printjobs = %d\n",
2471                 sharename, njobs, lp_maxprintjobs(snum) ));
2472
2473         if (!allocate_print_jobid(pdb, snum, sharename, &jobid))
2474                 goto fail;
2475
2476         /* create the database entry */
2477
2478         ZERO_STRUCT(pjob);
2479
2480         pjob.pid = sys_getpid();
2481         pjob.sysjob = -1;
2482         pjob.fd = -1;
2483         pjob.starttime = time(NULL);
2484         pjob.status = LPQ_SPOOLING;
2485         pjob.size = 0;
2486         pjob.spooled = False;
2487         pjob.smbjob = True;
2488         pjob.nt_devmode = nt_devmode;
2489
2490         fstrcpy(pjob.jobname, jobname);
2491
2492         fstrcpy(pjob.user, lp_printjob_username(snum));
2493         standard_sub_advanced(sharename, server_info->sanitized_username,
2494                               path, server_info->utok.gid,
2495                               server_info->sanitized_username,
2496                               pdb_get_domain(server_info->sam_account),
2497                               pjob.user, sizeof(pjob.user)-1);
2498         /* ensure NULL termination */
2499         pjob.user[sizeof(pjob.user)-1] = '\0';
2500
2501         fstrcpy(pjob.queuename, lp_const_servicename(snum));
2502
2503         /* we have a job entry - now create the spool file */
2504         slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX",
2505                  path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2506         pjob.fd = mkstemp(pjob.filename);
2507
2508         if (pjob.fd == -1) {
2509                 if (errno == EACCES) {
2510                         /* Common setup error, force a report. */
2511                         DEBUG(0, ("print_job_start: insufficient permissions \
2512 to open spool file %s.\n", pjob.filename));
2513                 } else {
2514                         /* Normal case, report at level 3 and above. */
2515                         DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
2516                         DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
2517                 }
2518                 goto fail;
2519         }
2520
2521         pjob_store(sharename, jobid, &pjob);
2522
2523         /* Update the 'jobs changed' entry used by print_queue_status. */
2524         add_to_jobs_changed(pdb, jobid);
2525
2526         /* Ensure we keep a rough count of the number of total jobs... */
2527         tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2528
2529         release_print_db(pdb);
2530
2531         return jobid;
2532
2533  fail:
2534         if (jobid != -1)
2535                 pjob_delete(sharename, jobid);
2536
2537         release_print_db(pdb);
2538
2539         DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
2540         return (uint32)-1;
2541 }
2542
2543 /****************************************************************************
2544  Update the number of pages spooled to jobid
2545 ****************************************************************************/
2546
2547 void print_job_endpage(int snum, uint32 jobid)
2548 {
2549         const char* sharename = lp_const_servicename(snum);
2550         struct printjob *pjob;
2551
2552         pjob = print_job_find(sharename, jobid);
2553         if (!pjob)
2554                 return;
2555         /* don't allow another process to get this info - it is meaningless */
2556         if (pjob->pid != sys_getpid())
2557                 return;
2558
2559         pjob->page_count++;
2560         pjob_store(sharename, jobid, pjob);
2561 }
2562
2563 /****************************************************************************
2564  Print a file - called on closing the file. This spools the job.
2565  If normal close is false then we're tearing down the jobs - treat as an
2566  error.
2567 ****************************************************************************/
2568
2569 bool print_job_end(int snum, uint32 jobid, enum file_close_type close_type)
2570 {
2571         const char* sharename = lp_const_servicename(snum);
2572         struct printjob *pjob;
2573         int ret;
2574         SMB_STRUCT_STAT sbuf;
2575         struct printif *current_printif = get_printer_fns( snum );
2576
2577         pjob = print_job_find(sharename, jobid);
2578
2579         if (!pjob)
2580                 return False;
2581
2582         if (pjob->spooled || pjob->pid != sys_getpid())
2583                 return False;
2584
2585         if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
2586             (sys_fstat(pjob->fd, &sbuf, false) == 0)) {
2587                 pjob->size = sbuf.st_ex_size;
2588                 close(pjob->fd);
2589                 pjob->fd = -1;
2590         } else {
2591
2592                 /*
2593                  * Not a normal close or we couldn't stat the job file,
2594                  * so something has gone wrong. Cleanup.
2595                  */
2596                 close(pjob->fd);
2597                 pjob->fd = -1;
2598                 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
2599                 goto fail;
2600         }
2601
2602         /* Technically, this is not quite right. If the printer has a separator
2603          * page turned on, the NT spooler prints the separator page even if the
2604          * print job is 0 bytes. 010215 JRR */
2605         if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
2606                 /* don't bother spooling empty files or something being deleted. */
2607                 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
2608                         pjob->filename, pjob->size ? "deleted" : "zero length" ));
2609                 unlink(pjob->filename);
2610                 pjob_delete(sharename, jobid);
2611                 return True;
2612         }
2613
2614         pjob->smbjob = jobid;
2615
2616         ret = (*(current_printif->job_submit))(snum, pjob);
2617
2618         if (ret)
2619                 goto fail;
2620
2621         /* The print job has been successfully handed over to the back-end */
2622
2623         pjob->spooled = True;
2624         pjob->status = LPQ_QUEUED;
2625         pjob_store(sharename, jobid, pjob);
2626
2627         /* make sure the database is up to date */
2628         if (print_cache_expired(lp_const_servicename(snum), True))
2629                 print_queue_update(snum, False);
2630
2631         return True;
2632
2633 fail:
2634
2635         /* The print job was not successfully started. Cleanup */
2636         /* Still need to add proper error return propagation! 010122:JRR */
2637         unlink(pjob->filename);
2638         pjob_delete(sharename, jobid);
2639         return False;
2640 }
2641
2642 /****************************************************************************
2643  Get a snapshot of jobs in the system without traversing.
2644 ****************************************************************************/
2645
2646 static bool get_stored_queue_info(struct tdb_print_db *pdb, int snum, int *pcount, print_queue_struct **ppqueue)
2647 {
2648         TDB_DATA data, cgdata;
2649         print_queue_struct *queue = NULL;
2650         uint32 qcount = 0;
2651         uint32 extra_count = 0;
2652         int total_count = 0;
2653         size_t len = 0;
2654         uint32 i;
2655         int max_reported_jobs = lp_max_reported_jobs(snum);
2656         bool ret = False;
2657         const char* sharename = lp_servicename(snum);
2658
2659         /* make sure the database is up to date */
2660         if (print_cache_expired(lp_const_servicename(snum), True))
2661                 print_queue_update(snum, False);
2662
2663         *pcount = 0;
2664         *ppqueue = NULL;
2665
2666         ZERO_STRUCT(data);
2667         ZERO_STRUCT(cgdata);
2668
2669         /* Get the stored queue data. */
2670         data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
2671
2672         if (data.dptr && data.dsize >= sizeof(qcount))
2673                 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
2674
2675         /* Get the changed jobs list. */
2676         cgdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
2677         if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
2678                 extra_count = cgdata.dsize/4;
2679
2680         DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
2681
2682         /* Allocate the queue size. */
2683         if (qcount == 0 && extra_count == 0)
2684                 goto out;
2685
2686         if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
2687                 goto out;
2688
2689         /* Retrieve the linearised queue data. */
2690
2691         for( i  = 0; i < qcount; i++) {
2692                 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
2693                 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
2694                                 &qjob,
2695                                 &qsize,
2696                                 &qpage_count,
2697                                 &qstatus,
2698                                 &qpriority,
2699                                 &qtime,
2700                                 queue[i].fs_user,
2701                                 queue[i].fs_file);
2702                 queue[i].job = qjob;
2703                 queue[i].size = qsize;
2704                 queue[i].page_count = qpage_count;
2705                 queue[i].status = qstatus;
2706                 queue[i].priority = qpriority;
2707                 queue[i].time = qtime;
2708         }
2709
2710         total_count = qcount;
2711
2712         /* Add in the changed jobids. */
2713         for( i  = 0; i < extra_count; i++) {
2714                 uint32 jobid;
2715                 struct printjob *pjob;
2716
2717                 jobid = IVAL(cgdata.dptr, i*4);
2718                 DEBUG(5,("get_stored_queue_info: changed job = %u\n", (unsigned int)jobid));
2719                 pjob = print_job_find(lp_const_servicename(snum), jobid);
2720                 if (!pjob) {
2721                         DEBUG(5,("get_stored_queue_info: failed to find changed job = %u\n", (unsigned int)jobid));
2722                         remove_from_jobs_changed(sharename, jobid);
2723                         continue;
2724                 }
2725
2726                 queue[total_count].job = jobid;
2727                 queue[total_count].size = pjob->size;
2728                 queue[total_count].page_count = pjob->page_count;
2729                 queue[total_count].status = pjob->status;
2730                 queue[total_count].priority = 1;
2731                 queue[total_count].time = pjob->starttime;
2732                 fstrcpy(queue[total_count].fs_user, pjob->user);
2733                 fstrcpy(queue[total_count].fs_file, pjob->jobname);
2734                 total_count++;
2735         }
2736
2737         /* Sort the queue by submission time otherwise they are displayed
2738            in hash order. */
2739
2740         TYPESAFE_QSORT(queue, total_count, printjob_comp);
2741
2742         DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
2743
2744         if (max_reported_jobs && total_count > max_reported_jobs)
2745                 total_count = max_reported_jobs;
2746
2747         *ppqueue = queue;
2748         *pcount = total_count;
2749
2750         ret = True;
2751
2752   out:
2753
2754         SAFE_FREE(data.dptr);
2755         SAFE_FREE(cgdata.dptr);
2756         return ret;
2757 }
2758
2759 /****************************************************************************
2760  Get a printer queue listing.
2761  set queue = NULL and status = NULL if you just want to update the cache
2762 ****************************************************************************/
2763
2764 int print_queue_status(int snum,
2765                        print_queue_struct **ppqueue,
2766                        print_status_struct *status)
2767 {
2768         fstring keystr;
2769         TDB_DATA data, key;
2770         const char *sharename;
2771         struct tdb_print_db *pdb;
2772         int count = 0;
2773
2774         /* make sure the database is up to date */
2775
2776         if (print_cache_expired(lp_const_servicename(snum), True))
2777                 print_queue_update(snum, False);
2778
2779         /* return if we are done */
2780         if ( !ppqueue || !status )
2781                 return 0;
2782
2783         *ppqueue = NULL;
2784         sharename = lp_const_servicename(snum);
2785         pdb = get_print_db_byname(sharename);
2786
2787         if (!pdb)
2788                 return 0;
2789
2790         /*
2791          * Fetch the queue status.  We must do this first, as there may
2792          * be no jobs in the queue.
2793          */
2794
2795         ZERO_STRUCTP(status);
2796         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
2797         key = string_tdb_data(keystr);
2798
2799         data = tdb_fetch(pdb->tdb, key);
2800         if (data.dptr) {
2801                 if (data.dsize == sizeof(*status)) {
2802                         /* this memcpy is ok since the status struct was
2803                            not packed before storing it in the tdb */
2804                         memcpy(status, data.dptr, sizeof(*status));
2805                 }
2806                 SAFE_FREE(data.dptr);
2807         }
2808
2809         /*
2810          * Now, fetch the print queue information.  We first count the number
2811          * of entries, and then only retrieve the queue if necessary.
2812          */
2813
2814         if (!get_stored_queue_info(pdb, snum, &count, ppqueue)) {
2815                 release_print_db(pdb);
2816                 return 0;
2817         }
2818
2819         release_print_db(pdb);
2820         return count;
2821 }
2822
2823 /****************************************************************************
2824  Pause a queue.
2825 ****************************************************************************/
2826
2827 WERROR print_queue_pause(struct auth_serversupplied_info *server_info, int snum)
2828 {
2829         int ret;
2830         struct printif *current_printif = get_printer_fns( snum );
2831
2832         if (!print_access_check(server_info, snum,
2833                                 PRINTER_ACCESS_ADMINISTER)) {
2834                 return WERR_ACCESS_DENIED;
2835         }
2836
2837
2838         become_root();
2839
2840         ret = (*(current_printif->queue_pause))(snum);
2841
2842         unbecome_root();
2843
2844         if (ret != 0) {
2845                 return WERR_INVALID_PARAM;
2846         }
2847
2848         /* force update the database */
2849         print_cache_flush(lp_const_servicename(snum));
2850
2851         /* Send a printer notify message */
2852
2853         notify_printer_status(snum, PRINTER_STATUS_PAUSED);
2854
2855         return WERR_OK;
2856 }
2857
2858 /****************************************************************************
2859  Resume a queue.
2860 ****************************************************************************/
2861
2862 WERROR print_queue_resume(struct auth_serversupplied_info *server_info, int snum)
2863 {
2864         int ret;
2865         struct printif *current_printif = get_printer_fns( snum );
2866
2867         if (!print_access_check(server_info, snum,
2868                                 PRINTER_ACCESS_ADMINISTER)) {
2869                 return WERR_ACCESS_DENIED;
2870         }
2871
2872         become_root();
2873
2874         ret = (*(current_printif->queue_resume))(snum);
2875
2876         unbecome_root();
2877
2878         if (ret != 0) {
2879                 return WERR_INVALID_PARAM;
2880         }
2881
2882         /* make sure the database is up to date */
2883         if (print_cache_expired(lp_const_servicename(snum), True))
2884                 print_queue_update(snum, True);
2885
2886         /* Send a printer notify message */
2887
2888         notify_printer_status(snum, PRINTER_STATUS_OK);
2889
2890         return WERR_OK;
2891 }
2892
2893 /****************************************************************************
2894  Purge a queue - implemented by deleting all jobs that we can delete.
2895 ****************************************************************************/
2896
2897 WERROR print_queue_purge(struct auth_serversupplied_info *server_info, int snum)
2898 {
2899         print_queue_struct *queue;
2900         print_status_struct status;
2901         int njobs, i;
2902         bool can_job_admin;
2903
2904         /* Force and update so the count is accurate (i.e. not a cached count) */
2905         print_queue_update(snum, True);
2906
2907         can_job_admin = print_access_check(server_info, snum,
2908                                            JOB_ACCESS_ADMINISTER);
2909         njobs = print_queue_status(snum, &queue, &status);
2910
2911         if ( can_job_admin )
2912                 become_root();
2913
2914         for (i=0;i<njobs;i++) {
2915                 bool owner = is_owner(server_info, lp_const_servicename(snum),
2916                                       queue[i].job);
2917
2918                 if (owner || can_job_admin) {
2919                         print_job_delete1(snum, queue[i].job);
2920                 }
2921         }
2922
2923         if ( can_job_admin )
2924                 unbecome_root();
2925
2926         /* update the cache */
2927         print_queue_update( snum, True );
2928
2929         SAFE_FREE(queue);
2930
2931         return WERR_OK;
2932 }