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