few edits
[Samba.git] / source / printing / printing.c
blob1243c6a8e061dcc4db09a8bff3a65051091815be
1 /*
2 Unix SMB/Netbios implementation.
3 Version 3.0
4 printing backend routines
5 Copyright (C) Andrew Tridgell 1992-2000
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.
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.
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.
22 #include "printing.h"
24 /* Current printer interface */
25 struct printif *current_printif = &generic_printif;
27 /*
28 the printing backend revolves around a tdb database that stores the
29 SMB view of the print queue
31 The key for this database is a jobid - a internally generated number that
32 uniquely identifies a print job
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
38 jobids are assigned when a job starts spooling.
41 /* the open printing.tdb database */
42 static TDB_CONTEXT *tdb;
43 static pid_t local_pid;
45 static int get_queue_status(int, print_status_struct *);
47 /****************************************************************************
48 Initialise the printing backend. Called once at startup.
49 Does not survive a fork
50 ****************************************************************************/
52 BOOL print_backend_init(void)
54 char *sversion = "INFO/version";
56 if (tdb && local_pid == sys_getpid())
57 return True;
58 tdb = tdb_open_log(lock_path("printing.tdb"), 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
59 if (!tdb) {
60 DEBUG(0,("print_backend_init: Failed to open printing backend database %s.\n",
61 lock_path("printing.tdb") ));
62 return False;
64 local_pid = sys_getpid();
66 /* handle a Samba upgrade */
67 tdb_lock_bystring(tdb, sversion, 0);
68 if (tdb_fetch_int32(tdb, sversion) != PRINT_DATABASE_VERSION) {
69 tdb_traverse(tdb, tdb_traverse_delete_fn, NULL);
70 tdb_store_int32(tdb, sversion, PRINT_DATABASE_VERSION);
72 tdb_unlock_bystring(tdb, sversion);
74 /* select the appropriate printing interface... */
75 #ifdef HAVE_CUPS
76 if (strcmp(lp_printcapname(), "cups") == 0)
77 current_printif = &cups_printif;
78 #endif /* HAVE_CUPS */
80 /* do NT print initialization... */
81 return nt_printing_init();
84 /****************************************************************************
85 Useful function to generate a tdb key.
86 ****************************************************************************/
88 static TDB_DATA print_key(int jobid)
90 static int j;
91 TDB_DATA ret;
93 j = jobid;
94 ret.dptr = (void *)&j;
95 ret.dsize = sizeof(j);
96 return ret;
99 /****************************************************************************
100 Useful function to find a print job in the database.
101 ****************************************************************************/
103 static struct printjob *print_job_find(int jobid)
105 static struct printjob pjob;
106 TDB_DATA ret;
108 ret = tdb_fetch(tdb, print_key(jobid));
109 if (!ret.dptr || ret.dsize != sizeof(pjob))
110 return NULL;
112 memcpy(&pjob, ret.dptr, sizeof(pjob));
113 SAFE_FREE(ret.dptr);
114 unix_to_dos(pjob.queuename);
115 return &pjob;
118 /****************************************************************************
119 Store a job structure back to the database.
120 ****************************************************************************/
122 static BOOL print_job_store(int jobid, struct printjob *pjob)
124 TDB_DATA d;
125 BOOL ret;
127 dos_to_unix(pjob->queuename);
128 d.dptr = (void *)pjob;
129 d.dsize = sizeof(*pjob);
130 ret = (tdb_store(tdb, print_key(jobid), d, TDB_REPLACE) == 0);
131 unix_to_dos(pjob->queuename);
132 return ret;
135 /****************************************************************************
136 Parse a file name from the system spooler to generate a jobid.
137 ****************************************************************************/
139 static int print_parse_jobid(char *fname)
141 int jobid;
143 if (strncmp(fname,PRINT_SPOOL_PREFIX,strlen(PRINT_SPOOL_PREFIX)) != 0)
144 return -1;
145 fname += strlen(PRINT_SPOOL_PREFIX);
147 jobid = atoi(fname);
148 if (jobid <= 0)
149 return -1;
151 return jobid;
154 /****************************************************************************
155 List a unix job in the print database.
156 ****************************************************************************/
158 static void print_unix_job(int snum, print_queue_struct *q)
160 int jobid = q->job + UNIX_JOB_START;
161 struct printjob pj, *old_pj;
163 /* Preserve the timestamp on an existing unix print job */
165 old_pj = print_job_find(jobid);
167 ZERO_STRUCT(pj);
169 pj.pid = (pid_t)-1;
170 pj.sysjob = q->job;
171 pj.fd = -1;
172 pj.starttime = old_pj ? old_pj->starttime : q->time;
173 pj.status = q->status;
174 pj.size = q->size;
175 pj.spooled = True;
176 pj.smbjob = False;
177 fstrcpy(pj.filename, "");
178 fstrcpy(pj.jobname, q->fs_file);
179 fstrcpy(pj.user, q->fs_user);
180 fstrcpy(pj.queuename, lp_servicename(snum));
182 print_job_store(jobid, &pj);
186 struct traverse_struct {
187 print_queue_struct *queue;
188 int qcount, snum, maxcount, total_jobs;
191 /****************************************************************************
192 Utility fn to delete any jobs that are no longer active.
193 ****************************************************************************/
195 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
197 struct traverse_struct *ts = (struct traverse_struct *)state;
198 struct printjob pjob;
199 int i, jobid;
201 if (data.dsize != sizeof(pjob) || key.dsize != sizeof(int))
202 return 0;
203 memcpy(&jobid, key.dptr, sizeof(jobid));
204 memcpy(&pjob, data.dptr, sizeof(pjob));
205 unix_to_dos(pjob.queuename);
207 if (ts->snum != lp_servicenumber(pjob.queuename)) {
208 /* this isn't for the queue we are looking at */
209 ts->total_jobs++;
210 return 0;
213 if (!pjob.smbjob) {
214 /* remove a unix job if it isn't in the system queue any more */
216 for (i=0;i<ts->qcount;i++) {
217 if (jobid == ts->queue[i].job + UNIX_JOB_START)
218 break;
220 if (i == ts->qcount)
221 tdb_delete(tdb, key);
222 else
223 ts->total_jobs++;
224 return 0;
227 /* maybe it hasn't been spooled yet */
228 if (!pjob.spooled) {
229 /* if a job is not spooled and the process doesn't
230 exist then kill it. This cleans up after smbd
231 deaths */
232 if (!process_exists(pjob.pid))
233 tdb_delete(tdb, key);
234 else
235 ts->total_jobs++;
236 return 0;
239 for (i=0;i<ts->qcount;i++) {
240 int qid = print_parse_jobid(ts->queue[i].fs_file);
241 if (jobid == qid)
242 break;
245 /* The job isn't in the system queue - we have to assume it has
246 completed, so delete the database entry. */
248 if (i == ts->qcount) {
249 time_t cur_t = time(NULL);
251 /* A race can occur between the time a job is spooled and
252 when it appears in the lpq output. This happens when
253 the job is added to printing.tdb when another smbd
254 running print_queue_update() has completed a lpq and
255 is currently traversing the printing tdb and deleting jobs.
256 A workaround is to not delete the job if it has been
257 submitted less than lp_lpqcachetime() seconds ago. */
259 if ((cur_t - pjob.starttime) > lp_lpqcachetime())
260 tdb_delete(t, key);
261 else
262 ts->total_jobs++;
264 else
265 ts->total_jobs++;
267 return 0;
270 /****************************************************************************
271 Check if the print queue has been updated recently enough.
272 ****************************************************************************/
274 static void print_cache_flush(int snum)
276 fstring key;
277 slprintf(key, sizeof(key)-1, "CACHE/%s", lp_servicename(snum));
278 dos_to_unix(key); /* Convert key to unix-codepage */
279 tdb_store_int32(tdb, key, -1);
282 /****************************************************************************
283 Check if someone already thinks they are doing the update.
284 ****************************************************************************/
286 static pid_t get_updating_pid(fstring printer_name)
288 fstring keystr;
289 TDB_DATA data, key;
290 pid_t updating_pid;
292 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
293 key.dptr = keystr;
294 key.dsize = strlen(keystr);
296 data = tdb_fetch(tdb, key);
297 if (!data.dptr || data.dsize != sizeof(pid_t))
298 return (pid_t)-1;
300 memcpy(&updating_pid, data.dptr, sizeof(pid_t));
301 SAFE_FREE(data.dptr);
303 if (process_exists(updating_pid))
304 return updating_pid;
306 return (pid_t)-1;
309 /****************************************************************************
310 Set the fact that we're doing the update, or have finished doing the update
311 in th tdb.
312 ****************************************************************************/
314 static void set_updating_pid(fstring printer_name, BOOL delete)
316 fstring keystr;
317 TDB_DATA key;
318 TDB_DATA data;
319 pid_t updating_pid = sys_getpid();
321 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
322 key.dptr = keystr;
323 key.dsize = strlen(keystr);
325 if (delete) {
326 tdb_delete(tdb, key);
327 return;
330 data.dptr = (void *)&updating_pid;
331 data.dsize = sizeof(pid_t);
333 tdb_store(tdb, key, data, TDB_REPLACE);
336 /****************************************************************************
337 Send a message saying the queue changed.
338 ****************************************************************************/
340 static void send_queue_message(const char *printer_name, uint32 high, uint32 low)
342 char msg[sizeof(PRINTER_MESSAGE_INFO)];
343 PRINTER_MESSAGE_INFO info;
345 ZERO_STRUCT(info);
347 info.low = low;
348 info.high = high;
349 info.flags = 0;
350 fstrcpy(info.printer_name, printer_name);
351 memcpy( msg, &info, sizeof(PRINTER_MESSAGE_INFO));
353 message_send_all(conn_tdb_ctx(), MSG_PRINTER_NOTIFY, msg, sizeof(PRINTER_MESSAGE_INFO), False, NULL);
356 /****************************************************************************
357 update the internal database from the system print queue for a queue
358 ****************************************************************************/
360 static void print_queue_update(int snum)
362 int i, qcount;
363 print_queue_struct *queue = NULL;
364 print_status_struct status;
365 print_status_struct old_status;
366 struct printjob *pjob;
367 struct traverse_struct tstruct;
368 fstring keystr, printer_name, cachestr;
369 TDB_DATA data, key;
371 /* Convert printer name (i.e. share name) to unix-codepage for all of the
372 * following tdb key generation */
373 fstrcpy(printer_name, lp_servicename(snum));
374 dos_to_unix(printer_name);
377 * Check to see if someone else is doing this update.
378 * This is essentially a mutex on the update.
381 if (get_updating_pid(printer_name) != -1)
382 return;
384 /* Lock the queue for the database update */
386 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", printer_name);
387 /* Only wait 10 seconds for this. */
388 if (tdb_lock_bystring(tdb, keystr, 10) == -1) {
389 DEBUG(0,("print_queue_update: Failed to lock printing database\n" ));
390 return;
394 * Ensure that no one else got in here.
395 * If the updating pid is still -1 then we are
396 * the winner.
399 if (get_updating_pid(printer_name) != -1) {
401 * Someone else is doing the update, exit.
403 tdb_unlock_bystring(tdb, keystr);
404 return;
408 * We're going to do the update ourselves.
411 /* Tell others we're doing the update. */
412 set_updating_pid(printer_name, False);
415 * Allow others to enter and notice we're doing
416 * the update.
419 tdb_unlock_bystring(tdb, keystr);
422 * Update the cache time FIRST ! Stops others even
423 * attempting to get the lock and doing this
424 * if the lpq takes a long time.
427 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", printer_name);
428 tdb_store_int32(tdb, cachestr, (int)time(NULL));
430 /* get the current queue using the appropriate interface */
431 ZERO_STRUCT(status);
433 qcount = (*(current_printif->queue_get))(snum, &queue, &status);
435 DEBUG(3, ("%d job%s in queue for %s\n", qcount, (qcount != 1) ?
436 "s" : "", printer_name));
439 any job in the internal database that is marked as spooled
440 and doesn't exist in the system queue is considered finished
441 and removed from the database
443 any job in the system database but not in the internal database
444 is added as a unix job
446 fill in any system job numbers as we go
448 for (i=0; i<qcount; i++) {
449 int jobid = print_parse_jobid(queue[i].fs_file);
451 if (jobid == -1) {
452 /* assume its a unix print job */
453 print_unix_job(snum, &queue[i]);
454 continue;
457 /* we have an active SMB print job - update its status */
458 pjob = print_job_find(jobid);
459 if (!pjob) {
460 /* err, somethings wrong. Probably smbd was restarted
461 with jobs in the queue. All we can do is treat them
462 like unix jobs. Pity. */
463 print_unix_job(snum, &queue[i]);
464 continue;
467 pjob->sysjob = queue[i].job;
468 pjob->status = queue[i].status;
470 print_job_store(jobid, pjob);
473 /* now delete any queued entries that don't appear in the
474 system queue */
475 tstruct.queue = queue;
476 tstruct.qcount = qcount;
477 tstruct.snum = snum;
478 tstruct.total_jobs = 0;
480 tdb_traverse(tdb, traverse_fn_delete, (void *)&tstruct);
482 safe_free(tstruct.queue);
484 tdb_store_int32(tdb, "INFO/total_jobs", tstruct.total_jobs);
487 * Get the old print status. We will use this to compare the
488 * number of jobs. If they have changed we need to send a
489 * "changed" message to the smbds.
492 if( qcount != get_queue_status(snum, &old_status)) {
493 DEBUG(10,("print_queue_update: queue status change %d jobs -> %d jobs for printer %s\n",
494 old_status.qcount, qcount, printer_name ));
495 send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
498 /* store the new queue status structure */
499 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printer_name);
500 key.dptr = keystr;
501 key.dsize = strlen(keystr);
503 status.qcount = qcount;
504 data.dptr = (void *)&status;
505 data.dsize = sizeof(status);
506 tdb_store(tdb, key, data, TDB_REPLACE);
509 * Update the cache time again. We want to do this call
510 * as little as possible...
513 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", printer_name);
514 tdb_store_int32(tdb, keystr, (int32)time(NULL));
516 /* Delete our pid from the db. */
517 set_updating_pid(printer_name, True);
520 /****************************************************************************
521 Check if a jobid is valid. It is valid if it exists in the database.
522 ****************************************************************************/
524 BOOL print_job_exists(int jobid)
526 return tdb_exists(tdb, print_key(jobid));
529 /****************************************************************************
530 Work out which service a jobid is for.
531 Note that we have to look up by queue name to ensure that it works for
532 other than the process that started the job.
533 ****************************************************************************/
535 int print_job_snum(int jobid)
537 struct printjob *pjob = print_job_find(jobid);
538 if (!pjob)
539 return -1;
541 return find_service(pjob->queuename);
544 /****************************************************************************
545 Give the fd used for a jobid.
546 ****************************************************************************/
548 int print_job_fd(int jobid)
550 struct printjob *pjob = print_job_find(jobid);
551 if (!pjob)
552 return -1;
553 /* don't allow another process to get this info - it is meaningless */
554 if (pjob->pid != local_pid)
555 return -1;
556 return pjob->fd;
559 /****************************************************************************
560 Give the filename used for a jobid.
561 Only valid for the process doing the spooling and when the job
562 has not been spooled.
563 ****************************************************************************/
565 char *print_job_fname(int jobid)
567 struct printjob *pjob = print_job_find(jobid);
568 if (!pjob || pjob->spooled || pjob->pid != local_pid)
569 return NULL;
570 return pjob->filename;
573 /****************************************************************************
574 Set the place in the queue for a job.
575 ****************************************************************************/
577 BOOL print_job_set_place(int jobid, int place)
579 DEBUG(2,("print_job_set_place not implemented yet\n"));
580 return False;
583 /****************************************************************************
584 Set the name of a job. Only possible for owner.
585 ****************************************************************************/
587 BOOL print_job_set_name(int jobid, char *name)
589 struct printjob *pjob = print_job_find(jobid);
590 if (!pjob || pjob->pid != local_pid)
591 return False;
593 fstrcpy(pjob->jobname, name);
594 return print_job_store(jobid, pjob);
597 /****************************************************************************
598 Delete a print job - don't update queue.
599 ****************************************************************************/
601 static BOOL print_job_delete1(int jobid)
603 struct printjob *pjob = print_job_find(jobid);
604 int snum, result = 0;
606 if (!pjob)
607 return False;
610 * If already deleting just return.
613 if (pjob->status == LPQ_DELETING)
614 return True;
616 snum = print_job_snum(jobid);
617 if (snum == -1) {
618 DEBUG(5,("print_job_delete1: unknown service number for jobid %d\n", jobid));
619 return False;
622 /* Hrm - we need to be able to cope with deleting a job before it
623 has reached the spooler. */
625 if (pjob->sysjob == -1) {
626 DEBUG(5, ("attempt to delete job %d not seen by lpr\n", jobid));
629 /* Set the tdb entry to be deleting. */
631 pjob->status = LPQ_DELETING;
632 print_job_store(jobid, pjob);
634 if (pjob->spooled && pjob->sysjob != -1)
635 result = (*(current_printif->job_delete))(snum, pjob);
637 /* Delete the tdb entry if the delete suceeded or the job hasn't
638 been spooled. */
640 if (result == 0) {
641 tdb_delete(tdb, print_key(jobid));
644 return (result == 0);
647 /****************************************************************************
648 Return true if the current user owns the print job.
649 ****************************************************************************/
651 static BOOL is_owner(struct current_user *user, int jobid)
653 struct printjob *pjob = print_job_find(jobid);
654 user_struct *vuser;
656 if (!pjob || !user)
657 return False;
659 if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
660 return strequal(pjob->user,
661 unix_to_dos_static(vuser->user.smb_name));
662 } else {
663 return strequal(pjob->user,
664 unix_to_dos_static(uidtoname(user->uid)));
668 /****************************************************************************
669 Delete a print job.
670 ****************************************************************************/
672 BOOL print_job_delete(struct current_user *user, int jobid, WERROR *errcode)
674 int snum = print_job_snum(jobid);
675 char *printer_name;
676 BOOL owner;
678 if (snum == -1) {
679 DEBUG(5,("print_job_delete: unknown service number for jobid %d\n", jobid));
680 return False;
683 owner = is_owner(user, jobid);
685 /* Check access against security descriptor or whether the user
686 owns their job. */
688 if (!owner &&
689 !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
690 DEBUG(3, ("delete denied by security descriptor\n"));
691 *errcode = WERR_ACCESS_DENIED;
692 return False;
695 if (!print_job_delete1(jobid))
696 return False;
698 /* force update the database and say the delete failed if the
699 job still exists */
701 print_queue_update(snum);
703 /* Send a printer notify message */
705 printer_name = PRINTERNAME(snum);
707 send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
709 return !print_job_exists(jobid);
712 /****************************************************************************
713 Pause a job.
714 ****************************************************************************/
716 BOOL print_job_pause(struct current_user *user, int jobid, WERROR *errcode)
718 struct printjob *pjob = print_job_find(jobid);
719 int snum, ret = -1;
720 char *printer_name;
722 if (!pjob || !user)
723 return False;
725 if (!pjob->spooled || pjob->sysjob == -1)
726 return False;
728 snum = print_job_snum(jobid);
729 if (snum == -1) {
730 DEBUG(5,("print_job_pause: unknown service number for jobid %d\n", jobid));
731 return False;
734 if (!is_owner(user, jobid) &&
735 !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
736 DEBUG(3, ("pause denied by security descriptor\n"));
737 *errcode = WERR_ACCESS_DENIED;
738 return False;
741 /* need to pause the spooled entry */
742 ret = (*(current_printif->job_pause))(snum, pjob);
744 if (ret != 0) {
745 *errcode = WERR_INVALID_PARAM;
746 return False;
749 /* force update the database */
750 print_cache_flush(snum);
752 /* Send a printer notify message */
754 printer_name = PRINTERNAME(snum);
756 send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
758 /* how do we tell if this succeeded? */
760 return True;
763 /****************************************************************************
764 Resume a job.
765 ****************************************************************************/
767 BOOL print_job_resume(struct current_user *user, int jobid, WERROR *errcode)
769 struct printjob *pjob = print_job_find(jobid);
770 char *printer_name;
771 int snum, ret;
773 if (!pjob || !user)
774 return False;
776 if (!pjob->spooled || pjob->sysjob == -1)
777 return False;
779 snum = print_job_snum(jobid);
780 if (snum == -1) {
781 DEBUG(5,("print_job_resume: unknown service number for jobid %d\n", jobid));
782 return False;
785 if (!is_owner(user, jobid) &&
786 !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
787 DEBUG(3, ("resume denied by security descriptor\n"));
788 *errcode = WERR_ACCESS_DENIED;
789 return False;
792 ret = (*(current_printif->job_resume))(snum, pjob);
794 if (ret != 0) {
795 *errcode = WERR_INVALID_PARAM;
796 return False;
799 /* force update the database */
800 print_cache_flush(snum);
802 /* Send a printer notify message */
804 printer_name = PRINTERNAME(snum);
806 send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
808 return True;
811 /****************************************************************************
812 Write to a print file.
813 ****************************************************************************/
815 int print_job_write(int jobid, const char *buf, int size)
817 int return_code;
818 struct printjob *pjob = print_job_find(jobid);
820 if (!pjob)
821 return -1;
822 /* don't allow another process to get this info - it is meaningless */
823 if (pjob->pid != local_pid)
824 return -1;
826 return_code = write(pjob->fd, buf, size);
827 if (return_code>0) {
828 pjob->size += size;
829 print_job_store(jobid, pjob);
831 return return_code;
834 /****************************************************************************
835 Check if the print queue has been updated recently enough.
836 ****************************************************************************/
838 static BOOL print_cache_expired(int snum)
840 fstring key;
841 time_t last_qscan_time, time_now = time(NULL);
843 slprintf(key, sizeof(key), "CACHE/%s", lp_servicename(snum));
844 dos_to_unix(key); /* Convert key to unix-codepage */
845 last_qscan_time = (time_t)tdb_fetch_int32(tdb, key);
848 * Invalidate the queue for 3 reasons.
849 * (1). last queue scan time == -1.
850 * (2). Current time - last queue scan time > allowed cache time.
851 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
852 * This last test picks up machines for which the clock has been moved
853 * forward, an lpq scan done and then the clock moved back. Otherwise
854 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
857 if (last_qscan_time == ((time_t)-1) || (time_now - last_qscan_time) >= lp_lpqcachetime() ||
858 last_qscan_time > (time_now + MAX_CACHE_VALID_TIME)) {
859 DEBUG(3, ("print cache expired for queue %s \
860 (last_qscan_time = %d, time now = %d, qcachetime = %d)\n", lp_servicename(snum),
861 (int)last_qscan_time, (int)time_now, (int)lp_lpqcachetime() ));
862 return True;
864 return False;
867 /****************************************************************************
868 Get the queue status - do not update if db is out of date.
869 ****************************************************************************/
871 static int get_queue_status(int snum, print_status_struct *status)
873 fstring keystr;
874 TDB_DATA data, key;
876 ZERO_STRUCTP(status);
877 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", lp_servicename(snum));
878 dos_to_unix(keystr); /* Convert key to unix-codepage */
879 key.dptr = keystr;
880 key.dsize = strlen(keystr);
881 data = tdb_fetch(tdb, key);
882 if (data.dptr) {
883 if (data.dsize == sizeof(print_status_struct)) {
884 memcpy(status, data.dptr, sizeof(print_status_struct));
886 SAFE_FREE(data.dptr);
888 return status->qcount;
891 /****************************************************************************
892 Determine the number of jobs in a queue.
893 ****************************************************************************/
895 int print_queue_length(int snum, print_status_struct *pstatus)
897 print_status_struct status;
898 int len;
900 /* make sure the database is up to date */
901 if (print_cache_expired(snum))
902 print_queue_update(snum);
904 /* also fetch the queue status */
905 memset(&status, 0, sizeof(status));
906 len = get_queue_status(snum, &status);
907 if (pstatus)
908 *pstatus = status;
909 return len;
912 /****************************************************************************
913 Determine the number of jobs in all queues.
914 ****************************************************************************/
916 static int get_total_jobs(int snum)
918 int total_jobs;
920 /* make sure the database is up to date */
921 if (print_cache_expired(snum))
922 print_queue_update(snum);
924 total_jobs = tdb_fetch_int32(tdb, "INFO/total_jobs");
925 if (total_jobs >0)
926 return total_jobs;
927 else
928 return 0;
931 /***************************************************************************
932 Start spooling a job - return the jobid.
933 ***************************************************************************/
935 int print_job_start(struct current_user *user, int snum, char *jobname)
937 int jobid;
938 char *path;
939 struct printjob pjob;
940 int next_jobid;
941 user_struct *vuser;
942 int njobs = 0;
944 errno = 0;
946 if (!print_access_check(user, snum, PRINTER_ACCESS_USE)) {
947 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
948 return -1;
951 if (!print_time_access_check(snum)) {
952 DEBUG(3, ("print_job_start: job start denied by time check\n"));
953 return -1;
956 path = lp_pathname(snum);
958 /* see if we have sufficient disk space */
959 if (lp_minprintspace(snum)) {
960 SMB_BIG_UINT dspace, dsize;
961 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
962 dspace < 2*(SMB_BIG_UINT)lp_minprintspace(snum)) {
963 DEBUG(3, ("print_job_start: disk space check failed.\n"));
964 errno = ENOSPC;
965 return -1;
969 /* for autoloaded printers, check that the printcap entry still exists */
970 if (lp_autoloaded(snum) && !pcap_printername_ok(lp_servicename(snum), NULL)) {
971 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_servicename(snum) ));
972 errno = ENOENT;
973 return -1;
976 /* Insure the maximum queue size is not violated */
977 if (lp_maxprintjobs(snum) && (njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
978 DEBUG(3, ("print_job_start: number of jobs (%d) larger than max printjobs per queue (%d).\n",
979 njobs, lp_maxprintjobs(snum) ));
980 errno = ENOSPC;
981 return -1;
984 /* Insure the maximum print jobs in the system is not violated */
985 if (lp_totalprintjobs() && get_total_jobs(snum) > lp_totalprintjobs()) {
986 DEBUG(3, ("print_job_start: number of jobs (%d) larger than max printjobs per system (%d).\n",
987 njobs, lp_totalprintjobs() ));
988 errno = ENOSPC;
989 return -1;
992 /* create the database entry */
993 ZERO_STRUCT(pjob);
994 pjob.pid = local_pid;
995 pjob.sysjob = -1;
996 pjob.fd = -1;
997 pjob.starttime = time(NULL);
998 pjob.status = LPQ_SPOOLING;
999 pjob.size = 0;
1000 pjob.spooled = False;
1001 pjob.smbjob = True;
1003 fstrcpy(pjob.jobname, jobname);
1005 if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
1006 fstrcpy(pjob.user, unix_to_dos_static(vuser->user.smb_name));
1007 } else {
1008 fstrcpy(pjob.user, unix_to_dos_static(uidtoname(user->uid)));
1011 fstrcpy(pjob.queuename, lp_servicename(snum));
1013 /* Lock the database - only wait 20 seconds. */
1014 if (tdb_lock_bystring(tdb, "INFO/nextjob", 20) == -1) {
1015 DEBUG(0,("print_job_start: failed to lock printing database.\n"));
1016 return -1;
1019 next_jobid = tdb_fetch_int32(tdb, "INFO/nextjob");
1020 if (next_jobid == -1)
1021 next_jobid = 1;
1023 for (jobid = NEXT_JOBID(next_jobid); jobid != next_jobid; jobid = NEXT_JOBID(jobid)) {
1024 if (!print_job_exists(jobid))
1025 break;
1027 if (jobid == next_jobid || !print_job_store(jobid, &pjob)) {
1028 DEBUG(3, ("print_job_start: either jobid (%d)==next_jobid(%d) or print_job_store failed.\n",
1029 jobid, next_jobid ));
1030 jobid = -1;
1031 goto fail;
1034 tdb_store_int32(tdb, "INFO/nextjob", jobid);
1036 /* we have a job entry - now create the spool file */
1037 slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.6d.XXXXXX",
1038 path, PRINT_SPOOL_PREFIX, jobid);
1039 pjob.fd = smb_mkstemp(pjob.filename);
1041 if (pjob.fd == -1) {
1042 if (errno == EACCES) {
1043 /* Common setup error, force a report. */
1044 DEBUG(0, ("print_job_start: insufficient permissions \
1045 to open spool file %s.\n", pjob.filename));
1046 } else {
1047 /* Normal case, report at level 3 and above. */
1048 DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
1049 DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
1051 goto fail;
1054 print_job_store(jobid, &pjob);
1056 tdb_unlock_bystring(tdb, "INFO/nextjob");
1059 * If the printer is marked as postscript output a leading
1060 * file identifier to ensure the file is treated as a raw
1061 * postscript file.
1062 * This has a similar effect as CtrlD=0 in WIN.INI file.
1063 * tim@fsg.com 09/06/94
1065 if (lp_postscript(snum)) {
1066 print_job_write(jobid, "%!\n",3);
1069 return jobid;
1071 fail:
1072 if (jobid != -1) {
1073 tdb_delete(tdb, print_key(jobid));
1076 tdb_unlock_bystring(tdb, "INFO/nextjob");
1078 DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
1079 return -1;
1082 /****************************************************************************
1083 Update the number of pages spooled to jobid
1084 ****************************************************************************/
1086 void print_job_endpage(int jobid)
1088 struct printjob *pjob = print_job_find(jobid);
1089 if (!pjob)
1090 return;
1091 /* don't allow another process to get this info - it is meaningless */
1092 if (pjob->pid != local_pid)
1093 return;
1095 pjob->page_count++;
1096 print_job_store(jobid, pjob);
1099 /****************************************************************************
1100 Print a file - called on closing the file. This spools the job.
1101 If normal close is false then we're tearing down the jobs - treat as an
1102 error.
1103 ****************************************************************************/
1105 BOOL print_job_end(int jobid, BOOL normal_close)
1107 struct printjob *pjob = print_job_find(jobid);
1108 int snum, ret;
1109 SMB_STRUCT_STAT sbuf;
1111 if (!pjob)
1112 return False;
1114 if (pjob->spooled || pjob->pid != local_pid)
1115 return False;
1117 snum = print_job_snum(jobid);
1118 if (snum == -1) {
1119 DEBUG(5,("print_job_end: unknown service number for jobid %d\n", jobid));
1120 return False;
1123 if (normal_close && (sys_fstat(pjob->fd, &sbuf) == 0)) {
1124 pjob->size = sbuf.st_size;
1125 close(pjob->fd);
1126 pjob->fd = -1;
1127 } else {
1130 * Not a normal close or we couldn't stat the job file,
1131 * so something has gone wrong. Cleanup.
1133 close(pjob->fd);
1134 pjob->fd = -1;
1135 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
1136 goto fail;
1139 /* Technically, this is not quit right. If the printer has a separator
1140 * page turned on, the NT spooler prints the separator page even if the
1141 * print job is 0 bytes. 010215 JRR */
1142 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
1143 /* don't bother spooling empty files or something being deleted. */
1144 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
1145 pjob->filename, pjob->size ? "deleted" : "zero length" ));
1146 unlink(pjob->filename);
1147 tdb_delete(tdb, print_key(jobid));
1148 return True;
1151 ret = (*(current_printif->job_submit))(snum, pjob);
1153 if (ret)
1154 goto fail;
1156 /* The print job has been sucessfully handed over to the back-end */
1158 pjob->spooled = True;
1159 pjob->status = LPQ_QUEUED;
1160 print_job_store(jobid, pjob);
1162 /* make sure the database is up to date */
1163 if (print_cache_expired(snum))
1164 print_queue_update(snum);
1166 return True;
1168 fail:
1170 /* The print job was not succesfully started. Cleanup */
1171 /* Still need to add proper error return propagation! 010122:JRR */
1172 unlink(pjob->filename);
1173 tdb_delete(tdb, print_key(jobid));
1174 return False;
1177 /****************************************************************************
1178 Utility fn to enumerate the print queue.
1179 ****************************************************************************/
1181 static int traverse_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1183 struct traverse_struct *ts = (struct traverse_struct *)state;
1184 struct printjob pjob;
1185 int i, jobid;
1187 if (data.dsize != sizeof(pjob) || key.dsize != sizeof(int))
1188 return 0;
1189 memcpy(&jobid, key.dptr, sizeof(jobid));
1190 memcpy(&pjob, data.dptr, sizeof(pjob));
1191 unix_to_dos(pjob.queuename);
1193 /* maybe it isn't for this queue */
1194 if (ts->snum != lp_servicenumber(pjob.queuename))
1195 return 0;
1197 if (ts->qcount >= ts->maxcount)
1198 return 0;
1200 i = ts->qcount;
1202 ts->queue[i].job = jobid;
1203 ts->queue[i].size = pjob.size;
1204 ts->queue[i].page_count = pjob.page_count;
1205 ts->queue[i].status = pjob.status;
1206 ts->queue[i].priority = 1;
1207 ts->queue[i].time = pjob.starttime;
1208 fstrcpy(ts->queue[i].fs_user, pjob.user);
1209 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1211 ts->qcount++;
1213 return 0;
1216 struct traverse_count_struct {
1217 int snum, count;
1220 /****************************************************************************
1221 Utility fn to count the number of entries in the print queue.
1222 ****************************************************************************/
1224 static int traverse_count_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1226 struct traverse_count_struct *ts = (struct traverse_count_struct *)state;
1227 struct printjob pjob;
1228 int jobid;
1230 if (data.dsize != sizeof(pjob) || key.dsize != sizeof(int))
1231 return 0;
1232 memcpy(&jobid, key.dptr, sizeof(jobid));
1233 memcpy(&pjob, data.dptr, sizeof(pjob));
1234 unix_to_dos(pjob.queuename);
1236 /* maybe it isn't for this queue */
1237 if (ts->snum != lp_servicenumber(pjob.queuename))
1238 return 0;
1240 ts->count++;
1242 return 0;
1245 /****************************************************************************
1246 Sort print jobs by submittal time.
1247 ****************************************************************************/
1249 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1251 /* Silly cases */
1253 if (!j1 && !j2)
1254 return 0;
1255 if (!j1)
1256 return -1;
1257 if (!j2)
1258 return 1;
1260 /* Sort on job start time */
1262 if (j1->time == j2->time)
1263 return 0;
1264 return (j1->time > j2->time) ? 1 : -1;
1267 /****************************************************************************
1268 Get a printer queue listing.
1269 ****************************************************************************/
1271 int print_queue_status(int snum,
1272 print_queue_struct **queue,
1273 print_status_struct *status)
1275 struct traverse_struct tstruct;
1276 struct traverse_count_struct tsc;
1277 fstring keystr;
1278 TDB_DATA data, key;
1280 /* make sure the database is up to date */
1281 if (print_cache_expired(snum))
1282 print_queue_update(snum);
1284 *queue = NULL;
1287 * Fetch the queue status. We must do this first, as there may
1288 * be no jobs in the queue.
1290 ZERO_STRUCTP(status);
1291 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", lp_servicename(snum));
1292 dos_to_unix(keystr); /* Convert key to unix-codepage */
1293 key.dptr = keystr;
1294 key.dsize = strlen(keystr);
1295 data = tdb_fetch(tdb, key);
1296 if (data.dptr) {
1297 if (data.dsize == sizeof(*status)) {
1298 memcpy(status, data.dptr, sizeof(*status));
1300 SAFE_FREE(data.dptr);
1304 * Now, fetch the print queue information. We first count the number
1305 * of entries, and then only retrieve the queue if necessary.
1307 tsc.count = 0;
1308 tsc.snum = snum;
1310 tdb_traverse(tdb, traverse_count_fn_queue, (void *)&tsc);
1312 if (tsc.count == 0)
1313 return 0;
1315 /* Allocate the queue size. */
1316 if ((tstruct.queue = (print_queue_struct *)
1317 malloc(sizeof(print_queue_struct)*tsc.count)) == NULL)
1318 return 0;
1321 * Fill in the queue.
1322 * We need maxcount as the queue size may have changed between
1323 * the two calls to tdb_traverse.
1325 tstruct.qcount = 0;
1326 tstruct.maxcount = tsc.count;
1327 tstruct.snum = snum;
1329 tdb_traverse(tdb, traverse_fn_queue, (void *)&tstruct);
1331 /* Sort the queue by submission time otherwise they are displayed
1332 in hash order. */
1334 qsort(tstruct.queue, tstruct.qcount, sizeof(print_queue_struct),
1335 QSORT_CAST(printjob_comp));
1337 *queue = tstruct.queue;
1338 return tstruct.qcount;
1341 /****************************************************************************
1342 Turn a queue name into a snum.
1343 ****************************************************************************/
1345 int print_queue_snum(char *qname)
1347 int snum = lp_servicenumber(qname);
1348 if (snum == -1 || !lp_print_ok(snum))
1349 return -1;
1350 return snum;
1353 /****************************************************************************
1354 Pause a queue.
1355 ****************************************************************************/
1357 BOOL print_queue_pause(struct current_user *user, int snum, WERROR *errcode)
1359 char *printer_name;
1360 int ret;
1362 if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
1363 *errcode = WERR_ACCESS_DENIED;
1364 return False;
1367 ret = (*(current_printif->queue_pause))(snum);
1369 if (ret != 0) {
1370 *errcode = WERR_INVALID_PARAM;
1371 return False;
1374 /* force update the database */
1375 print_cache_flush(snum);
1377 /* Send a printer notify message */
1379 printer_name = PRINTERNAME(snum);
1381 send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
1383 return True;
1386 /****************************************************************************
1387 Resume a queue.
1388 ****************************************************************************/
1390 BOOL print_queue_resume(struct current_user *user, int snum, WERROR *errcode)
1392 char *printer_name;
1393 int ret;
1395 if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
1396 *errcode = WERR_ACCESS_DENIED;
1397 return False;
1400 ret = (*(current_printif->queue_resume))(snum);
1402 if (ret != 0) {
1403 *errcode = WERR_INVALID_PARAM;
1404 return False;
1407 /* make sure the database is up to date */
1408 if (print_cache_expired(snum)) print_queue_update(snum);
1410 /* Send a printer notify message */
1412 printer_name = PRINTERNAME(snum);
1414 send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
1416 return True;
1419 /****************************************************************************
1420 Purge a queue - implemented by deleting all jobs that we can delete.
1421 ****************************************************************************/
1423 BOOL print_queue_purge(struct current_user *user, int snum, WERROR *errcode)
1425 print_queue_struct *queue;
1426 print_status_struct status;
1427 char *printer_name;
1428 int njobs, i;
1429 BOOL can_job_admin;
1431 /* Force and update so the count is accurate (i.e. not a cached count) */
1432 print_queue_update(snum);
1434 can_job_admin = print_access_check(user, snum, JOB_ACCESS_ADMINISTER);
1435 njobs = print_queue_status(snum, &queue, &status);
1437 for (i=0;i<njobs;i++) {
1438 BOOL owner = is_owner(user, queue[i].job);
1440 if (owner || can_job_admin) {
1441 print_job_delete1(queue[i].job);
1445 safe_free(queue);
1447 /* Send a printer notify message */
1449 printer_name = PRINTERNAME(snum);
1451 send_queue_message(printer_name, 0, PRINTER_CHANGE_JOB);
1453 return True;