This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.(This used to...
[samba.git] / source3 / printing / printing.c
1 /* 
2    Unix SMB/CIFS implementation.
3    printing backend routines
4    Copyright (C) Andrew Tridgell 1992-2000
5    
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include "printing.h"
22
23 /* Current printer interface */
24 struct printif *current_printif = &generic_printif;
25
26 /* 
27    the printing backend revolves around a tdb database that stores the
28    SMB view of the print queue 
29    
30    The key for this database is a jobid - a internally generated number that
31    uniquely identifies a print job
32
33    reading the print queue involves two steps:
34      - possibly running lpq and updating the internal database from that
35      - reading entries from the database
36
37    jobids are assigned when a job starts spooling. 
38 */
39
40 /* the open printing.tdb database */
41 static TDB_CONTEXT *tdb;
42 static pid_t local_pid;
43
44 static int get_queue_status(int, print_status_struct *);
45
46 /****************************************************************************
47  Initialise the printing backend. Called once at startup. 
48  Does not survive a fork
49 ****************************************************************************/
50
51 BOOL print_backend_init(void)
52 {
53         char *sversion = "INFO/version";
54
55         if (tdb && local_pid == sys_getpid()) return True;
56         tdb = tdb_open_log(lock_path("printing.tdb"), 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
57         if (!tdb) {
58                 DEBUG(0,("print_backend_init: Failed to open printing backend database. Error = [%s]\n",
59                                  tdb_errorstr(tdb)));
60                 return False;
61         }
62         local_pid = sys_getpid();
63
64         /* handle a Samba upgrade */
65         tdb_lock_bystring(tdb, sversion);
66         if (tdb_fetch_int32(tdb, sversion) != PRINT_DATABASE_VERSION) {
67                 tdb_traverse(tdb, tdb_traverse_delete_fn, NULL);
68                 tdb_store_int32(tdb, sversion, PRINT_DATABASE_VERSION);
69         }
70         tdb_unlock_bystring(tdb, sversion);
71
72         /* select the appropriate printing interface... */
73 #ifdef HAVE_CUPS
74         if (strcmp(lp_printcapname(), "cups") == 0)
75                 current_printif = &cups_printif;
76 #endif /* HAVE_CUPS */
77
78         /* do NT print initialization... */
79         return nt_printing_init();
80 }
81
82 /****************************************************************************
83 useful function to generate a tdb key
84 ****************************************************************************/
85 static TDB_DATA print_key(int jobid)
86 {
87         static int j;
88         TDB_DATA ret;
89
90         j = jobid;
91         ret.dptr = (void *)&j;
92         ret.dsize = sizeof(j);
93         return ret;
94 }
95
96 /****************************************************************************
97 useful function to find a print job in the database
98 ****************************************************************************/
99 static struct printjob *print_job_find(int jobid)
100 {
101         static struct printjob pjob;
102         TDB_DATA ret;
103
104         ret = tdb_fetch(tdb, print_key(jobid));
105         if (!ret.dptr || ret.dsize != sizeof(pjob)) return NULL;
106
107         memcpy(&pjob, ret.dptr, sizeof(pjob));
108         free(ret.dptr);
109         return &pjob;
110 }
111
112 /****************************************************************************
113 store a job structure back to the database
114 ****************************************************************************/
115 static BOOL print_job_store(int jobid, struct printjob *pjob)
116 {
117         TDB_DATA d;
118         BOOL ret;
119
120         d.dptr = (void *)pjob;
121         d.dsize = sizeof(*pjob);
122         ret = (tdb_store(tdb, print_key(jobid), d, TDB_REPLACE) == 0);
123         return ret;
124 }
125
126 /****************************************************************************
127 parse a file name from the system spooler to generate a jobid
128 ****************************************************************************/
129 static int print_parse_jobid(char *fname)
130 {
131         int jobid;
132
133         if (strncmp(fname,PRINT_SPOOL_PREFIX,strlen(PRINT_SPOOL_PREFIX)) != 0) return -1;
134         fname += strlen(PRINT_SPOOL_PREFIX);
135
136         jobid = atoi(fname);
137         if (jobid <= 0) return -1;
138
139         return jobid;
140 }
141
142
143 /****************************************************************************
144 list a unix job in the print database
145 ****************************************************************************/
146 static void print_unix_job(int snum, print_queue_struct *q)
147 {
148         int jobid = q->job + UNIX_JOB_START;
149         struct printjob pj, *old_pj;
150
151         /* Preserve the timestamp on an existing unix print job */
152
153         old_pj = print_job_find(jobid);
154
155         ZERO_STRUCT(pj);
156
157         pj.pid = (pid_t)-1;
158         pj.sysjob = q->job;
159         pj.fd = -1;
160         pj.starttime = old_pj ? old_pj->starttime : q->time;
161         pj.status = q->status;
162         pj.size = q->size;
163         pj.spooled = True;
164         pj.smbjob = False;
165         fstrcpy(pj.filename, "");
166         fstrcpy(pj.jobname, q->fs_file);
167         fstrcpy(pj.user, q->fs_user);
168         fstrcpy(pj.queuename, lp_servicename(snum));
169
170         print_job_store(jobid, &pj);
171 }
172
173
174 struct traverse_struct {
175         print_queue_struct *queue;
176         int qcount, snum, maxcount, total_jobs;
177 };
178
179 /* utility fn to delete any jobs that are no longer active */
180 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
181 {
182         struct traverse_struct *ts = (struct traverse_struct *)state;
183         struct printjob pjob;
184         int i, jobid;
185
186         if (data.dsize != sizeof(pjob) || key.dsize != sizeof(int)) return 0;
187         memcpy(&jobid, key.dptr, sizeof(jobid));
188         memcpy(&pjob,  data.dptr, sizeof(pjob));
189
190         if (ts->snum != lp_servicenumber(pjob.queuename)) {
191                 /* this isn't for the queue we are looking at */
192                 ts->total_jobs++;
193                 return 0;
194         }
195
196         if (!pjob.smbjob) {
197                 /* remove a unix job if it isn't in the system queue any more */
198
199                 for (i=0;i<ts->qcount;i++) {
200                         if (jobid == ts->queue[i].job + UNIX_JOB_START) break;
201                 }
202                 if (i == ts->qcount)
203                         tdb_delete(tdb, key);
204                 else
205                         ts->total_jobs++;
206                 return 0;
207         }
208
209         /* maybe it hasn't been spooled yet */
210         if (!pjob.spooled) {
211                 /* if a job is not spooled and the process doesn't
212                    exist then kill it. This cleans up after smbd
213                    deaths */
214                 if (!process_exists(pjob.pid))
215                         tdb_delete(tdb, key);
216                 else
217                         ts->total_jobs++;
218                 return 0;
219         }
220
221         for (i=0;i<ts->qcount;i++) {
222                 int qid = print_parse_jobid(ts->queue[i].fs_file);
223                 if (jobid == qid) break;
224         }
225         
226         /* The job isn't in the system queue - we have to assume it has
227            completed, so delete the database entry. */
228
229         if (i == ts->qcount) {
230                 time_t cur_t = time(NULL);
231
232                 /* A race can occur between the time a job is spooled and
233                    when it appears in the lpq output.  This happens when
234                    the job is added to printing.tdb when another smbd
235                    running print_queue_update() has completed a lpq and
236                    is currently traversing the printing tdb and deleting jobs.
237                    A workaround is to not delete the job if it has been 
238                    submitted less than lp_lpqcachetime() seconds ago. */
239
240                 if ((cur_t - pjob.starttime) > lp_lpqcachetime())
241                         tdb_delete(t, key);
242                 else
243                         ts->total_jobs++;
244         }
245         else
246                 ts->total_jobs++;
247
248         return 0;
249 }
250
251 /****************************************************************************
252 check if the print queue has been updated recently enough
253 ****************************************************************************/
254 static void print_cache_flush(int snum)
255 {
256         fstring key;
257         slprintf(key, sizeof(key)-1, "CACHE/%s", lp_servicename(snum));
258         tdb_store_int32(tdb, key, -1);
259 }
260
261 /****************************************************************************
262  Check if someone already thinks they are doing the update.
263 ****************************************************************************/
264
265 static pid_t get_updating_pid(fstring printer_name)
266 {
267         fstring keystr;
268         TDB_DATA data, key;
269         pid_t updating_pid;
270
271         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
272         key.dptr = keystr;
273         key.dsize = strlen(keystr);
274
275         data = tdb_fetch(tdb, key);
276         if (!data.dptr || data.dsize != sizeof(pid_t))
277                 return (pid_t)-1;
278
279         memcpy(&updating_pid, data.dptr, sizeof(pid_t));
280         free(data.dptr);
281
282         if (process_exists(updating_pid))
283                 return updating_pid;
284
285         return (pid_t)-1;
286 }
287
288 /****************************************************************************
289  Set the fact that we're doing the update, or have finished doing the update
290  in th tdb.
291 ****************************************************************************/
292
293 static void set_updating_pid(fstring printer_name, BOOL delete)
294 {
295         fstring keystr;
296         TDB_DATA key;
297         TDB_DATA data;
298         pid_t updating_pid = sys_getpid();
299
300         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
301         key.dptr = keystr;
302         key.dsize = strlen(keystr);
303
304         if (delete) {
305                 tdb_delete(tdb, key);
306                 return;
307         }
308         
309         data.dptr = (void *)&updating_pid;
310         data.dsize = sizeof(pid_t);
311
312         tdb_store(tdb, key, data, TDB_REPLACE); 
313 }
314
315 /****************************************************************************
316  Send a message saying the queue changed.
317 ****************************************************************************/
318
319 static void send_queue_message(const char *printer_name, uint32 high, uint32 low)
320 {
321         char msg[8 + sizeof(fstring)];
322         SIVAL(msg,0,low);
323         SIVAL(msg,4,high);
324         fstrcpy(&msg[8], printer_name);
325
326         message_send_all(conn_tdb_ctx(), MSG_PRINTER_NOTIFY, msg, 8 + strlen(printer_name) + 1, False, NULL);
327 }
328
329 /****************************************************************************
330 update the internal database from the system print queue for a queue in the background
331 ****************************************************************************/
332
333 static void print_queue_update_background(int snum)
334 {
335         int i, qcount;
336         print_queue_struct *queue = NULL;
337         print_status_struct status;
338         print_status_struct old_status;
339         struct printjob *pjob;
340         struct traverse_struct tstruct;
341         fstring keystr, printer_name, cachestr;
342         TDB_DATA data, key;
343
344         fstrcpy(printer_name, lp_servicename(snum));
345         
346         /*
347          * Check to see if someone else is doing this update.
348          * This is essentially a mutex on the update.
349          */
350
351         if (get_updating_pid(printer_name) != -1)
352                 return;
353
354         /* Lock the queue for the database update */
355
356         slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", printer_name);
357         tdb_lock_bystring(tdb, keystr);
358
359         /*
360          * Ensure that no one else got in here.
361          * If the updating pid is still -1 then we are
362          * the winner.
363          */
364
365         if (get_updating_pid(printer_name) != -1) {
366                 /*
367                  * Someone else is doing the update, exit.
368                  */
369                 tdb_unlock_bystring(tdb, keystr);
370                 return;
371         }
372
373         /*
374          * We're going to do the update ourselves.
375          */
376
377         /* Tell others we're doing the update. */
378         set_updating_pid(printer_name, False);
379
380         /*
381          * Allow others to enter and notice we're doing
382          * the update.
383          */
384
385         tdb_unlock_bystring(tdb, keystr);
386
387         /*
388          * Update the cache time FIRST ! Stops others even
389          * attempting to get the lock and doing this
390          * if the lpq takes a long time.
391          */
392
393         slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", printer_name);
394         tdb_store_int32(tdb, cachestr, (int)time(NULL));
395
396         /* get the current queue using the appropriate interface */
397         ZERO_STRUCT(status);
398
399         qcount = (*(current_printif->queue_get))(snum, &queue, &status);
400
401         DEBUG(3, ("%d job%s in queue for %s\n", qcount, (qcount != 1) ?
402                 "s" : "", printer_name));
403
404         /*
405           any job in the internal database that is marked as spooled
406           and doesn't exist in the system queue is considered finished
407           and removed from the database
408
409           any job in the system database but not in the internal database 
410           is added as a unix job
411
412           fill in any system job numbers as we go
413         */
414         for (i=0; i<qcount; i++) {
415                 int jobid = print_parse_jobid(queue[i].fs_file);
416
417                 if (jobid == -1) {
418                         /* assume its a unix print job */
419                         print_unix_job(snum, &queue[i]);
420                         continue;
421                 }
422
423                 /* we have an active SMB print job - update its status */
424                 pjob = print_job_find(jobid);
425                 if (!pjob) {
426                         /* err, somethings wrong. Probably smbd was restarted
427                            with jobs in the queue. All we can do is treat them
428                            like unix jobs. Pity. */
429                         print_unix_job(snum, &queue[i]);
430                         continue;
431                 }
432
433                 pjob->sysjob = queue[i].job;
434                 pjob->status = queue[i].status;
435
436                 print_job_store(jobid, pjob);
437         }
438
439         /* now delete any queued entries that don't appear in the
440            system queue */
441         tstruct.queue = queue;
442         tstruct.qcount = qcount;
443         tstruct.snum = snum;
444         tstruct.total_jobs = 0;
445
446         tdb_traverse(tdb, traverse_fn_delete, (void *)&tstruct);
447
448         safe_free(tstruct.queue);
449
450         tdb_store_int32(tdb, "INFO/total_jobs", tstruct.total_jobs);
451
452         /*
453          * Get the old print status. We will use this to compare the
454          * number of jobs. If they have changed we need to send a
455          * "changed" message to the smbds.
456          */
457
458         if( qcount != get_queue_status(snum, &old_status)) {
459                 DEBUG(10,("print_queue_update: queue status change %d jobs -> %d jobs for printer %s\n",
460                                 old_status.qcount, qcount, printer_name ));
461                 send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
462         }
463
464         /* store the new queue status structure */
465         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printer_name);
466         key.dptr = keystr;
467         key.dsize = strlen(keystr);
468
469         status.qcount = qcount;
470         data.dptr = (void *)&status;
471         data.dsize = sizeof(status);
472         tdb_store(tdb, key, data, TDB_REPLACE); 
473
474         /*
475          * Update the cache time again. We want to do this call
476          * as little as possible...
477          */
478
479         slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", printer_name);
480         tdb_store_int32(tdb, keystr, (int)time(NULL));
481
482         /* Delete our pid from the db. */
483         set_updating_pid(printer_name, True);
484 }
485
486 /****************************************************************************
487 this is the receive function of the background lpq updater
488 ****************************************************************************/
489 static void print_queue_receive(int msg_type, pid_t src, void *buf, size_t len)
490 {
491         int snum;
492         snum=*((int *)buf);
493         print_queue_update_background(snum);
494 }
495
496 static pid_t background_lpq_updater_pid;
497
498 /****************************************************************************
499 main thread of the background lpq updater
500 ****************************************************************************/
501 void start_background_queue(void)
502 {
503         DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
504         background_lpq_updater_pid = sys_fork();
505
506         if (background_lpq_updater_pid == -1) {
507                 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
508                 exit(1);
509         }
510
511         if(background_lpq_updater_pid == 0) {
512                 /* Child. */
513                 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
514
515                 claim_connection(NULL,"smbd lpq backend",0,False);
516
517                 if (!locking_init(0))
518                         exit(1);
519
520                 if (!print_backend_init())
521                         exit(1);
522
523                 message_register(MSG_PRINTER_UPDATE, print_queue_receive);
524                 
525                 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
526                 while (1) {
527                         pause();
528                         DEBUG(10,("start_background_queue: background LPQ thread got a message\n"));
529                         message_dispatch();
530                 }
531         }
532 }
533
534 /****************************************************************************
535 update the internal database from the system print queue for a queue
536 ****************************************************************************/
537 static void print_queue_update(int snum)
538 {
539         message_send_pid(background_lpq_updater_pid, MSG_PRINTER_UPDATE, &snum, sizeof(snum), False);
540 }
541
542 /****************************************************************************
543 check if a jobid is valid. It is valid if it exists in the database
544 ****************************************************************************/
545 BOOL print_job_exists(int jobid)
546 {
547         return tdb_exists(tdb, print_key(jobid));
548 }
549
550
551 /****************************************************************************
552 work out which service a jobid is for
553 note that we have to look up by queue name to ensure that it works for 
554 other than the process that started the job
555 ****************************************************************************/
556 int print_job_snum(int jobid)
557 {
558         struct printjob *pjob = print_job_find(jobid);
559         if (!pjob) return -1;
560
561         return find_service(pjob->queuename);
562 }
563
564 /****************************************************************************
565 give the fd used for a jobid
566 ****************************************************************************/
567 int print_job_fd(int jobid)
568 {
569         struct printjob *pjob = print_job_find(jobid);
570         if (!pjob) return -1;
571         /* don't allow another process to get this info - it is meaningless */
572         if (pjob->pid != local_pid) return -1;
573         return pjob->fd;
574 }
575
576 /****************************************************************************
577 give the filename used for a jobid
578 only valid for the process doing the spooling and when the job
579 has not been spooled
580 ****************************************************************************/
581 char *print_job_fname(int jobid)
582 {
583         struct printjob *pjob = print_job_find(jobid);
584         if (!pjob || pjob->spooled || pjob->pid != local_pid) return NULL;
585         return pjob->filename;
586 }
587
588
589 /****************************************************************************
590 set the place in the queue for a job
591 ****************************************************************************/
592 BOOL print_job_set_place(int jobid, int place)
593 {
594         DEBUG(2,("print_job_set_place not implemented yet\n"));
595         return False;
596 }
597
598 /****************************************************************************
599 set the name of a job. Only possible for owner
600 ****************************************************************************/
601 BOOL print_job_set_name(int jobid, char *name)
602 {
603         struct printjob *pjob = print_job_find(jobid);
604         if (!pjob || pjob->pid != local_pid) return False;
605
606         fstrcpy(pjob->jobname, name);
607         return print_job_store(jobid, pjob);
608 }
609
610
611 /****************************************************************************
612 delete a print job - don't update queue
613 ****************************************************************************/
614 static BOOL print_job_delete1(int jobid)
615 {
616         struct printjob *pjob = print_job_find(jobid);
617         int snum, result = 0;
618
619         if (!pjob) return False;
620
621         /*
622          * If already deleting just return.
623          */
624
625         if (pjob->status == LPQ_DELETING)
626                 return True;
627
628         snum = print_job_snum(jobid);
629         if (snum == -1) {
630                 DEBUG(5,("print_job_delete1: unknown service number for jobid %d\n", jobid));
631                 return False;
632         }
633
634         /* Hrm - we need to be able to cope with deleting a job before it
635            has reached the spooler. */
636
637         if (pjob->sysjob == -1) {
638                 DEBUG(5, ("attempt to delete job %d not seen by lpr\n",
639                           jobid));
640         }
641
642         /* Set the tdb entry to be deleting. */
643
644         pjob->status = LPQ_DELETING;
645         print_job_store(jobid, pjob);
646
647         if (pjob->spooled && pjob->sysjob != -1)
648                 result = (*(current_printif->job_delete))(snum, pjob);
649
650         /* Delete the tdb entry if the delete suceeded or the job hasn't
651            been spooled. */
652
653         if (result == 0) {
654                 tdb_delete(tdb, print_key(jobid));
655         }
656
657         return (result == 0);
658 }
659
660 /****************************************************************************
661 return true if the current user owns the print job
662 ****************************************************************************/
663 static BOOL is_owner(struct current_user *user, int jobid)
664 {
665         struct printjob *pjob = print_job_find(jobid);
666         user_struct *vuser;
667
668         if (!pjob || !user) return False;
669
670         if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
671                 return strequal(pjob->user, vuser->user.smb_name);
672         } else {
673                 return strequal(pjob->user, uidtoname(user->uid));
674         }
675 }
676
677 /****************************************************************************
678 delete a print job
679 ****************************************************************************/
680 BOOL print_job_delete(struct current_user *user, int jobid, WERROR *errcode)
681 {
682         int snum = print_job_snum(jobid);
683         char *printer_name;
684         BOOL owner;
685
686         if (snum == -1) {
687                 DEBUG(5,("print_job_delete: unknown service number for jobid %d\n", jobid));
688                 return False;
689         }
690
691         owner = is_owner(user, jobid);
692         
693         /* Check access against security descriptor or whether the user
694            owns their job. */
695
696         if (!owner && 
697             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
698                 DEBUG(3, ("delete denied by security descriptor\n"));
699                 *errcode = WERR_ACCESS_DENIED;
700                 return False;
701         }
702
703         if (!print_job_delete1(jobid)) return False;
704
705         /* force update the database and say the delete failed if the
706            job still exists */
707
708         print_queue_update(snum);
709
710         /* Send a printer notify message */
711
712         printer_name = PRINTERNAME(snum);
713
714         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
715
716         return !print_job_exists(jobid);
717 }
718
719
720 /****************************************************************************
721 pause a job
722 ****************************************************************************/
723 BOOL print_job_pause(struct current_user *user, int jobid, WERROR *errcode)
724 {
725         struct printjob *pjob = print_job_find(jobid);
726         int snum, ret = -1;
727         char *printer_name;
728         
729         if (!pjob || !user) return False;
730
731         if (!pjob->spooled || pjob->sysjob == -1) return False;
732
733         snum = print_job_snum(jobid);
734         if (snum == -1) {
735                 DEBUG(5,("print_job_pause: unknown service number for jobid %d\n", jobid));
736                 return False;
737         }
738         if (snum == -1) {
739                 DEBUG(5,("print_job_resume: unknown service number for jobid %d\n", jobid));
740                 return False;
741         }
742
743         if (!is_owner(user, jobid) &&
744             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
745                 DEBUG(3, ("pause denied by security descriptor\n"));
746                 *errcode = WERR_ACCESS_DENIED;
747                 return False;
748         }
749
750         /* need to pause the spooled entry */
751         ret = (*(current_printif->job_pause))(snum, pjob);
752
753         if (ret != 0) {
754                 *errcode = WERR_INVALID_PARAM;
755                 return False;
756         }
757
758         /* force update the database */
759         print_cache_flush(snum);
760
761         /* Send a printer notify message */
762
763         printer_name = PRINTERNAME(snum);
764
765         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
766
767         /* how do we tell if this succeeded? */
768
769         return True;
770 }
771
772 /****************************************************************************
773 resume a job
774 ****************************************************************************/
775 BOOL print_job_resume(struct current_user *user, int jobid, WERROR *errcode)
776 {
777         struct printjob *pjob = print_job_find(jobid);
778         char *printer_name;
779         int snum, ret;
780         
781         if (!pjob || !user) return False;
782
783         if (!pjob->spooled || pjob->sysjob == -1) return False;
784
785         snum = print_job_snum(jobid);
786
787         if (!is_owner(user, jobid) &&
788             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
789                 DEBUG(3, ("resume denied by security descriptor\n"));
790                 *errcode = WERR_ACCESS_DENIED;
791                 return False;
792         }
793
794         ret = (*(current_printif->job_resume))(snum, pjob);
795
796         if (ret != 0) {
797                 *errcode = WERR_INVALID_PARAM;
798                 return False;
799         }
800
801         /* force update the database */
802         print_cache_flush(snum);
803
804         /* Send a printer notify message */
805
806         printer_name = PRINTERNAME(snum);
807
808         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
809
810         return True;
811 }
812
813 /****************************************************************************
814 write to a print file
815 ****************************************************************************/
816 int print_job_write(int jobid, const char *buf, int size)
817 {
818         int return_code;
819         struct printjob *pjob = print_job_find(jobid);
820
821         if (!pjob)
822                 return -1;
823         /* don't allow another process to get this info - it is meaningless */
824         if (pjob->pid != local_pid)
825                 return -1;
826
827         return_code = write(pjob->fd, buf, size);
828         if (return_code>0) {
829                 pjob->size += size;
830                 print_job_store(jobid, pjob);
831         }
832         return return_code;
833 }
834
835 /****************************************************************************
836  Check if the print queue has been updated recently enough.
837 ****************************************************************************/
838
839 static BOOL print_cache_expired(int snum)
840 {
841         fstring key;
842         time_t last_qscan_time, time_now = time(NULL);
843
844         slprintf(key, sizeof(key), "CACHE/%s", lp_servicename(snum));
845         last_qscan_time = (time_t)tdb_fetch_int32(tdb, key);
846
847         /*
848          * Invalidate the queue for 3 reasons.
849          * (1). last queue scan time == -1.
850          * (2). Current time - last queue scan time > allowed cache time.
851          * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
852          * This last test picks up machines for which the clock has been moved
853          * forward, an lpq scan done and then the clock moved back. Otherwise
854          * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
855          */
856
857         if (last_qscan_time == ((time_t)-1) || (time_now - last_qscan_time) >= lp_lpqcachetime() ||
858                         last_qscan_time > (time_now + MAX_CACHE_VALID_TIME)) {
859                 DEBUG(3, ("print cache expired for queue %s \
860 (last_qscan_time = %d, time now = %d, qcachetime = %d)\n", lp_servicename(snum),
861                         (int)last_qscan_time, (int)time_now, (int)lp_lpqcachetime() ));
862                 return True;
863         }
864         return False;
865 }
866
867 /****************************************************************************
868  Get the queue status - do not update if db is out of date.
869 ****************************************************************************/
870 static int get_queue_status(int snum, print_status_struct *status)
871 {
872         fstring keystr;
873         TDB_DATA data, key;
874
875         ZERO_STRUCTP(status);
876         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", lp_servicename(snum));
877         key.dptr = keystr;
878         key.dsize = strlen(keystr);
879         data = tdb_fetch(tdb, key);
880         if (data.dptr) {
881                 if (data.dsize == sizeof(print_status_struct)) {
882                         memcpy(status, data.dptr, sizeof(print_status_struct));
883                 }
884                 free(data.dptr);
885         }
886         return status->qcount;
887 }
888
889 /****************************************************************************
890  Determine the number of jobs in a queue.
891 ****************************************************************************/
892
893 int print_queue_length(int snum, print_status_struct *pstatus)
894 {
895         print_status_struct status;
896         int len;
897  
898         /* make sure the database is up to date */
899         if (print_cache_expired(snum))
900                 print_queue_update(snum);
901  
902         /* also fetch the queue status */
903         memset(&status, 0, sizeof(status));
904         len = get_queue_status(snum, &status);
905         if (pstatus)
906                 *pstatus = status;
907         return len;
908 }
909
910 /****************************************************************************
911  Determine the number of jobs in all queues.
912 ****************************************************************************/
913 static int get_total_jobs(int snum)
914 {
915         int total_jobs;
916
917         /* make sure the database is up to date */
918         if (print_cache_expired(snum)) print_queue_update(snum);
919
920         total_jobs = tdb_fetch_int32(tdb, "INFO/total_jobs");
921         if (total_jobs >0)
922                 return total_jobs;
923         else
924                 return 0;
925 }
926
927 /***************************************************************************
928 start spooling a job - return the jobid
929 ***************************************************************************/
930 int print_job_start(struct current_user *user, int snum, char *jobname)
931 {
932         int jobid;
933         char *path;
934         struct printjob pjob;
935         int next_jobid;
936         user_struct *vuser;
937         int njobs = 0;
938
939         errno = 0;
940
941         if (!print_access_check(user, snum, PRINTER_ACCESS_USE)) {
942                 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
943                 return -1;
944         }
945
946         if (!print_time_access_check(snum)) {
947                 DEBUG(3, ("print_job_start: job start denied by time check\n"));
948                 return -1;
949         }
950
951         path = lp_pathname(snum);
952
953         /* see if we have sufficient disk space */
954         if (lp_minprintspace(snum)) {
955                 SMB_BIG_UINT dspace, dsize;
956                 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
957                     dspace < 2*(SMB_BIG_UINT)lp_minprintspace(snum)) {
958                         DEBUG(3, ("print_job_start: disk space check failed.\n"));
959                         errno = ENOSPC;
960                         return -1;
961                 }
962         }
963
964         /* for autoloaded printers, check that the printcap entry still exists */
965         if (lp_autoloaded(snum) && !pcap_printername_ok(lp_servicename(snum), NULL)) {
966                 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_servicename(snum) ));
967                 errno = ENOENT;
968                 return -1;
969         }
970
971         /* Insure the maximum queue size is not violated */
972         if (lp_maxprintjobs(snum) && (njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
973                 DEBUG(3, ("print_job_start: number of jobs (%d) larger than max printjobs per queue (%d).\n",
974                         njobs, lp_maxprintjobs(snum) ));
975                 errno = ENOSPC;
976                 return -1;
977         }
978
979         /* Insure the maximum print jobs in the system is not violated */
980         if (lp_totalprintjobs() && get_total_jobs(snum) > lp_totalprintjobs()) {
981                 DEBUG(3, ("print_job_start: number of jobs (%d) larger than max printjobs per system (%d).\n",
982                         njobs, lp_totalprintjobs() ));
983                 errno = ENOSPC;
984                 return -1;
985         }
986
987         /* create the database entry */
988         ZERO_STRUCT(pjob);
989         pjob.pid = local_pid;
990         pjob.sysjob = -1;
991         pjob.fd = -1;
992         pjob.starttime = time(NULL);
993         pjob.status = LPQ_SPOOLING;
994         pjob.size = 0;
995         pjob.spooled = False;
996         pjob.smbjob = True;
997
998         fstrcpy(pjob.jobname, jobname);
999
1000         if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
1001                 fstrcpy(pjob.user, vuser->user.smb_name);
1002         } else {
1003                 fstrcpy(pjob.user, uidtoname(user->uid));
1004         }
1005
1006         fstrcpy(pjob.queuename, lp_servicename(snum));
1007
1008         /* lock the database */
1009         tdb_lock_bystring(tdb, "INFO/nextjob");
1010
1011         next_jobid = tdb_fetch_int32(tdb, "INFO/nextjob");
1012         if (next_jobid == -1)
1013                 next_jobid = 1;
1014
1015         for (jobid = NEXT_JOBID(next_jobid); jobid != next_jobid; jobid = NEXT_JOBID(jobid)) {
1016                 if (!print_job_exists(jobid))
1017                         break;
1018         }
1019         if (jobid == next_jobid || !print_job_store(jobid, &pjob)) {
1020                 DEBUG(3, ("print_job_start: either jobid (%d)==next_jobid(%d) or print_job_store failed.\n",
1021                                 jobid, next_jobid ));
1022                 jobid = -1;
1023                 goto fail;
1024         }
1025
1026         tdb_store_int32(tdb, "INFO/nextjob", jobid);
1027
1028         /* we have a job entry - now create the spool file */
1029         slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.6d.XXXXXX", 
1030                  path, PRINT_SPOOL_PREFIX, jobid);
1031         pjob.fd = smb_mkstemp(pjob.filename);
1032
1033         if (pjob.fd == -1) {
1034                 if (errno == EACCES) {
1035                         /* Common setup error, force a report. */
1036                         DEBUG(0, ("print_job_start: insufficient permissions \
1037 to open spool file %s.\n", pjob.filename));
1038                 } else {
1039                         /* Normal case, report at level 3 and above. */
1040                         DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
1041                         DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
1042                 }
1043                 goto fail;
1044         }
1045
1046         print_job_store(jobid, &pjob);
1047
1048         tdb_unlock_bystring(tdb, "INFO/nextjob");
1049
1050         /*
1051          * If the printer is marked as postscript output a leading
1052          * file identifier to ensure the file is treated as a raw
1053          * postscript file.
1054          * This has a similar effect as CtrlD=0 in WIN.INI file.
1055          * tim@fsg.com 09/06/94
1056          */
1057         if (lp_postscript(snum)) {
1058                 print_job_write(jobid, "%!\n",3);
1059         }
1060
1061         return jobid;
1062
1063  fail:
1064         if (jobid != -1) {
1065                 tdb_delete(tdb, print_key(jobid));
1066         }
1067
1068         tdb_unlock_bystring(tdb, "INFO/nextjob");
1069
1070         DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
1071         return -1;
1072 }
1073
1074 /****************************************************************************
1075  Update the number of pages spooled to jobid
1076 ****************************************************************************/
1077
1078 void print_job_endpage(int jobid)
1079 {
1080         struct printjob *pjob = print_job_find(jobid);
1081         if (!pjob)
1082                 return;
1083         /* don't allow another process to get this info - it is meaningless */
1084         if (pjob->pid != local_pid)
1085                 return;
1086
1087         pjob->page_count++;
1088         print_job_store(jobid, pjob);
1089 }
1090
1091 /****************************************************************************
1092  Print a file - called on closing the file. This spools the job.
1093  If normal close is false then we're tearing down the jobs - treat as an
1094  error.
1095 ****************************************************************************/
1096
1097 BOOL print_job_end(int jobid, BOOL normal_close)
1098 {
1099         struct printjob *pjob = print_job_find(jobid);
1100         int snum, ret;
1101         SMB_STRUCT_STAT sbuf;
1102
1103         if (!pjob)
1104                 return False;
1105
1106         if (pjob->spooled || pjob->pid != local_pid)
1107                 return False;
1108
1109         snum = print_job_snum(jobid);
1110         if (snum == -1) {
1111                 DEBUG(5,("print_job_end: unknown service number for jobid %d\n", jobid));
1112                 return False;
1113         }
1114
1115         if (normal_close && (sys_fstat(pjob->fd, &sbuf) == 0)) {
1116                 pjob->size = sbuf.st_size;
1117                 close(pjob->fd);
1118                 pjob->fd = -1;
1119         } else {
1120
1121                 /* 
1122                  * Not a normal close or we couldn't stat the job file,
1123                  * so something has gone wrong. Cleanup.
1124                  */
1125                 close(pjob->fd);
1126                 pjob->fd = -1;
1127                 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
1128                 goto fail;
1129         }
1130
1131         /* Technically, this is not quit right. If the printer has a separator
1132          * page turned on, the NT spooler prints the separator page even if the
1133          * print job is 0 bytes. 010215 JRR */
1134         if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
1135                 /* don't bother spooling empty files or something being deleted. */
1136                 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
1137                         pjob->filename, pjob->size ? "deleted" : "zero length" ));
1138                 unlink(pjob->filename);
1139                 tdb_delete(tdb, print_key(jobid));
1140                 return True;
1141         }
1142
1143         ret = (*(current_printif->job_submit))(snum, pjob);
1144
1145         if (ret)
1146                 goto fail;
1147
1148         /* The print job has been sucessfully handed over to the back-end */
1149         
1150         pjob->spooled = True;
1151         pjob->status = LPQ_QUEUED;
1152         print_job_store(jobid, pjob);
1153         
1154         /* make sure the database is up to date */
1155         if (print_cache_expired(snum))
1156                 print_queue_update(snum);
1157         
1158         return True;
1159
1160 fail:
1161
1162         /* The print job was not succesfully started. Cleanup */
1163         /* Still need to add proper error return propagation! 010122:JRR */
1164         unlink(pjob->filename);
1165         tdb_delete(tdb, print_key(jobid));
1166         return False;
1167 }
1168
1169 /* utility fn to enumerate the print queue */
1170 static int traverse_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1171 {
1172         struct traverse_struct *ts = (struct traverse_struct *)state;
1173         struct printjob pjob;
1174         int i, jobid;
1175
1176         if (data.dsize != sizeof(pjob) || key.dsize != sizeof(int)) return 0;
1177         memcpy(&jobid, key.dptr, sizeof(jobid));
1178         memcpy(&pjob,  data.dptr, sizeof(pjob));
1179
1180         /* maybe it isn't for this queue */
1181         if (ts->snum != lp_servicenumber(pjob.queuename))
1182                 return 0;
1183
1184         if (ts->qcount >= ts->maxcount) return 0;
1185
1186         i = ts->qcount;
1187
1188         ts->queue[i].job = jobid;
1189         ts->queue[i].size = pjob.size;
1190         ts->queue[i].page_count = pjob.page_count;
1191         ts->queue[i].status = pjob.status;
1192         ts->queue[i].priority = 1;
1193         ts->queue[i].time = pjob.starttime;
1194         fstrcpy(ts->queue[i].fs_user, pjob.user);
1195         fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1196
1197         ts->qcount++;
1198
1199         return 0;
1200 }
1201
1202 struct traverse_count_struct {
1203         int snum, count;
1204 };
1205
1206 /* utility fn to count the number of entries in the print queue */
1207 static int traverse_count_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1208 {
1209         struct traverse_count_struct *ts = (struct traverse_count_struct *)state;
1210         struct printjob pjob;
1211         int jobid;
1212
1213         if (data.dsize != sizeof(pjob) || key.dsize != sizeof(int)) return 0;
1214         memcpy(&jobid, key.dptr, sizeof(jobid));
1215         memcpy(&pjob,  data.dptr, sizeof(pjob));
1216
1217         /* maybe it isn't for this queue */
1218         if (ts->snum != lp_servicenumber(pjob.queuename))
1219                 return 0;
1220
1221         ts->count++;
1222
1223         return 0;
1224 }
1225
1226 /* Sort print jobs by submittal time */
1227
1228 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1229 {
1230         /* Silly cases */
1231
1232         if (!j1 && !j2) return 0;
1233         if (!j1) return -1;
1234         if (!j2) return 1;
1235
1236         /* Sort on job start time */
1237
1238         if (j1->time == j2->time) return 0;
1239         return (j1->time > j2->time) ? 1 : -1;
1240 }
1241
1242 /****************************************************************************
1243 get a printer queue listing
1244 ****************************************************************************/
1245 int print_queue_status(int snum, 
1246                        print_queue_struct **queue,
1247                        print_status_struct *status)
1248 {
1249         struct traverse_struct tstruct;
1250         struct traverse_count_struct tsc;
1251         fstring keystr;
1252         TDB_DATA data, key;
1253
1254         /* make sure the database is up to date */
1255         if (print_cache_expired(snum)) print_queue_update(snum);
1256
1257         *queue = NULL;
1258         
1259         /*
1260          * Fetch the queue status.  We must do this first, as there may
1261          * be no jobs in the queue.
1262          */
1263         ZERO_STRUCTP(status);
1264         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", lp_servicename(snum));
1265         key.dptr = keystr;
1266         key.dsize = strlen(keystr);
1267         data = tdb_fetch(tdb, key);
1268         if (data.dptr) {
1269                 if (data.dsize == sizeof(*status)) {
1270                         memcpy(status, data.dptr, sizeof(*status));
1271                 }
1272                 free(data.dptr);
1273         }
1274
1275         /*
1276          * Now, fetch the print queue information.  We first count the number
1277          * of entries, and then only retrieve the queue if necessary.
1278          */
1279         tsc.count = 0;
1280         tsc.snum = snum;
1281         
1282         tdb_traverse(tdb, traverse_count_fn_queue, (void *)&tsc);
1283
1284         if (tsc.count == 0)
1285                 return 0;
1286
1287         /* Allocate the queue size. */
1288         if ((tstruct.queue = (print_queue_struct *)
1289              malloc(sizeof(print_queue_struct)*tsc.count))
1290                                 == NULL)
1291                 return 0;
1292
1293         /*
1294          * Fill in the queue.
1295          * We need maxcount as the queue size may have changed between
1296          * the two calls to tdb_traverse.
1297          */
1298         tstruct.qcount = 0;
1299         tstruct.maxcount = tsc.count;
1300         tstruct.snum = snum;
1301
1302         tdb_traverse(tdb, traverse_fn_queue, (void *)&tstruct);
1303
1304         /* Sort the queue by submission time otherwise they are displayed
1305            in hash order. */
1306
1307         qsort(tstruct.queue, tstruct.qcount, sizeof(print_queue_struct),
1308               QSORT_CAST(printjob_comp));
1309
1310         *queue = tstruct.queue;
1311         return tstruct.qcount;
1312 }
1313
1314
1315 /****************************************************************************
1316 turn a queue name into a snum
1317 ****************************************************************************/
1318 int print_queue_snum(char *qname)
1319 {
1320         int snum = lp_servicenumber(qname);
1321         if (snum == -1 || !lp_print_ok(snum)) return -1;
1322         return snum;
1323 }
1324
1325
1326 /****************************************************************************
1327  pause a queue
1328 ****************************************************************************/
1329 BOOL print_queue_pause(struct current_user *user, int snum, WERROR *errcode)
1330 {
1331         char *printer_name;
1332         int ret;
1333         
1334         if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
1335                 *errcode = WERR_ACCESS_DENIED;
1336                 return False;
1337         }
1338
1339         ret = (*(current_printif->queue_pause))(snum);
1340
1341         if (ret != 0) {
1342                 *errcode = WERR_INVALID_PARAM;
1343                 return False;
1344         }
1345
1346         /* force update the database */
1347         print_cache_flush(snum);
1348
1349         /* Send a printer notify message */
1350
1351         printer_name = PRINTERNAME(snum);
1352
1353         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
1354
1355         return True;
1356 }
1357
1358 /****************************************************************************
1359  resume a queue
1360 ****************************************************************************/
1361 BOOL print_queue_resume(struct current_user *user, int snum, WERROR *errcode)
1362 {
1363         char *printer_name;
1364         int ret;
1365
1366         if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
1367                 *errcode = WERR_ACCESS_DENIED;
1368                 return False;
1369         }
1370
1371         ret = (*(current_printif->queue_resume))(snum);
1372
1373         if (ret != 0) {
1374                 *errcode = WERR_INVALID_PARAM;
1375                 return False;
1376         }
1377
1378         /* make sure the database is up to date */
1379         if (print_cache_expired(snum)) print_queue_update(snum);
1380
1381         /* Send a printer notify message */
1382
1383         printer_name = PRINTERNAME(snum);
1384
1385         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
1386
1387         return True;
1388 }
1389
1390 /****************************************************************************
1391  purge a queue - implemented by deleting all jobs that we can delete
1392 ****************************************************************************/
1393 BOOL print_queue_purge(struct current_user *user, int snum, WERROR *errcode)
1394 {
1395         print_queue_struct *queue;
1396         print_status_struct status;
1397         char *printer_name;
1398         int njobs, i;
1399         BOOL can_job_admin;
1400
1401         /* Force and update so the count is accurate (i.e. not a cached count) */
1402         print_queue_update(snum);
1403         
1404         can_job_admin = print_access_check(user, snum, JOB_ACCESS_ADMINISTER);
1405         njobs = print_queue_status(snum, &queue, &status);
1406
1407         for (i=0;i<njobs;i++) {
1408                 BOOL owner = is_owner(user, queue[i].job);
1409
1410                 if (owner || can_job_admin) {
1411                         print_job_delete1(queue[i].job);
1412                 }
1413         }
1414
1415         safe_free(queue);
1416
1417         /* Send a printer notify message */
1418
1419         printer_name = PRINTERNAME(snum);
1420
1421         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
1422
1423         return True;
1424 }