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