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