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