clean up lib64 linking paths the same way as lib
[Samba/gebeck_regimport.git] / source3 / printing / printing.c
blob71c634442b325fc84f272e73da1a221659b3cffe
1 /*
2 Unix SMB/Netbios implementation.
3 Version 3.0
4 printing backend routines
5 Copyright (C) Andrew Tridgell 1992-2000
6 Copyright (C) Jeremy Allison 2002
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "includes.h"
23 #include "printing.h"
25 extern struct current_user current_user;
26 extern userdom_struct current_user_info;
28 /* Current printer interface */
29 static bool remove_from_jobs_changed(const char* sharename, uint32 jobid);
32 the printing backend revolves around a tdb database that stores the
33 SMB view of the print queue
35 The key for this database is a jobid - a internally generated number that
36 uniquely identifies a print job
38 reading the print queue involves two steps:
39 - possibly running lpq and updating the internal database from that
40 - reading entries from the database
42 jobids are assigned when a job starts spooling.
45 static TDB_CONTEXT *rap_tdb;
46 static uint16 next_rap_jobid;
47 struct rap_jobid_key {
48 fstring sharename;
49 uint32 jobid;
52 /***************************************************************************
53 Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
54 bit RPC jobids.... JRA.
55 ***************************************************************************/
57 uint16 pjobid_to_rap(const char* sharename, uint32 jobid)
59 uint16 rap_jobid;
60 TDB_DATA data, key;
61 struct rap_jobid_key jinfo;
62 uint8 buf[2];
64 DEBUG(10,("pjobid_to_rap: called.\n"));
66 if (!rap_tdb) {
67 /* Create the in-memory tdb. */
68 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
69 if (!rap_tdb)
70 return 0;
73 ZERO_STRUCT( jinfo );
74 fstrcpy( jinfo.sharename, sharename );
75 jinfo.jobid = jobid;
76 key.dptr = (uint8 *)&jinfo;
77 key.dsize = sizeof(jinfo);
79 data = tdb_fetch(rap_tdb, key);
80 if (data.dptr && data.dsize == sizeof(uint16)) {
81 rap_jobid = SVAL(data.dptr, 0);
82 SAFE_FREE(data.dptr);
83 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
84 (unsigned int)jobid, (unsigned int)rap_jobid));
85 return rap_jobid;
87 SAFE_FREE(data.dptr);
88 /* Not found - create and store mapping. */
89 rap_jobid = ++next_rap_jobid;
90 if (rap_jobid == 0)
91 rap_jobid = ++next_rap_jobid;
92 SSVAL(buf,0,rap_jobid);
93 data.dptr = buf;
94 data.dsize = sizeof(rap_jobid);
95 tdb_store(rap_tdb, key, data, TDB_REPLACE);
96 tdb_store(rap_tdb, data, key, TDB_REPLACE);
98 DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
99 (unsigned int)jobid, (unsigned int)rap_jobid));
100 return rap_jobid;
103 bool rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
105 TDB_DATA data, key;
106 uint8 buf[2];
108 DEBUG(10,("rap_to_pjobid called.\n"));
110 if (!rap_tdb)
111 return False;
113 SSVAL(buf,0,rap_jobid);
114 key.dptr = buf;
115 key.dsize = sizeof(rap_jobid);
116 data = tdb_fetch(rap_tdb, key);
117 if ( data.dptr && data.dsize == sizeof(struct rap_jobid_key) )
119 struct rap_jobid_key *jinfo = (struct rap_jobid_key*)data.dptr;
120 if (sharename != NULL) {
121 fstrcpy( sharename, jinfo->sharename );
123 *pjobid = jinfo->jobid;
124 DEBUG(10,("rap_to_pjobid: jobid %u maps to RAP jobid %u\n",
125 (unsigned int)*pjobid, (unsigned int)rap_jobid));
126 SAFE_FREE(data.dptr);
127 return True;
130 DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
131 (unsigned int)rap_jobid));
132 SAFE_FREE(data.dptr);
133 return False;
136 static void rap_jobid_delete(const char* sharename, uint32 jobid)
138 TDB_DATA key, data;
139 uint16 rap_jobid;
140 struct rap_jobid_key jinfo;
141 uint8 buf[2];
143 DEBUG(10,("rap_jobid_delete: called.\n"));
145 if (!rap_tdb)
146 return;
148 ZERO_STRUCT( jinfo );
149 fstrcpy( jinfo.sharename, sharename );
150 jinfo.jobid = jobid;
151 key.dptr = (uint8 *)&jinfo;
152 key.dsize = sizeof(jinfo);
154 data = tdb_fetch(rap_tdb, key);
155 if (!data.dptr || (data.dsize != sizeof(uint16))) {
156 DEBUG(10,("rap_jobid_delete: cannot find jobid %u\n",
157 (unsigned int)jobid ));
158 SAFE_FREE(data.dptr);
159 return;
162 DEBUG(10,("rap_jobid_delete: deleting jobid %u\n",
163 (unsigned int)jobid ));
165 rap_jobid = SVAL(data.dptr, 0);
166 SAFE_FREE(data.dptr);
167 SSVAL(buf,0,rap_jobid);
168 data.dptr = buf;
169 data.dsize = sizeof(rap_jobid);
170 tdb_delete(rap_tdb, key);
171 tdb_delete(rap_tdb, data);
174 static int get_queue_status(const char* sharename, print_status_struct *);
176 /****************************************************************************
177 Initialise the printing backend. Called once at startup before the fork().
178 ****************************************************************************/
180 bool print_backend_init(struct messaging_context *msg_ctx)
182 const char *sversion = "INFO/version";
183 int services = lp_numservices();
184 int snum;
186 unlink(cache_path("printing.tdb"));
187 mkdir(cache_path("printing"),0755);
189 /* handle a Samba upgrade */
191 for (snum = 0; snum < services; snum++) {
192 struct tdb_print_db *pdb;
193 if (!lp_print_ok(snum))
194 continue;
196 pdb = get_print_db_byname(lp_const_servicename(snum));
197 if (!pdb)
198 continue;
199 if (tdb_lock_bystring(pdb->tdb, sversion) == -1) {
200 DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
201 release_print_db(pdb);
202 return False;
204 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
205 tdb_wipe_all(pdb->tdb);
206 tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
208 tdb_unlock_bystring(pdb->tdb, sversion);
209 release_print_db(pdb);
212 close_all_print_db(); /* Don't leave any open. */
214 /* do NT print initialization... */
215 return nt_printing_init(msg_ctx);
218 /****************************************************************************
219 Shut down printing backend. Called once at shutdown to close the tdb.
220 ****************************************************************************/
222 void printing_end(void)
224 close_all_print_db(); /* Don't leave any open. */
227 /****************************************************************************
228 Retrieve the set of printing functions for a given service. This allows
229 us to set the printer function table based on the value of the 'printing'
230 service parameter.
232 Use the generic interface as the default and only use cups interface only
233 when asked for (and only when supported)
234 ****************************************************************************/
236 static struct printif *get_printer_fns_from_type( enum printing_types type )
238 struct printif *printer_fns = &generic_printif;
240 #ifdef HAVE_CUPS
241 if ( type == PRINT_CUPS ) {
242 printer_fns = &cups_printif;
244 #endif /* HAVE_CUPS */
246 #ifdef HAVE_IPRINT
247 if ( type == PRINT_IPRINT ) {
248 printer_fns = &iprint_printif;
250 #endif /* HAVE_IPRINT */
252 printer_fns->type = type;
254 return printer_fns;
257 static struct printif *get_printer_fns( int snum )
259 return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
263 /****************************************************************************
264 Useful function to generate a tdb key.
265 ****************************************************************************/
267 static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
269 TDB_DATA ret;
271 SIVAL(tmp, 0, jobid);
272 ret.dptr = (uint8 *)tmp;
273 ret.dsize = sizeof(*tmp);
274 return ret;
277 /***********************************************************************
278 unpack a pjob from a tdb buffer
279 ***********************************************************************/
281 int unpack_pjob( uint8 *buf, int buflen, struct printjob *pjob )
283 int len = 0;
284 int used;
285 uint32 pjpid, pjsysjob, pjfd, pjstarttime, pjstatus;
286 uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
288 if ( !buf || !pjob )
289 return -1;
291 len += tdb_unpack(buf+len, buflen-len, "dddddddddffff",
292 &pjpid,
293 &pjsysjob,
294 &pjfd,
295 &pjstarttime,
296 &pjstatus,
297 &pjsize,
298 &pjpage_count,
299 &pjspooled,
300 &pjsmbjob,
301 pjob->filename,
302 pjob->jobname,
303 pjob->user,
304 pjob->queuename);
306 if ( len == -1 )
307 return -1;
309 if ( (used = unpack_devicemode(&pjob->nt_devmode, buf+len, buflen-len)) == -1 )
310 return -1;
312 len += used;
314 pjob->pid = pjpid;
315 pjob->sysjob = pjsysjob;
316 pjob->fd = pjfd;
317 pjob->starttime = pjstarttime;
318 pjob->status = pjstatus;
319 pjob->size = pjsize;
320 pjob->page_count = pjpage_count;
321 pjob->spooled = pjspooled;
322 pjob->smbjob = pjsmbjob;
324 return len;
328 /****************************************************************************
329 Useful function to find a print job in the database.
330 ****************************************************************************/
332 static struct printjob *print_job_find(const char *sharename, uint32 jobid)
334 static struct printjob pjob;
335 uint32_t tmp;
336 TDB_DATA ret;
337 struct tdb_print_db *pdb = get_print_db_byname(sharename);
339 DEBUG(10,("print_job_find: looking up job %u for share %s\n",
340 (unsigned int)jobid, sharename ));
342 if (!pdb) {
343 return NULL;
346 ret = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
347 release_print_db(pdb);
349 if (!ret.dptr) {
350 DEBUG(10,("print_job_find: failed to find jobid %u.\n", (unsigned int)jobid ));
351 return NULL;
354 if ( pjob.nt_devmode ) {
355 free_nt_devicemode( &pjob.nt_devmode );
358 ZERO_STRUCT( pjob );
360 if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
361 DEBUG(10,("print_job_find: failed to unpack jobid %u.\n", (unsigned int)jobid ));
362 SAFE_FREE(ret.dptr);
363 return NULL;
366 SAFE_FREE(ret.dptr);
368 DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
369 (int)pjob.sysjob, (unsigned int)jobid ));
371 return &pjob;
374 /* Convert a unix jobid to a smb jobid */
376 struct unixjob_traverse_state {
377 int sysjob;
378 uint32 sysjob_to_jobid_value;
381 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
382 TDB_DATA data, void *private_data)
384 struct printjob *pjob;
385 struct unixjob_traverse_state *state =
386 (struct unixjob_traverse_state *)private_data;
388 if (!data.dptr || data.dsize == 0)
389 return 0;
391 pjob = (struct printjob *)data.dptr;
392 if (key.dsize != sizeof(uint32))
393 return 0;
395 if (state->sysjob == pjob->sysjob) {
396 uint32 jobid = IVAL(key.dptr,0);
398 state->sysjob_to_jobid_value = jobid;
399 return 1;
402 return 0;
405 /****************************************************************************
406 This is a *horribly expensive call as we have to iterate through all the
407 current printer tdb's. Don't do this often ! JRA.
408 ****************************************************************************/
410 uint32 sysjob_to_jobid(int unix_jobid)
412 int services = lp_numservices();
413 int snum;
414 struct unixjob_traverse_state state;
416 state.sysjob = unix_jobid;
417 state.sysjob_to_jobid_value = (uint32)-1;
419 for (snum = 0; snum < services; snum++) {
420 struct tdb_print_db *pdb;
421 if (!lp_print_ok(snum))
422 continue;
423 pdb = get_print_db_byname(lp_const_servicename(snum));
424 if (!pdb) {
425 continue;
427 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
428 release_print_db(pdb);
429 if (state.sysjob_to_jobid_value != (uint32)-1)
430 return state.sysjob_to_jobid_value;
432 return (uint32)-1;
435 /****************************************************************************
436 Send notifications based on what has changed after a pjob_store.
437 ****************************************************************************/
439 static const struct {
440 uint32 lpq_status;
441 uint32 spoolss_status;
442 } lpq_to_spoolss_status_map[] = {
443 { LPQ_QUEUED, JOB_STATUS_QUEUED },
444 { LPQ_PAUSED, JOB_STATUS_PAUSED },
445 { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
446 { LPQ_PRINTING, JOB_STATUS_PRINTING },
447 { LPQ_DELETING, JOB_STATUS_DELETING },
448 { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
449 { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
450 { LPQ_PRINTED, JOB_STATUS_PRINTED },
451 { LPQ_DELETED, JOB_STATUS_DELETED },
452 { LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
453 { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
454 { -1, 0 }
457 /* Convert a lpq status value stored in printing.tdb into the
458 appropriate win32 API constant. */
460 static uint32 map_to_spoolss_status(uint32 lpq_status)
462 int i = 0;
464 while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
465 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
466 return lpq_to_spoolss_status_map[i].spoolss_status;
467 i++;
470 return 0;
473 static void pjob_store_notify(const char* sharename, uint32 jobid, struct printjob *old_data,
474 struct printjob *new_data)
476 bool new_job = False;
478 if (!old_data)
479 new_job = True;
481 /* Job attributes that can't be changed. We only send
482 notification for these on a new job. */
484 /* ACHTUNG! Due to a bug in Samba's spoolss parsing of the
485 NOTIFY_INFO_DATA buffer, we *have* to send the job submission
486 time first or else we'll end up with potential alignment
487 errors. I don't think the systemtime should be spooled as
488 a string, but this gets us around that error.
489 --jerry (i'll feel dirty for this) */
491 if (new_job) {
492 notify_job_submitted(sharename, jobid, new_data->starttime);
493 notify_job_username(sharename, jobid, new_data->user);
496 if (new_job || !strequal(old_data->jobname, new_data->jobname))
497 notify_job_name(sharename, jobid, new_data->jobname);
499 /* Job attributes of a new job or attributes that can be
500 modified. */
502 if (new_job || !strequal(old_data->jobname, new_data->jobname))
503 notify_job_name(sharename, jobid, new_data->jobname);
505 if (new_job || old_data->status != new_data->status)
506 notify_job_status(sharename, jobid, map_to_spoolss_status(new_data->status));
508 if (new_job || old_data->size != new_data->size)
509 notify_job_total_bytes(sharename, jobid, new_data->size);
511 if (new_job || old_data->page_count != new_data->page_count)
512 notify_job_total_pages(sharename, jobid, new_data->page_count);
515 /****************************************************************************
516 Store a job structure back to the database.
517 ****************************************************************************/
519 static bool pjob_store(const char* sharename, uint32 jobid, struct printjob *pjob)
521 uint32_t tmp;
522 TDB_DATA old_data, new_data;
523 bool ret = False;
524 struct tdb_print_db *pdb = get_print_db_byname(sharename);
525 uint8 *buf = NULL;
526 int len, newlen, buflen;
529 if (!pdb)
530 return False;
532 /* Get old data */
534 old_data = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
536 /* Doh! Now we have to pack/unpack data since the NT_DEVICEMODE was added */
538 newlen = 0;
540 do {
541 len = 0;
542 buflen = newlen;
543 len += tdb_pack(buf+len, buflen-len, "dddddddddffff",
544 (uint32)pjob->pid,
545 (uint32)pjob->sysjob,
546 (uint32)pjob->fd,
547 (uint32)pjob->starttime,
548 (uint32)pjob->status,
549 (uint32)pjob->size,
550 (uint32)pjob->page_count,
551 (uint32)pjob->spooled,
552 (uint32)pjob->smbjob,
553 pjob->filename,
554 pjob->jobname,
555 pjob->user,
556 pjob->queuename);
558 len += pack_devicemode(pjob->nt_devmode, buf+len, buflen-len);
560 if (buflen != len) {
561 buf = (uint8 *)SMB_REALLOC(buf, len);
562 if (!buf) {
563 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
564 goto done;
566 newlen = len;
568 } while ( buflen != len );
571 /* Store new data */
573 new_data.dptr = buf;
574 new_data.dsize = len;
575 ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
576 TDB_REPLACE) == 0);
578 release_print_db(pdb);
580 /* Send notify updates for what has changed */
582 if ( ret ) {
583 struct printjob old_pjob;
585 if ( old_data.dsize )
587 if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
589 pjob_store_notify( sharename, jobid, &old_pjob , pjob );
590 free_nt_devicemode( &old_pjob.nt_devmode );
593 else {
594 /* new job */
595 pjob_store_notify( sharename, jobid, NULL, pjob );
599 done:
600 SAFE_FREE( old_data.dptr );
601 SAFE_FREE( buf );
603 return ret;
606 /****************************************************************************
607 Remove a job structure from the database.
608 ****************************************************************************/
610 void pjob_delete(const char* sharename, uint32 jobid)
612 uint32_t tmp;
613 struct printjob *pjob;
614 uint32 job_status = 0;
615 struct tdb_print_db *pdb;
617 pdb = get_print_db_byname( sharename );
619 if (!pdb)
620 return;
622 pjob = print_job_find( sharename, jobid );
624 if (!pjob) {
625 DEBUG(5, ("pjob_delete: we were asked to delete nonexistent job %u\n",
626 (unsigned int)jobid));
627 release_print_db(pdb);
628 return;
631 /* We must cycle through JOB_STATUS_DELETING and
632 JOB_STATUS_DELETED for the port monitor to delete the job
633 properly. */
635 job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
636 notify_job_status(sharename, jobid, job_status);
638 /* Remove from printing.tdb */
640 tdb_delete(pdb->tdb, print_key(jobid, &tmp));
641 remove_from_jobs_changed(sharename, jobid);
642 release_print_db( pdb );
643 rap_jobid_delete(sharename, jobid);
646 /****************************************************************************
647 Parse a file name from the system spooler to generate a jobid.
648 ****************************************************************************/
650 static uint32 print_parse_jobid(char *fname)
652 int jobid;
654 if (strncmp(fname,PRINT_SPOOL_PREFIX,strlen(PRINT_SPOOL_PREFIX)) != 0)
655 return (uint32)-1;
656 fname += strlen(PRINT_SPOOL_PREFIX);
658 jobid = atoi(fname);
659 if (jobid <= 0)
660 return (uint32)-1;
662 return (uint32)jobid;
665 /****************************************************************************
666 List a unix job in the print database.
667 ****************************************************************************/
669 static void print_unix_job(const char *sharename, print_queue_struct *q, uint32 jobid)
671 struct printjob pj, *old_pj;
673 if (jobid == (uint32)-1)
674 jobid = q->job + UNIX_JOB_START;
676 /* Preserve the timestamp on an existing unix print job */
678 old_pj = print_job_find(sharename, jobid);
680 ZERO_STRUCT(pj);
682 pj.pid = (pid_t)-1;
683 pj.sysjob = q->job;
684 pj.fd = -1;
685 pj.starttime = old_pj ? old_pj->starttime : q->time;
686 pj.status = q->status;
687 pj.size = q->size;
688 pj.spooled = True;
689 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
690 if (jobid < UNIX_JOB_START) {
691 pj.smbjob = True;
692 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
693 } else {
694 pj.smbjob = False;
695 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
697 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
698 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
700 pjob_store(sharename, jobid, &pj);
704 struct traverse_struct {
705 print_queue_struct *queue;
706 int qcount, snum, maxcount, total_jobs;
707 const char *sharename;
708 time_t lpq_time;
709 const char *lprm_command;
710 struct printif *print_if;
713 /****************************************************************************
714 Utility fn to delete any jobs that are no longer active.
715 ****************************************************************************/
717 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
719 struct traverse_struct *ts = (struct traverse_struct *)state;
720 struct printjob pjob;
721 uint32 jobid;
722 int i = 0;
724 if ( key.dsize != sizeof(jobid) )
725 return 0;
727 jobid = IVAL(key.dptr, 0);
728 if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
729 return 0;
730 free_nt_devicemode( &pjob.nt_devmode );
733 if (!pjob.smbjob) {
734 /* remove a unix job if it isn't in the system queue any more */
736 for (i=0;i<ts->qcount;i++) {
737 uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
738 if (jobid == u_jobid)
739 break;
741 if (i == ts->qcount) {
742 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
743 (unsigned int)jobid ));
744 pjob_delete(ts->sharename, jobid);
745 return 0;
748 /* need to continue the the bottom of the function to
749 save the correct attributes */
752 /* maybe it hasn't been spooled yet */
753 if (!pjob.spooled) {
754 /* if a job is not spooled and the process doesn't
755 exist then kill it. This cleans up after smbd
756 deaths */
757 if (!process_exists_by_pid(pjob.pid)) {
758 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
759 (unsigned int)jobid, (unsigned int)pjob.pid ));
760 pjob_delete(ts->sharename, jobid);
761 } else
762 ts->total_jobs++;
763 return 0;
766 /* this check only makes sense for jobs submitted from Windows clients */
768 if ( pjob.smbjob ) {
769 for (i=0;i<ts->qcount;i++) {
770 uint32 curr_jobid;
772 if ( pjob.status == LPQ_DELETED )
773 continue;
775 curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
777 if (jobid == curr_jobid) {
779 /* try to clean up any jobs that need to be deleted */
781 if ( pjob.status == LPQ_DELETING ) {
782 int result;
784 result = (*(ts->print_if->job_delete))(
785 ts->sharename, ts->lprm_command, &pjob );
787 if ( result != 0 ) {
788 /* if we can't delete, then reset the job status */
789 pjob.status = LPQ_QUEUED;
790 pjob_store(ts->sharename, jobid, &pjob);
792 else {
793 /* if we deleted the job, the remove the tdb record */
794 pjob_delete(ts->sharename, jobid);
795 pjob.status = LPQ_DELETED;
800 break;
805 /* The job isn't in the system queue - we have to assume it has
806 completed, so delete the database entry. */
808 if (i == ts->qcount) {
810 /* A race can occur between the time a job is spooled and
811 when it appears in the lpq output. This happens when
812 the job is added to printing.tdb when another smbd
813 running print_queue_update() has completed a lpq and
814 is currently traversing the printing tdb and deleting jobs.
815 Don't delete the job if it was submitted after the lpq_time. */
817 if (pjob.starttime < ts->lpq_time) {
818 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
819 (unsigned int)jobid,
820 (unsigned int)pjob.starttime,
821 (unsigned int)ts->lpq_time ));
822 pjob_delete(ts->sharename, jobid);
823 } else
824 ts->total_jobs++;
825 return 0;
828 /* Save the pjob attributes we will store.
829 FIXME!!! This is the only place where queue->job
830 represents the SMB jobid --jerry */
832 ts->queue[i].job = jobid;
833 ts->queue[i].size = pjob.size;
834 ts->queue[i].page_count = pjob.page_count;
835 ts->queue[i].status = pjob.status;
836 ts->queue[i].priority = 1;
837 ts->queue[i].time = pjob.starttime;
838 fstrcpy(ts->queue[i].fs_user, pjob.user);
839 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
841 ts->total_jobs++;
843 return 0;
846 /****************************************************************************
847 Check if the print queue has been updated recently enough.
848 ****************************************************************************/
850 static void print_cache_flush(const char *sharename)
852 fstring key;
853 struct tdb_print_db *pdb = get_print_db_byname(sharename);
855 if (!pdb)
856 return;
857 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
858 tdb_store_int32(pdb->tdb, key, -1);
859 release_print_db(pdb);
862 /****************************************************************************
863 Check if someone already thinks they are doing the update.
864 ****************************************************************************/
866 static pid_t get_updating_pid(const char *sharename)
868 fstring keystr;
869 TDB_DATA data, key;
870 pid_t updating_pid;
871 struct tdb_print_db *pdb = get_print_db_byname(sharename);
873 if (!pdb)
874 return (pid_t)-1;
875 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
876 key = string_tdb_data(keystr);
878 data = tdb_fetch(pdb->tdb, key);
879 release_print_db(pdb);
880 if (!data.dptr || data.dsize != sizeof(pid_t)) {
881 SAFE_FREE(data.dptr);
882 return (pid_t)-1;
885 updating_pid = IVAL(data.dptr, 0);
886 SAFE_FREE(data.dptr);
888 if (process_exists_by_pid(updating_pid))
889 return updating_pid;
891 return (pid_t)-1;
894 /****************************************************************************
895 Set the fact that we're doing the update, or have finished doing the update
896 in the tdb.
897 ****************************************************************************/
899 static void set_updating_pid(const fstring sharename, bool updating)
901 fstring keystr;
902 TDB_DATA key;
903 TDB_DATA data;
904 pid_t updating_pid = sys_getpid();
905 uint8 buffer[4];
907 struct tdb_print_db *pdb = get_print_db_byname(sharename);
909 if (!pdb)
910 return;
912 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
913 key = string_tdb_data(keystr);
915 DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
916 updating ? "" : "not ",
917 sharename ));
919 if ( !updating ) {
920 tdb_delete(pdb->tdb, key);
921 release_print_db(pdb);
922 return;
925 SIVAL( buffer, 0, updating_pid);
926 data.dptr = buffer;
927 data.dsize = 4; /* we always assume this is a 4 byte value */
929 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
930 release_print_db(pdb);
933 /****************************************************************************
934 Sort print jobs by submittal time.
935 ****************************************************************************/
937 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
939 /* Silly cases */
941 if (!j1 && !j2)
942 return 0;
943 if (!j1)
944 return -1;
945 if (!j2)
946 return 1;
948 /* Sort on job start time */
950 if (j1->time == j2->time)
951 return 0;
952 return (j1->time > j2->time) ? 1 : -1;
955 /****************************************************************************
956 Store the sorted queue representation for later portmon retrieval.
957 Skip deleted jobs
958 ****************************************************************************/
960 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
962 TDB_DATA data;
963 int max_reported_jobs = lp_max_reported_jobs(pts->snum);
964 print_queue_struct *queue = pts->queue;
965 size_t len;
966 size_t i;
967 unsigned int qcount;
969 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
970 pts->qcount = max_reported_jobs;
971 qcount = 0;
973 /* Work out the size. */
974 data.dsize = 0;
975 data.dsize += tdb_pack(NULL, 0, "d", qcount);
977 for (i = 0; i < pts->qcount; i++) {
978 if ( queue[i].status == LPQ_DELETED )
979 continue;
981 qcount++;
982 data.dsize += tdb_pack(NULL, 0, "ddddddff",
983 (uint32)queue[i].job,
984 (uint32)queue[i].size,
985 (uint32)queue[i].page_count,
986 (uint32)queue[i].status,
987 (uint32)queue[i].priority,
988 (uint32)queue[i].time,
989 queue[i].fs_user,
990 queue[i].fs_file);
993 if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
994 return;
996 len = 0;
997 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
998 for (i = 0; i < pts->qcount; i++) {
999 if ( queue[i].status == LPQ_DELETED )
1000 continue;
1002 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
1003 (uint32)queue[i].job,
1004 (uint32)queue[i].size,
1005 (uint32)queue[i].page_count,
1006 (uint32)queue[i].status,
1007 (uint32)queue[i].priority,
1008 (uint32)queue[i].time,
1009 queue[i].fs_user,
1010 queue[i].fs_file);
1013 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
1014 TDB_REPLACE);
1015 SAFE_FREE(data.dptr);
1016 return;
1019 static TDB_DATA get_jobs_changed_data(struct tdb_print_db *pdb)
1021 TDB_DATA data;
1023 ZERO_STRUCT(data);
1025 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
1026 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1027 SAFE_FREE(data.dptr);
1028 ZERO_STRUCT(data);
1031 return data;
1034 static void check_job_changed(const char *sharename, TDB_DATA data, uint32 jobid)
1036 unsigned int i;
1037 unsigned int job_count = data.dsize / 4;
1039 for (i = 0; i < job_count; i++) {
1040 uint32 ch_jobid;
1042 ch_jobid = IVAL(data.dptr, i*4);
1043 if (ch_jobid == jobid)
1044 remove_from_jobs_changed(sharename, jobid);
1048 /****************************************************************************
1049 Check if the print queue has been updated recently enough.
1050 ****************************************************************************/
1052 static bool print_cache_expired(const char *sharename, bool check_pending)
1054 fstring key;
1055 time_t last_qscan_time, time_now = time(NULL);
1056 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1057 bool result = False;
1059 if (!pdb)
1060 return False;
1062 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1063 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1066 * Invalidate the queue for 3 reasons.
1067 * (1). last queue scan time == -1.
1068 * (2). Current time - last queue scan time > allowed cache time.
1069 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1070 * This last test picks up machines for which the clock has been moved
1071 * forward, an lpq scan done and then the clock moved back. Otherwise
1072 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1075 if (last_qscan_time == ((time_t)-1)
1076 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1077 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1079 uint32 u;
1080 time_t msg_pending_time;
1082 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1083 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1084 sharename, (int)last_qscan_time, (int)time_now,
1085 (int)lp_lpqcachetime() ));
1087 /* check if another smbd has already sent a message to update the
1088 queue. Give the pending message one minute to clear and
1089 then send another message anyways. Make sure to check for
1090 clocks that have been run forward and then back again. */
1092 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1094 if ( check_pending
1095 && tdb_fetch_uint32( pdb->tdb, key, &u )
1096 && (msg_pending_time=u) > 0
1097 && msg_pending_time <= time_now
1098 && (time_now - msg_pending_time) < 60 )
1100 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1101 sharename));
1102 goto done;
1105 result = True;
1108 done:
1109 release_print_db(pdb);
1110 return result;
1113 /****************************************************************************
1114 main work for updating the lpq cahe for a printer queue
1115 ****************************************************************************/
1117 static void print_queue_update_internal( const char *sharename,
1118 struct printif *current_printif,
1119 char *lpq_command, char *lprm_command )
1121 int i, qcount;
1122 print_queue_struct *queue = NULL;
1123 print_status_struct status;
1124 print_status_struct old_status;
1125 struct printjob *pjob;
1126 struct traverse_struct tstruct;
1127 TDB_DATA data, key;
1128 TDB_DATA jcdata;
1129 fstring keystr, cachestr;
1130 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1132 if (!pdb) {
1133 return;
1136 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1137 sharename, current_printif->type, lpq_command));
1140 * Update the cache time FIRST ! Stops others even
1141 * attempting to get the lock and doing this
1142 * if the lpq takes a long time.
1145 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1146 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1148 /* get the current queue using the appropriate interface */
1149 ZERO_STRUCT(status);
1151 qcount = (*(current_printif->queue_get))(sharename,
1152 current_printif->type,
1153 lpq_command, &queue, &status);
1155 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1156 qcount, (qcount != 1) ? "s" : "", sharename));
1158 /* Sort the queue by submission time otherwise they are displayed
1159 in hash order. */
1161 qsort(queue, qcount, sizeof(print_queue_struct),
1162 QSORT_CAST(printjob_comp));
1165 any job in the internal database that is marked as spooled
1166 and doesn't exist in the system queue is considered finished
1167 and removed from the database
1169 any job in the system database but not in the internal database
1170 is added as a unix job
1172 fill in any system job numbers as we go
1175 jcdata = get_jobs_changed_data(pdb);
1177 for (i=0; i<qcount; i++) {
1178 uint32 jobid = print_parse_jobid(queue[i].fs_file);
1180 if (jobid == (uint32)-1) {
1181 /* assume its a unix print job */
1182 print_unix_job(sharename, &queue[i], jobid);
1183 continue;
1186 /* we have an active SMB print job - update its status */
1187 pjob = print_job_find(sharename, jobid);
1188 if (!pjob) {
1189 /* err, somethings wrong. Probably smbd was restarted
1190 with jobs in the queue. All we can do is treat them
1191 like unix jobs. Pity. */
1192 print_unix_job(sharename, &queue[i], jobid);
1193 continue;
1196 pjob->sysjob = queue[i].job;
1198 /* don't reset the status on jobs to be deleted */
1200 if ( pjob->status != LPQ_DELETING )
1201 pjob->status = queue[i].status;
1203 pjob_store(sharename, jobid, pjob);
1205 check_job_changed(sharename, jcdata, jobid);
1208 SAFE_FREE(jcdata.dptr);
1210 /* now delete any queued entries that don't appear in the
1211 system queue */
1212 tstruct.queue = queue;
1213 tstruct.qcount = qcount;
1214 tstruct.snum = -1;
1215 tstruct.total_jobs = 0;
1216 tstruct.lpq_time = time(NULL);
1217 tstruct.sharename = sharename;
1218 tstruct.lprm_command = lprm_command;
1219 tstruct.print_if = current_printif;
1221 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1223 /* Store the linearised queue, max jobs only. */
1224 store_queue_struct(pdb, &tstruct);
1226 SAFE_FREE(tstruct.queue);
1228 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1229 sharename, tstruct.total_jobs ));
1231 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1233 get_queue_status(sharename, &old_status);
1234 if (old_status.qcount != qcount)
1235 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1236 old_status.qcount, qcount, sharename));
1238 /* store the new queue status structure */
1239 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1240 key = string_tdb_data(keystr);
1242 status.qcount = qcount;
1243 data.dptr = (uint8 *)&status;
1244 data.dsize = sizeof(status);
1245 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1248 * Update the cache time again. We want to do this call
1249 * as little as possible...
1252 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1253 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1255 /* clear the msg pending record for this queue */
1257 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1259 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1260 /* log a message but continue on */
1262 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1263 sharename));
1266 release_print_db( pdb );
1268 return;
1271 /****************************************************************************
1272 Update the internal database from the system print queue for a queue.
1273 obtain a lock on the print queue before proceeding (needed when mutiple
1274 smbd processes maytry to update the lpq cache concurrently).
1275 ****************************************************************************/
1277 static void print_queue_update_with_lock( const char *sharename,
1278 struct printif *current_printif,
1279 char *lpq_command, char *lprm_command )
1281 fstring keystr;
1282 struct tdb_print_db *pdb;
1284 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1285 pdb = get_print_db_byname(sharename);
1286 if (!pdb)
1287 return;
1289 if ( !print_cache_expired(sharename, False) ) {
1290 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1291 release_print_db(pdb);
1292 return;
1296 * Check to see if someone else is doing this update.
1297 * This is essentially a mutex on the update.
1300 if (get_updating_pid(sharename) != -1) {
1301 release_print_db(pdb);
1302 return;
1305 /* Lock the queue for the database update */
1307 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1308 /* Only wait 10 seconds for this. */
1309 if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) == -1) {
1310 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1311 release_print_db(pdb);
1312 return;
1316 * Ensure that no one else got in here.
1317 * If the updating pid is still -1 then we are
1318 * the winner.
1321 if (get_updating_pid(sharename) != -1) {
1323 * Someone else is doing the update, exit.
1325 tdb_unlock_bystring(pdb->tdb, keystr);
1326 release_print_db(pdb);
1327 return;
1331 * We're going to do the update ourselves.
1334 /* Tell others we're doing the update. */
1335 set_updating_pid(sharename, True);
1338 * Allow others to enter and notice we're doing
1339 * the update.
1342 tdb_unlock_bystring(pdb->tdb, keystr);
1344 /* do the main work now */
1346 print_queue_update_internal( sharename, current_printif,
1347 lpq_command, lprm_command );
1349 /* Delete our pid from the db. */
1350 set_updating_pid(sharename, False);
1351 release_print_db(pdb);
1354 /****************************************************************************
1355 this is the receive function of the background lpq updater
1356 ****************************************************************************/
1357 static void print_queue_receive(struct messaging_context *msg,
1358 void *private_data,
1359 uint32_t msg_type,
1360 struct server_id server_id,
1361 DATA_BLOB *data)
1363 fstring sharename;
1364 char *lpqcommand = NULL, *lprmcommand = NULL;
1365 int printing_type;
1366 size_t len;
1368 len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1369 sharename,
1370 &printing_type,
1371 &lpqcommand,
1372 &lprmcommand );
1374 if ( len == -1 ) {
1375 SAFE_FREE(lpqcommand);
1376 SAFE_FREE(lprmcommand);
1377 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1378 return;
1381 print_queue_update_with_lock(sharename,
1382 get_printer_fns_from_type((enum printing_types)printing_type),
1383 lpqcommand, lprmcommand );
1385 SAFE_FREE(lpqcommand);
1386 SAFE_FREE(lprmcommand);
1387 return;
1390 static pid_t background_lpq_updater_pid = -1;
1392 /****************************************************************************
1393 main thread of the background lpq updater
1394 ****************************************************************************/
1395 void start_background_queue(void)
1397 /* Use local variables for this as we don't
1398 * need to save the parent side of this, just
1399 * ensure it closes when the process exits.
1401 int pause_pipe[2];
1403 DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
1405 if (pipe(pause_pipe) == -1) {
1406 DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
1407 exit(1);
1410 background_lpq_updater_pid = sys_fork();
1412 if (background_lpq_updater_pid == -1) {
1413 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
1414 exit(1);
1417 if(background_lpq_updater_pid == 0) {
1418 /* Child. */
1419 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
1421 close(pause_pipe[0]);
1422 pause_pipe[0] = -1;
1424 if (!reinit_after_fork(smbd_messaging_context(),
1425 smbd_event_context(), true)) {
1426 DEBUG(0,("reinit_after_fork() failed\n"));
1427 smb_panic("reinit_after_fork() failed");
1430 smbd_setup_sig_term_handler();
1431 smbd_setup_sig_hup_handler();
1433 claim_connection( NULL, "smbd lpq backend",
1434 FLAG_MSG_GENERAL|FLAG_MSG_SMBD|FLAG_MSG_PRINT_GENERAL);
1436 if (!locking_init()) {
1437 exit(1);
1440 messaging_register(smbd_messaging_context(), NULL,
1441 MSG_PRINTER_UPDATE, print_queue_receive);
1443 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
1444 while (1) {
1445 fd_set r_fds, w_fds;
1446 int ret;
1447 struct timeval to;
1448 int maxfd = 0;
1450 /* Process a signal and timed events now... */
1451 if (run_events(smbd_event_context(), 0, NULL, NULL)) {
1452 continue;
1455 to.tv_sec = SMBD_SELECT_TIMEOUT;
1456 to.tv_usec = 0;
1459 * Setup the select fd sets.
1462 FD_ZERO(&r_fds);
1463 FD_ZERO(&w_fds);
1466 * Are there any timed events waiting ? If so, ensure we don't
1467 * select for longer than it would take to wait for them.
1471 struct timeval now;
1472 GetTimeOfDay(&now);
1474 event_add_to_select_args(smbd_event_context(), &now,
1475 &r_fds, &w_fds, &to, &maxfd);
1478 FD_SET(pause_pipe[1], &r_fds);
1479 maxfd = MAX(pause_pipe[1], maxfd);
1481 ret = sys_select(maxfd, &r_fds, &w_fds, NULL, &to);
1484 * If pause_pipe[1] is closed it means the parent smbd
1485 * and children exited or aborted. If sys_select()
1486 * failed, then something more sinister is wrong
1488 if ((ret < 0) ||
1489 (ret == 1 && FD_ISSET(pause_pipe[1], &r_fds))) {
1490 exit_server_cleanly(NULL);
1493 if (run_events(smbd_event_context(), ret, &r_fds, &w_fds)) {
1494 continue;
1499 close(pause_pipe[1]);
1502 /****************************************************************************
1503 update the internal database from the system print queue for a queue
1504 ****************************************************************************/
1506 static void print_queue_update(int snum, bool force)
1508 fstring key;
1509 fstring sharename;
1510 char *lpqcommand = NULL;
1511 char *lprmcommand = NULL;
1512 uint8 *buffer = NULL;
1513 size_t len = 0;
1514 size_t newlen;
1515 struct tdb_print_db *pdb;
1516 int type;
1517 struct printif *current_printif;
1518 TALLOC_CTX *ctx = talloc_tos();
1520 fstrcpy( sharename, lp_const_servicename(snum));
1522 /* don't strip out characters like '$' from the printername */
1524 lpqcommand = talloc_string_sub2(ctx,
1525 lp_lpqcommand(snum),
1526 "%p",
1527 PRINTERNAME(snum),
1528 false, false, false);
1529 if (!lpqcommand) {
1530 return;
1532 lpqcommand = talloc_sub_advanced(ctx,
1533 lp_servicename(snum),
1534 current_user_info.unix_name,
1536 current_user.ut.gid,
1537 get_current_username(),
1538 current_user_info.domain,
1539 lpqcommand);
1540 if (!lpqcommand) {
1541 return;
1544 lprmcommand = talloc_string_sub2(ctx,
1545 lp_lprmcommand(snum),
1546 "%p",
1547 PRINTERNAME(snum),
1548 false, false, false);
1549 if (!lprmcommand) {
1550 return;
1552 lprmcommand = talloc_sub_advanced(ctx,
1553 lp_servicename(snum),
1554 current_user_info.unix_name,
1556 current_user.ut.gid,
1557 get_current_username(),
1558 current_user_info.domain,
1559 lprmcommand);
1560 if (!lprmcommand) {
1561 return;
1565 * Make sure that the background queue process exists.
1566 * Otherwise just do the update ourselves
1569 if ( force || background_lpq_updater_pid == -1 ) {
1570 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1571 current_printif = get_printer_fns( snum );
1572 print_queue_update_with_lock( sharename, current_printif, lpqcommand, lprmcommand );
1574 return;
1577 type = lp_printing(snum);
1579 /* get the length */
1581 len = tdb_pack( NULL, 0, "fdPP",
1582 sharename,
1583 type,
1584 lpqcommand,
1585 lprmcommand );
1587 buffer = SMB_XMALLOC_ARRAY( uint8, len );
1589 /* now pack the buffer */
1590 newlen = tdb_pack( buffer, len, "fdPP",
1591 sharename,
1592 type,
1593 lpqcommand,
1594 lprmcommand );
1596 SMB_ASSERT( newlen == len );
1598 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1599 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1600 sharename, type, lpqcommand, lprmcommand ));
1602 /* here we set a msg pending record for other smbd processes
1603 to throttle the number of duplicate print_queue_update msgs
1604 sent. */
1606 pdb = get_print_db_byname(sharename);
1607 if (!pdb) {
1608 SAFE_FREE(buffer);
1609 return;
1612 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1614 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1615 /* log a message but continue on */
1617 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1618 sharename));
1621 release_print_db( pdb );
1623 /* finally send the message */
1625 messaging_send_buf(smbd_messaging_context(),
1626 pid_to_procid(background_lpq_updater_pid),
1627 MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1629 SAFE_FREE( buffer );
1631 return;
1634 /****************************************************************************
1635 Create/Update an entry in the print tdb that will allow us to send notify
1636 updates only to interested smbd's.
1637 ****************************************************************************/
1639 bool print_notify_register_pid(int snum)
1641 TDB_DATA data;
1642 struct tdb_print_db *pdb = NULL;
1643 TDB_CONTEXT *tdb = NULL;
1644 const char *printername;
1645 uint32 mypid = (uint32)sys_getpid();
1646 bool ret = False;
1647 size_t i;
1649 /* if (snum == -1), then the change notify request was
1650 on a print server handle and we need to register on
1651 all print queus */
1653 if (snum == -1)
1655 int num_services = lp_numservices();
1656 int idx;
1658 for ( idx=0; idx<num_services; idx++ ) {
1659 if (lp_snum_ok(idx) && lp_print_ok(idx) )
1660 print_notify_register_pid(idx);
1663 return True;
1665 else /* register for a specific printer */
1667 printername = lp_const_servicename(snum);
1668 pdb = get_print_db_byname(printername);
1669 if (!pdb)
1670 return False;
1671 tdb = pdb->tdb;
1674 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1675 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1676 printername));
1677 if (pdb)
1678 release_print_db(pdb);
1679 return False;
1682 data = get_printer_notify_pid_list( tdb, printername, True );
1684 /* Add ourselves and increase the refcount. */
1686 for (i = 0; i < data.dsize; i += 8) {
1687 if (IVAL(data.dptr,i) == mypid) {
1688 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1689 SIVAL(data.dptr, i+4, new_refcount);
1690 break;
1694 if (i == data.dsize) {
1695 /* We weren't in the list. Realloc. */
1696 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1697 if (!data.dptr) {
1698 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1699 printername));
1700 goto done;
1702 data.dsize += 8;
1703 SIVAL(data.dptr,data.dsize - 8,mypid);
1704 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1707 /* Store back the record. */
1708 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1709 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1710 list for printer %s\n", printername));
1711 goto done;
1714 ret = True;
1716 done:
1718 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1719 if (pdb)
1720 release_print_db(pdb);
1721 SAFE_FREE(data.dptr);
1722 return ret;
1725 /****************************************************************************
1726 Update an entry in the print tdb that will allow us to send notify
1727 updates only to interested smbd's.
1728 ****************************************************************************/
1730 bool print_notify_deregister_pid(int snum)
1732 TDB_DATA data;
1733 struct tdb_print_db *pdb = NULL;
1734 TDB_CONTEXT *tdb = NULL;
1735 const char *printername;
1736 uint32 mypid = (uint32)sys_getpid();
1737 size_t i;
1738 bool ret = False;
1740 /* if ( snum == -1 ), we are deregister a print server handle
1741 which means to deregister on all print queues */
1743 if (snum == -1)
1745 int num_services = lp_numservices();
1746 int idx;
1748 for ( idx=0; idx<num_services; idx++ ) {
1749 if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1750 print_notify_deregister_pid(idx);
1753 return True;
1755 else /* deregister a specific printer */
1757 printername = lp_const_servicename(snum);
1758 pdb = get_print_db_byname(printername);
1759 if (!pdb)
1760 return False;
1761 tdb = pdb->tdb;
1764 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1765 DEBUG(0,("print_notify_register_pid: Failed to lock \
1766 printer %s database\n", printername));
1767 if (pdb)
1768 release_print_db(pdb);
1769 return False;
1772 data = get_printer_notify_pid_list( tdb, printername, True );
1774 /* Reduce refcount. Remove ourselves if zero. */
1776 for (i = 0; i < data.dsize; ) {
1777 if (IVAL(data.dptr,i) == mypid) {
1778 uint32 refcount = IVAL(data.dptr, i+4);
1780 refcount--;
1782 if (refcount == 0) {
1783 if (data.dsize - i > 8)
1784 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1785 data.dsize -= 8;
1786 continue;
1788 SIVAL(data.dptr, i+4, refcount);
1791 i += 8;
1794 if (data.dsize == 0)
1795 SAFE_FREE(data.dptr);
1797 /* Store back the record. */
1798 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1799 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1800 list for printer %s\n", printername));
1801 goto done;
1804 ret = True;
1806 done:
1808 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1809 if (pdb)
1810 release_print_db(pdb);
1811 SAFE_FREE(data.dptr);
1812 return ret;
1815 /****************************************************************************
1816 Check if a jobid is valid. It is valid if it exists in the database.
1817 ****************************************************************************/
1819 bool print_job_exists(const char* sharename, uint32 jobid)
1821 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1822 bool ret;
1823 uint32_t tmp;
1825 if (!pdb)
1826 return False;
1827 ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
1828 release_print_db(pdb);
1829 return ret;
1832 /****************************************************************************
1833 Give the fd used for a jobid.
1834 ****************************************************************************/
1836 int print_job_fd(const char* sharename, uint32 jobid)
1838 struct printjob *pjob = print_job_find(sharename, jobid);
1839 if (!pjob)
1840 return -1;
1841 /* don't allow another process to get this info - it is meaningless */
1842 if (pjob->pid != sys_getpid())
1843 return -1;
1844 return pjob->fd;
1847 /****************************************************************************
1848 Give the filename used for a jobid.
1849 Only valid for the process doing the spooling and when the job
1850 has not been spooled.
1851 ****************************************************************************/
1853 char *print_job_fname(const char* sharename, uint32 jobid)
1855 struct printjob *pjob = print_job_find(sharename, jobid);
1856 if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
1857 return NULL;
1858 return pjob->filename;
1862 /****************************************************************************
1863 Give the filename used for a jobid.
1864 Only valid for the process doing the spooling and when the job
1865 has not been spooled.
1866 ****************************************************************************/
1868 NT_DEVICEMODE *print_job_devmode(const char* sharename, uint32 jobid)
1870 struct printjob *pjob = print_job_find(sharename, jobid);
1872 if ( !pjob )
1873 return NULL;
1875 return pjob->nt_devmode;
1878 /****************************************************************************
1879 Set the place in the queue for a job.
1880 ****************************************************************************/
1882 bool print_job_set_place(const char *sharename, uint32 jobid, int place)
1884 DEBUG(2,("print_job_set_place not implemented yet\n"));
1885 return False;
1888 /****************************************************************************
1889 Set the name of a job. Only possible for owner.
1890 ****************************************************************************/
1892 bool print_job_set_name(const char *sharename, uint32 jobid, char *name)
1894 struct printjob *pjob;
1896 pjob = print_job_find(sharename, jobid);
1897 if (!pjob || pjob->pid != sys_getpid())
1898 return False;
1900 fstrcpy(pjob->jobname, name);
1901 return pjob_store(sharename, jobid, pjob);
1904 /***************************************************************************
1905 Remove a jobid from the 'jobs changed' list.
1906 ***************************************************************************/
1908 static bool remove_from_jobs_changed(const char* sharename, uint32 jobid)
1910 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1911 TDB_DATA data, key;
1912 size_t job_count, i;
1913 bool ret = False;
1914 bool gotlock = False;
1916 if (!pdb) {
1917 return False;
1920 ZERO_STRUCT(data);
1922 key = string_tdb_data("INFO/jobs_changed");
1924 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
1925 goto out;
1927 gotlock = True;
1929 data = tdb_fetch(pdb->tdb, key);
1931 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
1932 goto out;
1934 job_count = data.dsize / 4;
1935 for (i = 0; i < job_count; i++) {
1936 uint32 ch_jobid;
1938 ch_jobid = IVAL(data.dptr, i*4);
1939 if (ch_jobid == jobid) {
1940 if (i < job_count -1 )
1941 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
1942 data.dsize -= 4;
1943 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
1944 goto out;
1945 break;
1949 ret = True;
1950 out:
1952 if (gotlock)
1953 tdb_chainunlock(pdb->tdb, key);
1954 SAFE_FREE(data.dptr);
1955 release_print_db(pdb);
1956 if (ret)
1957 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
1958 else
1959 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
1960 return ret;
1963 /****************************************************************************
1964 Delete a print job - don't update queue.
1965 ****************************************************************************/
1967 static bool print_job_delete1(int snum, uint32 jobid)
1969 const char* sharename = lp_const_servicename(snum);
1970 struct printjob *pjob = print_job_find(sharename, jobid);
1971 int result = 0;
1972 struct printif *current_printif = get_printer_fns( snum );
1974 if (!pjob)
1975 return False;
1978 * If already deleting just return.
1981 if (pjob->status == LPQ_DELETING)
1982 return True;
1984 /* Hrm - we need to be able to cope with deleting a job before it
1985 has reached the spooler. Just mark it as LPQ_DELETING and
1986 let the print_queue_update() code rmeove the record */
1989 if (pjob->sysjob == -1) {
1990 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
1993 /* Set the tdb entry to be deleting. */
1995 pjob->status = LPQ_DELETING;
1996 pjob_store(sharename, jobid, pjob);
1998 if (pjob->spooled && pjob->sysjob != -1)
2000 result = (*(current_printif->job_delete))(
2001 PRINTERNAME(snum),
2002 lp_lprmcommand(snum),
2003 pjob);
2005 /* Delete the tdb entry if the delete succeeded or the job hasn't
2006 been spooled. */
2008 if (result == 0) {
2009 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2010 int njobs = 1;
2012 if (!pdb)
2013 return False;
2014 pjob_delete(sharename, jobid);
2015 /* Ensure we keep a rough count of the number of total jobs... */
2016 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
2017 release_print_db(pdb);
2021 remove_from_jobs_changed( sharename, jobid );
2023 return (result == 0);
2026 /****************************************************************************
2027 Return true if the current user owns the print job.
2028 ****************************************************************************/
2030 static bool is_owner(struct auth_serversupplied_info *server_info,
2031 const char *servicename,
2032 uint32 jobid)
2034 struct printjob *pjob = print_job_find(servicename, jobid);
2036 if (!pjob || !server_info)
2037 return False;
2039 return strequal(pjob->user, server_info->sanitized_username);
2042 /****************************************************************************
2043 Delete a print job.
2044 ****************************************************************************/
2046 bool print_job_delete(struct auth_serversupplied_info *server_info, int snum,
2047 uint32 jobid, WERROR *errcode)
2049 const char* sharename = lp_const_servicename( snum );
2050 struct printjob *pjob;
2051 bool owner;
2052 char *fname;
2054 *errcode = WERR_OK;
2056 owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2058 /* Check access against security descriptor or whether the user
2059 owns their job. */
2061 if (!owner &&
2062 !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2063 DEBUG(3, ("delete denied by security descriptor\n"));
2064 *errcode = WERR_ACCESS_DENIED;
2066 /* BEGIN_ADMIN_LOG */
2067 sys_adminlog( LOG_ERR,
2068 "Permission denied-- user not allowed to delete, \
2069 pause, or resume print job. User name: %s. Printer name: %s.",
2070 uidtoname(server_info->utok.uid),
2071 PRINTERNAME(snum) );
2072 /* END_ADMIN_LOG */
2074 return False;
2078 * get the spooled filename of the print job
2079 * if this works, then the file has not been spooled
2080 * to the underlying print system. Just delete the
2081 * spool file & return.
2084 if ( (fname = print_job_fname( sharename, jobid )) != NULL )
2086 /* remove the spool file */
2087 DEBUG(10,("print_job_delete: Removing spool file [%s]\n", fname ));
2088 if ( unlink( fname ) == -1 ) {
2089 *errcode = map_werror_from_unix(errno);
2090 return False;
2094 if (!print_job_delete1(snum, jobid)) {
2095 *errcode = WERR_ACCESS_DENIED;
2096 return False;
2099 /* force update the database and say the delete failed if the
2100 job still exists */
2102 print_queue_update(snum, True);
2104 pjob = print_job_find(sharename, jobid);
2105 if ( pjob && (pjob->status != LPQ_DELETING) )
2106 *errcode = WERR_ACCESS_DENIED;
2108 return (pjob == NULL );
2111 /****************************************************************************
2112 Pause a job.
2113 ****************************************************************************/
2115 bool print_job_pause(struct auth_serversupplied_info *server_info, int snum,
2116 uint32 jobid, WERROR *errcode)
2118 const char* sharename = lp_const_servicename(snum);
2119 struct printjob *pjob;
2120 int ret = -1;
2121 struct printif *current_printif = get_printer_fns( snum );
2123 pjob = print_job_find(sharename, jobid);
2125 if (!pjob || !server_info) {
2126 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2127 (unsigned int)jobid ));
2128 return False;
2131 if (!pjob->spooled || pjob->sysjob == -1) {
2132 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2133 (int)pjob->sysjob, (unsigned int)jobid ));
2134 return False;
2137 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2138 !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2139 DEBUG(3, ("pause denied by security descriptor\n"));
2141 /* BEGIN_ADMIN_LOG */
2142 sys_adminlog( LOG_ERR,
2143 "Permission denied-- user not allowed to delete, \
2144 pause, or resume print job. User name: %s. Printer name: %s.",
2145 uidtoname(server_info->utok.uid),
2146 PRINTERNAME(snum) );
2147 /* END_ADMIN_LOG */
2149 *errcode = WERR_ACCESS_DENIED;
2150 return False;
2153 /* need to pause the spooled entry */
2154 ret = (*(current_printif->job_pause))(snum, pjob);
2156 if (ret != 0) {
2157 *errcode = WERR_INVALID_PARAM;
2158 return False;
2161 /* force update the database */
2162 print_cache_flush(lp_const_servicename(snum));
2164 /* Send a printer notify message */
2166 notify_job_status(sharename, jobid, JOB_STATUS_PAUSED);
2168 /* how do we tell if this succeeded? */
2170 return True;
2173 /****************************************************************************
2174 Resume a job.
2175 ****************************************************************************/
2177 bool print_job_resume(struct auth_serversupplied_info *server_info, int snum,
2178 uint32 jobid, WERROR *errcode)
2180 const char *sharename = lp_const_servicename(snum);
2181 struct printjob *pjob;
2182 int ret;
2183 struct printif *current_printif = get_printer_fns( snum );
2185 pjob = print_job_find(sharename, jobid);
2187 if (!pjob || !server_info) {
2188 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2189 (unsigned int)jobid ));
2190 return False;
2193 if (!pjob->spooled || pjob->sysjob == -1) {
2194 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2195 (int)pjob->sysjob, (unsigned int)jobid ));
2196 return False;
2199 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2200 !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2201 DEBUG(3, ("resume denied by security descriptor\n"));
2202 *errcode = WERR_ACCESS_DENIED;
2204 /* BEGIN_ADMIN_LOG */
2205 sys_adminlog( LOG_ERR,
2206 "Permission denied-- user not allowed to delete, \
2207 pause, or resume print job. User name: %s. Printer name: %s.",
2208 uidtoname(server_info->utok.uid),
2209 PRINTERNAME(snum) );
2210 /* END_ADMIN_LOG */
2211 return False;
2214 ret = (*(current_printif->job_resume))(snum, pjob);
2216 if (ret != 0) {
2217 *errcode = WERR_INVALID_PARAM;
2218 return False;
2221 /* force update the database */
2222 print_cache_flush(lp_const_servicename(snum));
2224 /* Send a printer notify message */
2226 notify_job_status(sharename, jobid, JOB_STATUS_QUEUED);
2228 return True;
2231 /****************************************************************************
2232 Write to a print file.
2233 ****************************************************************************/
2235 ssize_t print_job_write(int snum, uint32 jobid, const char *buf, SMB_OFF_T pos, size_t size)
2237 const char* sharename = lp_const_servicename(snum);
2238 int return_code;
2239 struct printjob *pjob;
2241 pjob = print_job_find(sharename, jobid);
2243 if (!pjob)
2244 return -1;
2245 /* don't allow another process to get this info - it is meaningless */
2246 if (pjob->pid != sys_getpid())
2247 return -1;
2249 return_code = write_data_at_offset(pjob->fd, buf, size, pos);
2251 if (return_code>0) {
2252 pjob->size += size;
2253 pjob_store(sharename, jobid, pjob);
2255 return return_code;
2258 /****************************************************************************
2259 Get the queue status - do not update if db is out of date.
2260 ****************************************************************************/
2262 static int get_queue_status(const char* sharename, print_status_struct *status)
2264 fstring keystr;
2265 TDB_DATA data;
2266 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2267 int len;
2269 if (status) {
2270 ZERO_STRUCTP(status);
2273 if (!pdb)
2274 return 0;
2276 if (status) {
2277 fstr_sprintf(keystr, "STATUS/%s", sharename);
2278 data = tdb_fetch(pdb->tdb, string_tdb_data(keystr));
2279 if (data.dptr) {
2280 if (data.dsize == sizeof(print_status_struct))
2281 /* this memcpy is ok since the status struct was
2282 not packed before storing it in the tdb */
2283 memcpy(status, data.dptr, sizeof(print_status_struct));
2284 SAFE_FREE(data.dptr);
2287 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2288 release_print_db(pdb);
2289 return (len == -1 ? 0 : len);
2292 /****************************************************************************
2293 Determine the number of jobs in a queue.
2294 ****************************************************************************/
2296 int print_queue_length(int snum, print_status_struct *pstatus)
2298 const char* sharename = lp_const_servicename( snum );
2299 print_status_struct status;
2300 int len;
2302 ZERO_STRUCT( status );
2304 /* make sure the database is up to date */
2305 if (print_cache_expired(lp_const_servicename(snum), True))
2306 print_queue_update(snum, False);
2308 /* also fetch the queue status */
2309 memset(&status, 0, sizeof(status));
2310 len = get_queue_status(sharename, &status);
2312 if (pstatus)
2313 *pstatus = status;
2315 return len;
2318 /***************************************************************************
2319 Allocate a jobid. Hold the lock for as short a time as possible.
2320 ***************************************************************************/
2322 static bool allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char *sharename, uint32 *pjobid)
2324 int i;
2325 uint32 jobid;
2327 *pjobid = (uint32)-1;
2329 for (i = 0; i < 3; i++) {
2330 /* Lock the database - only wait 20 seconds. */
2331 if (tdb_lock_bystring_with_timeout(pdb->tdb, "INFO/nextjob", 20) == -1) {
2332 DEBUG(0,("allocate_print_jobid: failed to lock printing database %s\n", sharename));
2333 return False;
2336 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2337 if (tdb_error(pdb->tdb) != TDB_ERR_NOEXIST) {
2338 DEBUG(0, ("allocate_print_jobid: failed to fetch INFO/nextjob for print queue %s\n",
2339 sharename));
2340 return False;
2342 jobid = 0;
2345 jobid = NEXT_JOBID(jobid);
2347 if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
2348 DEBUG(3, ("allocate_print_jobid: failed to store INFO/nextjob.\n"));
2349 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2350 return False;
2353 /* We've finished with the INFO/nextjob lock. */
2354 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2356 if (!print_job_exists(sharename, jobid))
2357 break;
2360 if (i > 2) {
2361 DEBUG(0, ("allocate_print_jobid: failed to allocate a print job for queue %s\n",
2362 sharename));
2363 /* Probably full... */
2364 errno = ENOSPC;
2365 return False;
2368 /* Store a dummy placeholder. */
2370 uint32_t tmp;
2371 TDB_DATA dum;
2372 dum.dptr = NULL;
2373 dum.dsize = 0;
2374 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2375 TDB_INSERT) == -1) {
2376 DEBUG(3, ("allocate_print_jobid: jobid (%d) failed to store placeholder.\n",
2377 jobid ));
2378 return False;
2382 *pjobid = jobid;
2383 return True;
2386 /***************************************************************************
2387 Append a jobid to the 'jobs changed' list.
2388 ***************************************************************************/
2390 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32 jobid)
2392 TDB_DATA data;
2393 uint32 store_jobid;
2395 SIVAL(&store_jobid, 0, jobid);
2396 data.dptr = (uint8 *)&store_jobid;
2397 data.dsize = 4;
2399 DEBUG(10,("add_to_jobs_changed: Added jobid %u\n", (unsigned int)jobid ));
2401 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
2402 data) == 0);
2405 /***************************************************************************
2406 Start spooling a job - return the jobid.
2407 ***************************************************************************/
2409 uint32 print_job_start(struct auth_serversupplied_info *server_info, int snum,
2410 const char *jobname, NT_DEVICEMODE *nt_devmode )
2412 uint32 jobid;
2413 char *path;
2414 struct printjob pjob;
2415 const char *sharename = lp_const_servicename(snum);
2416 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2417 int njobs;
2419 errno = 0;
2421 if (!pdb)
2422 return (uint32)-1;
2424 if (!print_access_check(server_info, snum, PRINTER_ACCESS_USE)) {
2425 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
2426 release_print_db(pdb);
2427 return (uint32)-1;
2430 if (!print_time_access_check(lp_servicename(snum))) {
2431 DEBUG(3, ("print_job_start: job start denied by time check\n"));
2432 release_print_db(pdb);
2433 return (uint32)-1;
2436 path = lp_pathname(snum);
2438 /* see if we have sufficient disk space */
2439 if (lp_minprintspace(snum)) {
2440 uint64_t dspace, dsize;
2441 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
2442 dspace < 2*(uint64_t)lp_minprintspace(snum)) {
2443 DEBUG(3, ("print_job_start: disk space check failed.\n"));
2444 release_print_db(pdb);
2445 errno = ENOSPC;
2446 return (uint32)-1;
2450 /* for autoloaded printers, check that the printcap entry still exists */
2451 if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum))) {
2452 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
2453 release_print_db(pdb);
2454 errno = ENOENT;
2455 return (uint32)-1;
2458 /* Insure the maximum queue size is not violated */
2459 if ((njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
2460 DEBUG(3, ("print_job_start: Queue %s number of jobs (%d) larger than max printjobs per queue (%d).\n",
2461 sharename, njobs, lp_maxprintjobs(snum) ));
2462 release_print_db(pdb);
2463 errno = ENOSPC;
2464 return (uint32)-1;
2467 DEBUG(10,("print_job_start: Queue %s number of jobs (%d), max printjobs = %d\n",
2468 sharename, njobs, lp_maxprintjobs(snum) ));
2470 if (!allocate_print_jobid(pdb, snum, sharename, &jobid))
2471 goto fail;
2473 /* create the database entry */
2475 ZERO_STRUCT(pjob);
2477 pjob.pid = sys_getpid();
2478 pjob.sysjob = -1;
2479 pjob.fd = -1;
2480 pjob.starttime = time(NULL);
2481 pjob.status = LPQ_SPOOLING;
2482 pjob.size = 0;
2483 pjob.spooled = False;
2484 pjob.smbjob = True;
2485 pjob.nt_devmode = nt_devmode;
2487 fstrcpy(pjob.jobname, jobname);
2489 fstrcpy(pjob.user, lp_printjob_username(snum));
2490 standard_sub_advanced(sharename, server_info->sanitized_username,
2491 path, server_info->utok.gid,
2492 server_info->sanitized_username,
2493 pdb_get_domain(server_info->sam_account),
2494 pjob.user, sizeof(pjob.user)-1);
2495 /* ensure NULL termination */
2496 pjob.user[sizeof(pjob.user)-1] = '\0';
2498 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2500 /* we have a job entry - now create the spool file */
2501 slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX",
2502 path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2503 pjob.fd = smb_mkstemp(pjob.filename);
2505 if (pjob.fd == -1) {
2506 if (errno == EACCES) {
2507 /* Common setup error, force a report. */
2508 DEBUG(0, ("print_job_start: insufficient permissions \
2509 to open spool file %s.\n", pjob.filename));
2510 } else {
2511 /* Normal case, report at level 3 and above. */
2512 DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
2513 DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
2515 goto fail;
2518 pjob_store(sharename, jobid, &pjob);
2520 /* Update the 'jobs changed' entry used by print_queue_status. */
2521 add_to_jobs_changed(pdb, jobid);
2523 /* Ensure we keep a rough count of the number of total jobs... */
2524 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2526 release_print_db(pdb);
2528 return jobid;
2530 fail:
2531 if (jobid != -1)
2532 pjob_delete(sharename, jobid);
2534 release_print_db(pdb);
2536 DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
2537 return (uint32)-1;
2540 /****************************************************************************
2541 Update the number of pages spooled to jobid
2542 ****************************************************************************/
2544 void print_job_endpage(int snum, uint32 jobid)
2546 const char* sharename = lp_const_servicename(snum);
2547 struct printjob *pjob;
2549 pjob = print_job_find(sharename, jobid);
2550 if (!pjob)
2551 return;
2552 /* don't allow another process to get this info - it is meaningless */
2553 if (pjob->pid != sys_getpid())
2554 return;
2556 pjob->page_count++;
2557 pjob_store(sharename, jobid, pjob);
2560 /****************************************************************************
2561 Print a file - called on closing the file. This spools the job.
2562 If normal close is false then we're tearing down the jobs - treat as an
2563 error.
2564 ****************************************************************************/
2566 bool print_job_end(int snum, uint32 jobid, enum file_close_type close_type)
2568 const char* sharename = lp_const_servicename(snum);
2569 struct printjob *pjob;
2570 int ret;
2571 SMB_STRUCT_STAT sbuf;
2572 struct printif *current_printif = get_printer_fns( snum );
2574 pjob = print_job_find(sharename, jobid);
2576 if (!pjob)
2577 return False;
2579 if (pjob->spooled || pjob->pid != sys_getpid())
2580 return False;
2582 if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
2583 (sys_fstat(pjob->fd, &sbuf) == 0)) {
2584 pjob->size = sbuf.st_size;
2585 close(pjob->fd);
2586 pjob->fd = -1;
2587 } else {
2590 * Not a normal close or we couldn't stat the job file,
2591 * so something has gone wrong. Cleanup.
2593 close(pjob->fd);
2594 pjob->fd = -1;
2595 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
2596 goto fail;
2599 /* Technically, this is not quite right. If the printer has a separator
2600 * page turned on, the NT spooler prints the separator page even if the
2601 * print job is 0 bytes. 010215 JRR */
2602 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
2603 /* don't bother spooling empty files or something being deleted. */
2604 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
2605 pjob->filename, pjob->size ? "deleted" : "zero length" ));
2606 unlink(pjob->filename);
2607 pjob_delete(sharename, jobid);
2608 return True;
2611 pjob->smbjob = jobid;
2613 ret = (*(current_printif->job_submit))(snum, pjob);
2615 if (ret)
2616 goto fail;
2618 /* The print job has been successfully handed over to the back-end */
2620 pjob->spooled = True;
2621 pjob->status = LPQ_QUEUED;
2622 pjob_store(sharename, jobid, pjob);
2624 /* make sure the database is up to date */
2625 if (print_cache_expired(lp_const_servicename(snum), True))
2626 print_queue_update(snum, False);
2628 return True;
2630 fail:
2632 /* The print job was not successfully started. Cleanup */
2633 /* Still need to add proper error return propagation! 010122:JRR */
2634 unlink(pjob->filename);
2635 pjob_delete(sharename, jobid);
2636 return False;
2639 /****************************************************************************
2640 Get a snapshot of jobs in the system without traversing.
2641 ****************************************************************************/
2643 static bool get_stored_queue_info(struct tdb_print_db *pdb, int snum, int *pcount, print_queue_struct **ppqueue)
2645 TDB_DATA data, cgdata;
2646 print_queue_struct *queue = NULL;
2647 uint32 qcount = 0;
2648 uint32 extra_count = 0;
2649 int total_count = 0;
2650 size_t len = 0;
2651 uint32 i;
2652 int max_reported_jobs = lp_max_reported_jobs(snum);
2653 bool ret = False;
2654 const char* sharename = lp_servicename(snum);
2656 /* make sure the database is up to date */
2657 if (print_cache_expired(lp_const_servicename(snum), True))
2658 print_queue_update(snum, False);
2660 *pcount = 0;
2661 *ppqueue = NULL;
2663 ZERO_STRUCT(data);
2664 ZERO_STRUCT(cgdata);
2666 /* Get the stored queue data. */
2667 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
2669 if (data.dptr && data.dsize >= sizeof(qcount))
2670 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
2672 /* Get the changed jobs list. */
2673 cgdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
2674 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
2675 extra_count = cgdata.dsize/4;
2677 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
2679 /* Allocate the queue size. */
2680 if (qcount == 0 && extra_count == 0)
2681 goto out;
2683 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
2684 goto out;
2686 /* Retrieve the linearised queue data. */
2688 for( i = 0; i < qcount; i++) {
2689 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
2690 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
2691 &qjob,
2692 &qsize,
2693 &qpage_count,
2694 &qstatus,
2695 &qpriority,
2696 &qtime,
2697 queue[i].fs_user,
2698 queue[i].fs_file);
2699 queue[i].job = qjob;
2700 queue[i].size = qsize;
2701 queue[i].page_count = qpage_count;
2702 queue[i].status = qstatus;
2703 queue[i].priority = qpriority;
2704 queue[i].time = qtime;
2707 total_count = qcount;
2709 /* Add in the changed jobids. */
2710 for( i = 0; i < extra_count; i++) {
2711 uint32 jobid;
2712 struct printjob *pjob;
2714 jobid = IVAL(cgdata.dptr, i*4);
2715 DEBUG(5,("get_stored_queue_info: changed job = %u\n", (unsigned int)jobid));
2716 pjob = print_job_find(lp_const_servicename(snum), jobid);
2717 if (!pjob) {
2718 DEBUG(5,("get_stored_queue_info: failed to find changed job = %u\n", (unsigned int)jobid));
2719 remove_from_jobs_changed(sharename, jobid);
2720 continue;
2723 queue[total_count].job = jobid;
2724 queue[total_count].size = pjob->size;
2725 queue[total_count].page_count = pjob->page_count;
2726 queue[total_count].status = pjob->status;
2727 queue[total_count].priority = 1;
2728 queue[total_count].time = pjob->starttime;
2729 fstrcpy(queue[total_count].fs_user, pjob->user);
2730 fstrcpy(queue[total_count].fs_file, pjob->jobname);
2731 total_count++;
2734 /* Sort the queue by submission time otherwise they are displayed
2735 in hash order. */
2737 qsort(queue, total_count, sizeof(print_queue_struct), QSORT_CAST(printjob_comp));
2739 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
2741 if (max_reported_jobs && total_count > max_reported_jobs)
2742 total_count = max_reported_jobs;
2744 *ppqueue = queue;
2745 *pcount = total_count;
2747 ret = True;
2749 out:
2751 SAFE_FREE(data.dptr);
2752 SAFE_FREE(cgdata.dptr);
2753 return ret;
2756 /****************************************************************************
2757 Get a printer queue listing.
2758 set queue = NULL and status = NULL if you just want to update the cache
2759 ****************************************************************************/
2761 int print_queue_status(int snum,
2762 print_queue_struct **ppqueue,
2763 print_status_struct *status)
2765 fstring keystr;
2766 TDB_DATA data, key;
2767 const char *sharename;
2768 struct tdb_print_db *pdb;
2769 int count = 0;
2771 /* make sure the database is up to date */
2773 if (print_cache_expired(lp_const_servicename(snum), True))
2774 print_queue_update(snum, False);
2776 /* return if we are done */
2777 if ( !ppqueue || !status )
2778 return 0;
2780 *ppqueue = NULL;
2781 sharename = lp_const_servicename(snum);
2782 pdb = get_print_db_byname(sharename);
2784 if (!pdb)
2785 return 0;
2788 * Fetch the queue status. We must do this first, as there may
2789 * be no jobs in the queue.
2792 ZERO_STRUCTP(status);
2793 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
2794 key = string_tdb_data(keystr);
2796 data = tdb_fetch(pdb->tdb, key);
2797 if (data.dptr) {
2798 if (data.dsize == sizeof(*status)) {
2799 /* this memcpy is ok since the status struct was
2800 not packed before storing it in the tdb */
2801 memcpy(status, data.dptr, sizeof(*status));
2803 SAFE_FREE(data.dptr);
2807 * Now, fetch the print queue information. We first count the number
2808 * of entries, and then only retrieve the queue if necessary.
2811 if (!get_stored_queue_info(pdb, snum, &count, ppqueue)) {
2812 release_print_db(pdb);
2813 return 0;
2816 release_print_db(pdb);
2817 return count;
2820 /****************************************************************************
2821 Pause a queue.
2822 ****************************************************************************/
2824 bool print_queue_pause(struct auth_serversupplied_info *server_info, int snum,
2825 WERROR *errcode)
2827 int ret;
2828 struct printif *current_printif = get_printer_fns( snum );
2830 if (!print_access_check(server_info, snum,
2831 PRINTER_ACCESS_ADMINISTER)) {
2832 *errcode = WERR_ACCESS_DENIED;
2833 return False;
2837 become_root();
2839 ret = (*(current_printif->queue_pause))(snum);
2841 unbecome_root();
2843 if (ret != 0) {
2844 *errcode = WERR_INVALID_PARAM;
2845 return False;
2848 /* force update the database */
2849 print_cache_flush(lp_const_servicename(snum));
2851 /* Send a printer notify message */
2853 notify_printer_status(snum, PRINTER_STATUS_PAUSED);
2855 return True;
2858 /****************************************************************************
2859 Resume a queue.
2860 ****************************************************************************/
2862 bool print_queue_resume(struct auth_serversupplied_info *server_info, int snum,
2863 WERROR *errcode)
2865 int ret;
2866 struct printif *current_printif = get_printer_fns( snum );
2868 if (!print_access_check(server_info, snum,
2869 PRINTER_ACCESS_ADMINISTER)) {
2870 *errcode = WERR_ACCESS_DENIED;
2871 return False;
2874 become_root();
2876 ret = (*(current_printif->queue_resume))(snum);
2878 unbecome_root();
2880 if (ret != 0) {
2881 *errcode = WERR_INVALID_PARAM;
2882 return False;
2885 /* make sure the database is up to date */
2886 if (print_cache_expired(lp_const_servicename(snum), True))
2887 print_queue_update(snum, True);
2889 /* Send a printer notify message */
2891 notify_printer_status(snum, PRINTER_STATUS_OK);
2893 return True;
2896 /****************************************************************************
2897 Purge a queue - implemented by deleting all jobs that we can delete.
2898 ****************************************************************************/
2900 bool print_queue_purge(struct auth_serversupplied_info *server_info, int snum,
2901 WERROR *errcode)
2903 print_queue_struct *queue;
2904 print_status_struct status;
2905 int njobs, i;
2906 bool can_job_admin;
2908 /* Force and update so the count is accurate (i.e. not a cached count) */
2909 print_queue_update(snum, True);
2911 can_job_admin = print_access_check(server_info, snum,
2912 JOB_ACCESS_ADMINISTER);
2913 njobs = print_queue_status(snum, &queue, &status);
2915 if ( can_job_admin )
2916 become_root();
2918 for (i=0;i<njobs;i++) {
2919 bool owner = is_owner(server_info, lp_const_servicename(snum),
2920 queue[i].job);
2922 if (owner || can_job_admin) {
2923 print_job_delete1(snum, queue[i].job);
2927 if ( can_job_admin )
2928 unbecome_root();
2930 /* update the cache */
2931 print_queue_update( snum, True );
2933 SAFE_FREE(queue);
2935 return True;