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