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