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