printing merge from HEAD
[ira/wip.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 %s\n",
59                                  lock_path("printing.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         if (background_lpq_updater_pid > 0) {
540                 message_send_pid(background_lpq_updater_pid, MSG_PRINTER_UPDATE, 
541                                  &snum, sizeof(snum), False);
542         }
543 }
544
545 /****************************************************************************
546 check if a jobid is valid. It is valid if it exists in the database
547 ****************************************************************************/
548 BOOL print_job_exists(int jobid)
549 {
550         return tdb_exists(tdb, print_key(jobid));
551 }
552
553
554 /****************************************************************************
555 work out which service a jobid is for
556 note that we have to look up by queue name to ensure that it works for 
557 other than the process that started the job
558 ****************************************************************************/
559 int print_job_snum(int jobid)
560 {
561         struct printjob *pjob = print_job_find(jobid);
562         if (!pjob) return -1;
563
564         return find_service(pjob->queuename);
565 }
566
567 /****************************************************************************
568 give the fd used for a jobid
569 ****************************************************************************/
570 int print_job_fd(int jobid)
571 {
572         struct printjob *pjob = print_job_find(jobid);
573         if (!pjob) return -1;
574         /* don't allow another process to get this info - it is meaningless */
575         if (pjob->pid != local_pid) return -1;
576         return pjob->fd;
577 }
578
579 /****************************************************************************
580 give the filename used for a jobid
581 only valid for the process doing the spooling and when the job
582 has not been spooled
583 ****************************************************************************/
584 char *print_job_fname(int jobid)
585 {
586         struct printjob *pjob = print_job_find(jobid);
587         if (!pjob || pjob->spooled || pjob->pid != local_pid) return NULL;
588         return pjob->filename;
589 }
590
591
592 /****************************************************************************
593 set the place in the queue for a job
594 ****************************************************************************/
595 BOOL print_job_set_place(int jobid, int place)
596 {
597         DEBUG(2,("print_job_set_place not implemented yet\n"));
598         return False;
599 }
600
601 /****************************************************************************
602 set the name of a job. Only possible for owner
603 ****************************************************************************/
604 BOOL print_job_set_name(int jobid, char *name)
605 {
606         struct printjob *pjob = print_job_find(jobid);
607         if (!pjob || pjob->pid != local_pid) return False;
608
609         fstrcpy(pjob->jobname, name);
610         return print_job_store(jobid, pjob);
611 }
612
613
614 /****************************************************************************
615 delete a print job - don't update queue
616 ****************************************************************************/
617 static BOOL print_job_delete1(int jobid)
618 {
619         struct printjob *pjob = print_job_find(jobid);
620         int snum, result = 0;
621
622         if (!pjob) return False;
623
624         /*
625          * If already deleting just return.
626          */
627
628         if (pjob->status == LPQ_DELETING)
629                 return True;
630
631         snum = print_job_snum(jobid);
632         if (snum == -1) {
633                 DEBUG(5,("print_job_delete1: unknown service number for jobid %d\n", jobid));
634                 return False;
635         }
636
637         /* Hrm - we need to be able to cope with deleting a job before it
638            has reached the spooler. */
639
640         if (pjob->sysjob == -1) {
641                 DEBUG(5, ("attempt to delete job %d not seen by lpr\n",
642                           jobid));
643         }
644
645         /* Set the tdb entry to be deleting. */
646
647         pjob->status = LPQ_DELETING;
648         print_job_store(jobid, pjob);
649
650         if (pjob->spooled && pjob->sysjob != -1)
651                 result = (*(current_printif->job_delete))(snum, pjob);
652
653         /* Delete the tdb entry if the delete suceeded or the job hasn't
654            been spooled. */
655
656         if (result == 0) {
657                 tdb_delete(tdb, print_key(jobid));
658         }
659
660         return (result == 0);
661 }
662
663 /****************************************************************************
664 return true if the current user owns the print job
665 ****************************************************************************/
666 static BOOL is_owner(struct current_user *user, int jobid)
667 {
668         struct printjob *pjob = print_job_find(jobid);
669         user_struct *vuser;
670
671         if (!pjob || !user) return False;
672
673         if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
674                 return strequal(pjob->user, vuser->user.smb_name);
675         } else {
676                 return strequal(pjob->user, uidtoname(user->uid));
677         }
678 }
679
680 /****************************************************************************
681 delete a print job
682 ****************************************************************************/
683 BOOL print_job_delete(struct current_user *user, int jobid, WERROR *errcode)
684 {
685         int snum = print_job_snum(jobid);
686         char *printer_name;
687         BOOL owner;
688
689         if (snum == -1) {
690                 DEBUG(5,("print_job_delete: unknown service number for jobid %d\n", jobid));
691                 return False;
692         }
693
694         owner = is_owner(user, jobid);
695         
696         /* Check access against security descriptor or whether the user
697            owns their job. */
698
699         if (!owner && 
700             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
701                 DEBUG(3, ("delete denied by security descriptor\n"));
702                 *errcode = WERR_ACCESS_DENIED;
703                 return False;
704         }
705
706         if (!print_job_delete1(jobid)) return False;
707
708         /* force update the database and say the delete failed if the
709            job still exists */
710
711         print_queue_update(snum);
712
713         /* Send a printer notify message */
714
715         printer_name = PRINTERNAME(snum);
716
717         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
718
719         return !print_job_exists(jobid);
720 }
721
722
723 /****************************************************************************
724 pause a job
725 ****************************************************************************/
726 BOOL print_job_pause(struct current_user *user, int jobid, WERROR *errcode)
727 {
728         struct printjob *pjob = print_job_find(jobid);
729         int snum, ret = -1;
730         char *printer_name;
731         
732         if (!pjob || !user) return False;
733
734         if (!pjob->spooled || pjob->sysjob == -1) return False;
735
736         snum = print_job_snum(jobid);
737         if (snum == -1) {
738                 DEBUG(5,("print_job_pause: unknown service number for jobid %d\n", jobid));
739                 return False;
740         }
741         if (snum == -1) {
742                 DEBUG(5,("print_job_resume: unknown service number for jobid %d\n", jobid));
743                 return False;
744         }
745
746         if (!is_owner(user, jobid) &&
747             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
748                 DEBUG(3, ("pause denied by security descriptor\n"));
749                 *errcode = WERR_ACCESS_DENIED;
750                 return False;
751         }
752
753         /* need to pause the spooled entry */
754         ret = (*(current_printif->job_pause))(snum, pjob);
755
756         if (ret != 0) {
757                 *errcode = WERR_INVALID_PARAM;
758                 return False;
759         }
760
761         /* force update the database */
762         print_cache_flush(snum);
763
764         /* Send a printer notify message */
765
766         printer_name = PRINTERNAME(snum);
767
768         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
769
770         /* how do we tell if this succeeded? */
771
772         return True;
773 }
774
775 /****************************************************************************
776 resume a job
777 ****************************************************************************/
778 BOOL print_job_resume(struct current_user *user, int jobid, WERROR *errcode)
779 {
780         struct printjob *pjob = print_job_find(jobid);
781         char *printer_name;
782         int snum, ret;
783         
784         if (!pjob || !user) return False;
785
786         if (!pjob->spooled || pjob->sysjob == -1) return False;
787
788         snum = print_job_snum(jobid);
789
790         if (!is_owner(user, jobid) &&
791             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
792                 DEBUG(3, ("resume denied by security descriptor\n"));
793                 *errcode = WERR_ACCESS_DENIED;
794                 return False;
795         }
796
797         ret = (*(current_printif->job_resume))(snum, pjob);
798
799         if (ret != 0) {
800                 *errcode = WERR_INVALID_PARAM;
801                 return False;
802         }
803
804         /* force update the database */
805         print_cache_flush(snum);
806
807         /* Send a printer notify message */
808
809         printer_name = PRINTERNAME(snum);
810
811         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
812
813         return True;
814 }
815
816 /****************************************************************************
817 write to a print file
818 ****************************************************************************/
819 int print_job_write(int jobid, const char *buf, int size)
820 {
821         int return_code;
822         struct printjob *pjob = print_job_find(jobid);
823
824         if (!pjob)
825                 return -1;
826         /* don't allow another process to get this info - it is meaningless */
827         if (pjob->pid != local_pid)
828                 return -1;
829
830         return_code = write(pjob->fd, buf, size);
831         if (return_code>0) {
832                 pjob->size += size;
833                 print_job_store(jobid, pjob);
834         }
835         return return_code;
836 }
837
838 /****************************************************************************
839  Check if the print queue has been updated recently enough.
840 ****************************************************************************/
841
842 static BOOL print_cache_expired(int snum)
843 {
844         fstring key;
845         time_t last_qscan_time, time_now = time(NULL);
846
847         slprintf(key, sizeof(key), "CACHE/%s", lp_servicename(snum));
848         last_qscan_time = (time_t)tdb_fetch_int32(tdb, key);
849
850         /*
851          * Invalidate the queue for 3 reasons.
852          * (1). last queue scan time == -1.
853          * (2). Current time - last queue scan time > allowed cache time.
854          * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
855          * This last test picks up machines for which the clock has been moved
856          * forward, an lpq scan done and then the clock moved back. Otherwise
857          * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
858          */
859
860         if (last_qscan_time == ((time_t)-1) || (time_now - last_qscan_time) >= lp_lpqcachetime() ||
861                         last_qscan_time > (time_now + MAX_CACHE_VALID_TIME)) {
862                 DEBUG(3, ("print cache expired for queue %s \
863 (last_qscan_time = %d, time now = %d, qcachetime = %d)\n", lp_servicename(snum),
864                         (int)last_qscan_time, (int)time_now, (int)lp_lpqcachetime() ));
865                 return True;
866         }
867         return False;
868 }
869
870 /****************************************************************************
871  Get the queue status - do not update if db is out of date.
872 ****************************************************************************/
873 static int get_queue_status(int snum, print_status_struct *status)
874 {
875         fstring keystr;
876         TDB_DATA data, key;
877
878         ZERO_STRUCTP(status);
879         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", lp_servicename(snum));
880         key.dptr = keystr;
881         key.dsize = strlen(keystr);
882         data = tdb_fetch(tdb, key);
883         if (data.dptr) {
884                 if (data.dsize == sizeof(print_status_struct)) {
885                         memcpy(status, data.dptr, sizeof(print_status_struct));
886                 }
887                 free(data.dptr);
888         }
889         return status->qcount;
890 }
891
892 /****************************************************************************
893  Determine the number of jobs in a queue.
894 ****************************************************************************/
895
896 int print_queue_length(int snum, print_status_struct *pstatus)
897 {
898         print_status_struct status;
899         int len;
900  
901         /* make sure the database is up to date */
902         if (print_cache_expired(snum))
903                 print_queue_update(snum);
904  
905         /* also fetch the queue status */
906         memset(&status, 0, sizeof(status));
907         len = get_queue_status(snum, &status);
908         if (pstatus)
909                 *pstatus = status;
910         return len;
911 }
912
913 /****************************************************************************
914  Determine the number of jobs in all queues.
915 ****************************************************************************/
916 static int get_total_jobs(int snum)
917 {
918         int total_jobs;
919
920         /* make sure the database is up to date */
921         if (print_cache_expired(snum)) print_queue_update(snum);
922
923         total_jobs = tdb_fetch_int32(tdb, "INFO/total_jobs");
924         if (total_jobs >0)
925                 return total_jobs;
926         else
927                 return 0;
928 }
929
930 /***************************************************************************
931 start spooling a job - return the jobid
932 ***************************************************************************/
933 int print_job_start(struct current_user *user, int snum, char *jobname)
934 {
935         int jobid;
936         char *path;
937         struct printjob pjob;
938         int next_jobid;
939         user_struct *vuser;
940         int njobs = 0;
941
942         errno = 0;
943
944         if (!print_access_check(user, snum, PRINTER_ACCESS_USE)) {
945                 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
946                 return -1;
947         }
948
949         if (!print_time_access_check(snum)) {
950                 DEBUG(3, ("print_job_start: job start denied by time check\n"));
951                 return -1;
952         }
953
954         path = lp_pathname(snum);
955
956         /* see if we have sufficient disk space */
957         if (lp_minprintspace(snum)) {
958                 SMB_BIG_UINT dspace, dsize;
959                 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
960                     dspace < 2*(SMB_BIG_UINT)lp_minprintspace(snum)) {
961                         DEBUG(3, ("print_job_start: disk space check failed.\n"));
962                         errno = ENOSPC;
963                         return -1;
964                 }
965         }
966
967         /* for autoloaded printers, check that the printcap entry still exists */
968         if (lp_autoloaded(snum) && !pcap_printername_ok(lp_servicename(snum), NULL)) {
969                 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_servicename(snum) ));
970                 errno = ENOENT;
971                 return -1;
972         }
973
974         /* Insure the maximum queue size is not violated */
975         if (lp_maxprintjobs(snum) && (njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
976                 DEBUG(3, ("print_job_start: number of jobs (%d) larger than max printjobs per queue (%d).\n",
977                         njobs, lp_maxprintjobs(snum) ));
978                 errno = ENOSPC;
979                 return -1;
980         }
981
982         /* Insure the maximum print jobs in the system is not violated */
983         if (lp_totalprintjobs() && get_total_jobs(snum) > lp_totalprintjobs()) {
984                 DEBUG(3, ("print_job_start: number of jobs (%d) larger than max printjobs per system (%d).\n",
985                         njobs, lp_totalprintjobs() ));
986                 errno = ENOSPC;
987                 return -1;
988         }
989
990         /* create the database entry */
991         ZERO_STRUCT(pjob);
992         pjob.pid = local_pid;
993         pjob.sysjob = -1;
994         pjob.fd = -1;
995         pjob.starttime = time(NULL);
996         pjob.status = LPQ_SPOOLING;
997         pjob.size = 0;
998         pjob.spooled = False;
999         pjob.smbjob = True;
1000
1001         fstrcpy(pjob.jobname, jobname);
1002
1003         if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
1004                 fstrcpy(pjob.user, vuser->user.smb_name);
1005         } else {
1006                 fstrcpy(pjob.user, uidtoname(user->uid));
1007         }
1008
1009         fstrcpy(pjob.queuename, lp_servicename(snum));
1010
1011         /* lock the database */
1012         tdb_lock_bystring(tdb, "INFO/nextjob");
1013
1014         next_jobid = tdb_fetch_int32(tdb, "INFO/nextjob");
1015         if (next_jobid == -1)
1016                 next_jobid = 1;
1017
1018         for (jobid = NEXT_JOBID(next_jobid); jobid != next_jobid; jobid = NEXT_JOBID(jobid)) {
1019                 if (!print_job_exists(jobid))
1020                         break;
1021         }
1022         if (jobid == next_jobid || !print_job_store(jobid, &pjob)) {
1023                 DEBUG(3, ("print_job_start: either jobid (%d)==next_jobid(%d) or print_job_store failed.\n",
1024                                 jobid, next_jobid ));
1025                 jobid = -1;
1026                 goto fail;
1027         }
1028
1029         tdb_store_int32(tdb, "INFO/nextjob", jobid);
1030
1031         /* we have a job entry - now create the spool file */
1032         slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.6d.XXXXXX", 
1033                  path, PRINT_SPOOL_PREFIX, jobid);
1034         pjob.fd = smb_mkstemp(pjob.filename);
1035
1036         if (pjob.fd == -1) {
1037                 if (errno == EACCES) {
1038                         /* Common setup error, force a report. */
1039                         DEBUG(0, ("print_job_start: insufficient permissions \
1040 to open spool file %s.\n", pjob.filename));
1041                 } else {
1042                         /* Normal case, report at level 3 and above. */
1043                         DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
1044                         DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
1045                 }
1046                 goto fail;
1047         }
1048
1049         print_job_store(jobid, &pjob);
1050
1051         tdb_unlock_bystring(tdb, "INFO/nextjob");
1052
1053         /*
1054          * If the printer is marked as postscript output a leading
1055          * file identifier to ensure the file is treated as a raw
1056          * postscript file.
1057          * This has a similar effect as CtrlD=0 in WIN.INI file.
1058          * tim@fsg.com 09/06/94
1059          */
1060         if (lp_postscript(snum)) {
1061                 print_job_write(jobid, "%!\n",3);
1062         }
1063
1064         return jobid;
1065
1066  fail:
1067         if (jobid != -1) {
1068                 tdb_delete(tdb, print_key(jobid));
1069         }
1070
1071         tdb_unlock_bystring(tdb, "INFO/nextjob");
1072
1073         DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
1074         return -1;
1075 }
1076
1077 /****************************************************************************
1078  Update the number of pages spooled to jobid
1079 ****************************************************************************/
1080
1081 void print_job_endpage(int jobid)
1082 {
1083         struct printjob *pjob = print_job_find(jobid);
1084         if (!pjob)
1085                 return;
1086         /* don't allow another process to get this info - it is meaningless */
1087         if (pjob->pid != local_pid)
1088                 return;
1089
1090         pjob->page_count++;
1091         print_job_store(jobid, pjob);
1092 }
1093
1094 /****************************************************************************
1095  Print a file - called on closing the file. This spools the job.
1096  If normal close is false then we're tearing down the jobs - treat as an
1097  error.
1098 ****************************************************************************/
1099
1100 BOOL print_job_end(int jobid, BOOL normal_close)
1101 {
1102         struct printjob *pjob = print_job_find(jobid);
1103         int snum, ret;
1104         SMB_STRUCT_STAT sbuf;
1105
1106         if (!pjob)
1107                 return False;
1108
1109         if (pjob->spooled || pjob->pid != local_pid)
1110                 return False;
1111
1112         snum = print_job_snum(jobid);
1113         if (snum == -1) {
1114                 DEBUG(5,("print_job_end: unknown service number for jobid %d\n", jobid));
1115                 return False;
1116         }
1117
1118         if (normal_close && (sys_fstat(pjob->fd, &sbuf) == 0)) {
1119                 pjob->size = sbuf.st_size;
1120                 close(pjob->fd);
1121                 pjob->fd = -1;
1122         } else {
1123
1124                 /* 
1125                  * Not a normal close or we couldn't stat the job file,
1126                  * so something has gone wrong. Cleanup.
1127                  */
1128                 close(pjob->fd);
1129                 pjob->fd = -1;
1130                 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
1131                 goto fail;
1132         }
1133
1134         /* Technically, this is not quit right. If the printer has a separator
1135          * page turned on, the NT spooler prints the separator page even if the
1136          * print job is 0 bytes. 010215 JRR */
1137         if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
1138                 /* don't bother spooling empty files or something being deleted. */
1139                 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
1140                         pjob->filename, pjob->size ? "deleted" : "zero length" ));
1141                 unlink(pjob->filename);
1142                 tdb_delete(tdb, print_key(jobid));
1143                 return True;
1144         }
1145
1146         ret = (*(current_printif->job_submit))(snum, pjob);
1147
1148         if (ret)
1149                 goto fail;
1150
1151         /* The print job has been sucessfully handed over to the back-end */
1152         
1153         pjob->spooled = True;
1154         pjob->status = LPQ_QUEUED;
1155         print_job_store(jobid, pjob);
1156         
1157         /* make sure the database is up to date */
1158         if (print_cache_expired(snum))
1159                 print_queue_update(snum);
1160         
1161         return True;
1162
1163 fail:
1164
1165         /* The print job was not succesfully started. Cleanup */
1166         /* Still need to add proper error return propagation! 010122:JRR */
1167         unlink(pjob->filename);
1168         tdb_delete(tdb, print_key(jobid));
1169         return False;
1170 }
1171
1172 /* utility fn to enumerate the print queue */
1173 static int traverse_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1174 {
1175         struct traverse_struct *ts = (struct traverse_struct *)state;
1176         struct printjob pjob;
1177         int i, jobid;
1178
1179         if (data.dsize != sizeof(pjob) || key.dsize != sizeof(int)) return 0;
1180         memcpy(&jobid, key.dptr, sizeof(jobid));
1181         memcpy(&pjob,  data.dptr, sizeof(pjob));
1182
1183         /* maybe it isn't for this queue */
1184         if (ts->snum != lp_servicenumber(pjob.queuename))
1185                 return 0;
1186
1187         if (ts->qcount >= ts->maxcount) return 0;
1188
1189         i = ts->qcount;
1190
1191         ts->queue[i].job = jobid;
1192         ts->queue[i].size = pjob.size;
1193         ts->queue[i].page_count = pjob.page_count;
1194         ts->queue[i].status = pjob.status;
1195         ts->queue[i].priority = 1;
1196         ts->queue[i].time = pjob.starttime;
1197         fstrcpy(ts->queue[i].fs_user, pjob.user);
1198         fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1199
1200         ts->qcount++;
1201
1202         return 0;
1203 }
1204
1205 struct traverse_count_struct {
1206         int snum, count;
1207 };
1208
1209 /* utility fn to count the number of entries in the print queue */
1210 static int traverse_count_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1211 {
1212         struct traverse_count_struct *ts = (struct traverse_count_struct *)state;
1213         struct printjob pjob;
1214         int jobid;
1215
1216         if (data.dsize != sizeof(pjob) || key.dsize != sizeof(int)) return 0;
1217         memcpy(&jobid, key.dptr, sizeof(jobid));
1218         memcpy(&pjob,  data.dptr, sizeof(pjob));
1219
1220         /* maybe it isn't for this queue */
1221         if (ts->snum != lp_servicenumber(pjob.queuename))
1222                 return 0;
1223
1224         ts->count++;
1225
1226         return 0;
1227 }
1228
1229 /* Sort print jobs by submittal time */
1230
1231 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1232 {
1233         /* Silly cases */
1234
1235         if (!j1 && !j2) return 0;
1236         if (!j1) return -1;
1237         if (!j2) return 1;
1238
1239         /* Sort on job start time */
1240
1241         if (j1->time == j2->time) return 0;
1242         return (j1->time > j2->time) ? 1 : -1;
1243 }
1244
1245 /****************************************************************************
1246 get a printer queue listing
1247 ****************************************************************************/
1248 int print_queue_status(int snum, 
1249                        print_queue_struct **queue,
1250                        print_status_struct *status)
1251 {
1252         struct traverse_struct tstruct;
1253         struct traverse_count_struct tsc;
1254         fstring keystr;
1255         TDB_DATA data, key;
1256
1257         /* make sure the database is up to date */
1258         if (print_cache_expired(snum)) print_queue_update(snum);
1259
1260         *queue = NULL;
1261         
1262         /*
1263          * Fetch the queue status.  We must do this first, as there may
1264          * be no jobs in the queue.
1265          */
1266         ZERO_STRUCTP(status);
1267         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", lp_servicename(snum));
1268         key.dptr = keystr;
1269         key.dsize = strlen(keystr);
1270         data = tdb_fetch(tdb, key);
1271         if (data.dptr) {
1272                 if (data.dsize == sizeof(*status)) {
1273                         memcpy(status, data.dptr, sizeof(*status));
1274                 }
1275                 free(data.dptr);
1276         }
1277
1278         /*
1279          * Now, fetch the print queue information.  We first count the number
1280          * of entries, and then only retrieve the queue if necessary.
1281          */
1282         tsc.count = 0;
1283         tsc.snum = snum;
1284         
1285         tdb_traverse(tdb, traverse_count_fn_queue, (void *)&tsc);
1286
1287         if (tsc.count == 0)
1288                 return 0;
1289
1290         /* Allocate the queue size. */
1291         if ((tstruct.queue = (print_queue_struct *)
1292              malloc(sizeof(print_queue_struct)*tsc.count))
1293                                 == NULL)
1294                 return 0;
1295
1296         /*
1297          * Fill in the queue.
1298          * We need maxcount as the queue size may have changed between
1299          * the two calls to tdb_traverse.
1300          */
1301         tstruct.qcount = 0;
1302         tstruct.maxcount = tsc.count;
1303         tstruct.snum = snum;
1304
1305         tdb_traverse(tdb, traverse_fn_queue, (void *)&tstruct);
1306
1307         /* Sort the queue by submission time otherwise they are displayed
1308            in hash order. */
1309
1310         qsort(tstruct.queue, tstruct.qcount, sizeof(print_queue_struct),
1311               QSORT_CAST(printjob_comp));
1312
1313         *queue = tstruct.queue;
1314         return tstruct.qcount;
1315 }
1316
1317
1318 /****************************************************************************
1319 turn a queue name into a snum
1320 ****************************************************************************/
1321 int print_queue_snum(char *qname)
1322 {
1323         int snum = lp_servicenumber(qname);
1324         if (snum == -1 || !lp_print_ok(snum)) return -1;
1325         return snum;
1326 }
1327
1328
1329 /****************************************************************************
1330  pause a queue
1331 ****************************************************************************/
1332 BOOL print_queue_pause(struct current_user *user, int snum, WERROR *errcode)
1333 {
1334         char *printer_name;
1335         int ret;
1336         
1337         if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
1338                 *errcode = WERR_ACCESS_DENIED;
1339                 return False;
1340         }
1341
1342         ret = (*(current_printif->queue_pause))(snum);
1343
1344         if (ret != 0) {
1345                 *errcode = WERR_INVALID_PARAM;
1346                 return False;
1347         }
1348
1349         /* force update the database */
1350         print_cache_flush(snum);
1351
1352         /* Send a printer notify message */
1353
1354         printer_name = PRINTERNAME(snum);
1355
1356         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
1357
1358         return True;
1359 }
1360
1361 /****************************************************************************
1362  resume a queue
1363 ****************************************************************************/
1364 BOOL print_queue_resume(struct current_user *user, int snum, WERROR *errcode)
1365 {
1366         char *printer_name;
1367         int ret;
1368
1369         if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
1370                 *errcode = WERR_ACCESS_DENIED;
1371                 return False;
1372         }
1373
1374         ret = (*(current_printif->queue_resume))(snum);
1375
1376         if (ret != 0) {
1377                 *errcode = WERR_INVALID_PARAM;
1378                 return False;
1379         }
1380
1381         /* make sure the database is up to date */
1382         if (print_cache_expired(snum)) print_queue_update(snum);
1383
1384         /* Send a printer notify message */
1385
1386         printer_name = PRINTERNAME(snum);
1387
1388         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
1389
1390         return True;
1391 }
1392
1393 /****************************************************************************
1394  purge a queue - implemented by deleting all jobs that we can delete
1395 ****************************************************************************/
1396 BOOL print_queue_purge(struct current_user *user, int snum, WERROR *errcode)
1397 {
1398         print_queue_struct *queue;
1399         print_status_struct status;
1400         char *printer_name;
1401         int njobs, i;
1402         BOOL can_job_admin;
1403
1404         /* Force and update so the count is accurate (i.e. not a cached count) */
1405         print_queue_update(snum);
1406         
1407         can_job_admin = print_access_check(user, snum, JOB_ACCESS_ADMINISTER);
1408         njobs = print_queue_status(snum, &queue, &status);
1409
1410         for (i=0;i<njobs;i++) {
1411                 BOOL owner = is_owner(user, queue[i].job);
1412
1413                 if (owner || can_job_admin) {
1414                         print_job_delete1(queue[i].job);
1415                 }
1416         }
1417
1418         safe_free(queue);
1419
1420         /* Send a printer notify message */
1421
1422         printer_name = PRINTERNAME(snum);
1423
1424         send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
1425
1426         return True;
1427 }