Fix bug #7288 - SMB job IDs in CUPS job names wrong.
[Samba/gebeck_regimport.git] / source3 / printing / printing.c
blob7804997dfafd126cc870fa155efd18b2d6dae6b4
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 List a unix job in the print database.
648 ****************************************************************************/
650 static void print_unix_job(const char *sharename, print_queue_struct *q, uint32 jobid)
652 struct printjob pj, *old_pj;
654 if (jobid == (uint32)-1)
655 jobid = q->job + UNIX_JOB_START;
657 /* Preserve the timestamp on an existing unix print job */
659 old_pj = print_job_find(sharename, jobid);
661 ZERO_STRUCT(pj);
663 pj.pid = (pid_t)-1;
664 pj.sysjob = q->job;
665 pj.fd = -1;
666 pj.starttime = old_pj ? old_pj->starttime : q->time;
667 pj.status = q->status;
668 pj.size = q->size;
669 pj.spooled = True;
670 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
671 if (jobid < UNIX_JOB_START) {
672 pj.smbjob = True;
673 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
674 } else {
675 pj.smbjob = False;
676 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
678 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
679 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
681 pjob_store(sharename, jobid, &pj);
685 struct traverse_struct {
686 print_queue_struct *queue;
687 int qcount, snum, maxcount, total_jobs;
688 const char *sharename;
689 time_t lpq_time;
690 const char *lprm_command;
691 struct printif *print_if;
694 /****************************************************************************
695 Utility fn to delete any jobs that are no longer active.
696 ****************************************************************************/
698 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
700 struct traverse_struct *ts = (struct traverse_struct *)state;
701 struct printjob pjob;
702 uint32 jobid;
703 int i = 0;
705 if ( key.dsize != sizeof(jobid) )
706 return 0;
708 jobid = IVAL(key.dptr, 0);
709 if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
710 return 0;
711 free_nt_devicemode( &pjob.nt_devmode );
714 if (!pjob.smbjob) {
715 /* remove a unix job if it isn't in the system queue any more */
717 for (i=0;i<ts->qcount;i++) {
718 uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
719 if (jobid == u_jobid)
720 break;
722 if (i == ts->qcount) {
723 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
724 (unsigned int)jobid ));
725 pjob_delete(ts->sharename, jobid);
726 return 0;
729 /* need to continue the the bottom of the function to
730 save the correct attributes */
733 /* maybe it hasn't been spooled yet */
734 if (!pjob.spooled) {
735 /* if a job is not spooled and the process doesn't
736 exist then kill it. This cleans up after smbd
737 deaths */
738 if (!process_exists_by_pid(pjob.pid)) {
739 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
740 (unsigned int)jobid, (unsigned int)pjob.pid ));
741 pjob_delete(ts->sharename, jobid);
742 } else
743 ts->total_jobs++;
744 return 0;
747 /* this check only makes sense for jobs submitted from Windows clients */
749 if ( pjob.smbjob ) {
750 for (i=0;i<ts->qcount;i++) {
751 uint32 curr_jobid;
753 if ( pjob.status == LPQ_DELETED )
754 continue;
756 curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
758 if (jobid == curr_jobid) {
760 /* try to clean up any jobs that need to be deleted */
762 if ( pjob.status == LPQ_DELETING ) {
763 int result;
765 result = (*(ts->print_if->job_delete))(
766 ts->sharename, ts->lprm_command, &pjob );
768 if ( result != 0 ) {
769 /* if we can't delete, then reset the job status */
770 pjob.status = LPQ_QUEUED;
771 pjob_store(ts->sharename, jobid, &pjob);
773 else {
774 /* if we deleted the job, the remove the tdb record */
775 pjob_delete(ts->sharename, jobid);
776 pjob.status = LPQ_DELETED;
781 break;
786 /* The job isn't in the system queue - we have to assume it has
787 completed, so delete the database entry. */
789 if (i == ts->qcount) {
791 /* A race can occur between the time a job is spooled and
792 when it appears in the lpq output. This happens when
793 the job is added to printing.tdb when another smbd
794 running print_queue_update() has completed a lpq and
795 is currently traversing the printing tdb and deleting jobs.
796 Don't delete the job if it was submitted after the lpq_time. */
798 if (pjob.starttime < ts->lpq_time) {
799 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
800 (unsigned int)jobid,
801 (unsigned int)pjob.starttime,
802 (unsigned int)ts->lpq_time ));
803 pjob_delete(ts->sharename, jobid);
804 } else
805 ts->total_jobs++;
806 return 0;
809 /* Save the pjob attributes we will store.
810 FIXME!!! This is the only place where queue->job
811 represents the SMB jobid --jerry */
813 ts->queue[i].job = jobid;
814 ts->queue[i].size = pjob.size;
815 ts->queue[i].page_count = pjob.page_count;
816 ts->queue[i].status = pjob.status;
817 ts->queue[i].priority = 1;
818 ts->queue[i].time = pjob.starttime;
819 fstrcpy(ts->queue[i].fs_user, pjob.user);
820 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
822 ts->total_jobs++;
824 return 0;
827 /****************************************************************************
828 Check if the print queue has been updated recently enough.
829 ****************************************************************************/
831 static void print_cache_flush(const char *sharename)
833 fstring key;
834 struct tdb_print_db *pdb = get_print_db_byname(sharename);
836 if (!pdb)
837 return;
838 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
839 tdb_store_int32(pdb->tdb, key, -1);
840 release_print_db(pdb);
843 /****************************************************************************
844 Check if someone already thinks they are doing the update.
845 ****************************************************************************/
847 static pid_t get_updating_pid(const char *sharename)
849 fstring keystr;
850 TDB_DATA data, key;
851 pid_t updating_pid;
852 struct tdb_print_db *pdb = get_print_db_byname(sharename);
854 if (!pdb)
855 return (pid_t)-1;
856 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
857 key = string_tdb_data(keystr);
859 data = tdb_fetch(pdb->tdb, key);
860 release_print_db(pdb);
861 if (!data.dptr || data.dsize != sizeof(pid_t)) {
862 SAFE_FREE(data.dptr);
863 return (pid_t)-1;
866 updating_pid = IVAL(data.dptr, 0);
867 SAFE_FREE(data.dptr);
869 if (process_exists_by_pid(updating_pid))
870 return updating_pid;
872 return (pid_t)-1;
875 /****************************************************************************
876 Set the fact that we're doing the update, or have finished doing the update
877 in the tdb.
878 ****************************************************************************/
880 static void set_updating_pid(const fstring sharename, bool updating)
882 fstring keystr;
883 TDB_DATA key;
884 TDB_DATA data;
885 pid_t updating_pid = sys_getpid();
886 uint8 buffer[4];
888 struct tdb_print_db *pdb = get_print_db_byname(sharename);
890 if (!pdb)
891 return;
893 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
894 key = string_tdb_data(keystr);
896 DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
897 updating ? "" : "not ",
898 sharename ));
900 if ( !updating ) {
901 tdb_delete(pdb->tdb, key);
902 release_print_db(pdb);
903 return;
906 SIVAL( buffer, 0, updating_pid);
907 data.dptr = buffer;
908 data.dsize = 4; /* we always assume this is a 4 byte value */
910 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
911 release_print_db(pdb);
914 /****************************************************************************
915 Sort print jobs by submittal time.
916 ****************************************************************************/
918 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
920 /* Silly cases */
922 if (!j1 && !j2)
923 return 0;
924 if (!j1)
925 return -1;
926 if (!j2)
927 return 1;
929 /* Sort on job start time */
931 if (j1->time == j2->time)
932 return 0;
933 return (j1->time > j2->time) ? 1 : -1;
936 /****************************************************************************
937 Store the sorted queue representation for later portmon retrieval.
938 Skip deleted jobs
939 ****************************************************************************/
941 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
943 TDB_DATA data;
944 int max_reported_jobs = lp_max_reported_jobs(pts->snum);
945 print_queue_struct *queue = pts->queue;
946 size_t len;
947 size_t i;
948 unsigned int qcount;
950 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
951 pts->qcount = max_reported_jobs;
952 qcount = 0;
954 /* Work out the size. */
955 data.dsize = 0;
956 data.dsize += tdb_pack(NULL, 0, "d", qcount);
958 for (i = 0; i < pts->qcount; i++) {
959 if ( queue[i].status == LPQ_DELETED )
960 continue;
962 qcount++;
963 data.dsize += tdb_pack(NULL, 0, "ddddddff",
964 (uint32)queue[i].job,
965 (uint32)queue[i].size,
966 (uint32)queue[i].page_count,
967 (uint32)queue[i].status,
968 (uint32)queue[i].priority,
969 (uint32)queue[i].time,
970 queue[i].fs_user,
971 queue[i].fs_file);
974 if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
975 return;
977 len = 0;
978 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
979 for (i = 0; i < pts->qcount; i++) {
980 if ( queue[i].status == LPQ_DELETED )
981 continue;
983 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
984 (uint32)queue[i].job,
985 (uint32)queue[i].size,
986 (uint32)queue[i].page_count,
987 (uint32)queue[i].status,
988 (uint32)queue[i].priority,
989 (uint32)queue[i].time,
990 queue[i].fs_user,
991 queue[i].fs_file);
994 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
995 TDB_REPLACE);
996 SAFE_FREE(data.dptr);
997 return;
1000 static TDB_DATA get_jobs_changed_data(struct tdb_print_db *pdb)
1002 TDB_DATA data;
1004 ZERO_STRUCT(data);
1006 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
1007 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1008 SAFE_FREE(data.dptr);
1009 ZERO_STRUCT(data);
1012 return data;
1015 static void check_job_changed(const char *sharename, TDB_DATA data, uint32 jobid)
1017 unsigned int i;
1018 unsigned int job_count = data.dsize / 4;
1020 for (i = 0; i < job_count; i++) {
1021 uint32 ch_jobid;
1023 ch_jobid = IVAL(data.dptr, i*4);
1024 if (ch_jobid == jobid)
1025 remove_from_jobs_changed(sharename, jobid);
1029 /****************************************************************************
1030 Check if the print queue has been updated recently enough.
1031 ****************************************************************************/
1033 static bool print_cache_expired(const char *sharename, bool check_pending)
1035 fstring key;
1036 time_t last_qscan_time, time_now = time(NULL);
1037 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1038 bool result = False;
1040 if (!pdb)
1041 return False;
1043 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1044 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1047 * Invalidate the queue for 3 reasons.
1048 * (1). last queue scan time == -1.
1049 * (2). Current time - last queue scan time > allowed cache time.
1050 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1051 * This last test picks up machines for which the clock has been moved
1052 * forward, an lpq scan done and then the clock moved back. Otherwise
1053 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1056 if (last_qscan_time == ((time_t)-1)
1057 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1058 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1060 uint32 u;
1061 time_t msg_pending_time;
1063 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1064 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1065 sharename, (int)last_qscan_time, (int)time_now,
1066 (int)lp_lpqcachetime() ));
1068 /* check if another smbd has already sent a message to update the
1069 queue. Give the pending message one minute to clear and
1070 then send another message anyways. Make sure to check for
1071 clocks that have been run forward and then back again. */
1073 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1075 if ( check_pending
1076 && tdb_fetch_uint32( pdb->tdb, key, &u )
1077 && (msg_pending_time=u) > 0
1078 && msg_pending_time <= time_now
1079 && (time_now - msg_pending_time) < 60 )
1081 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1082 sharename));
1083 goto done;
1086 result = True;
1089 done:
1090 release_print_db(pdb);
1091 return result;
1094 /****************************************************************************
1095 main work for updating the lpq cahe for a printer queue
1096 ****************************************************************************/
1098 static void print_queue_update_internal( const char *sharename,
1099 struct printif *current_printif,
1100 char *lpq_command, char *lprm_command )
1102 int i, qcount;
1103 print_queue_struct *queue = NULL;
1104 print_status_struct status;
1105 print_status_struct old_status;
1106 struct printjob *pjob;
1107 struct traverse_struct tstruct;
1108 TDB_DATA data, key;
1109 TDB_DATA jcdata;
1110 fstring keystr, cachestr;
1111 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1113 if (!pdb) {
1114 return;
1117 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1118 sharename, current_printif->type, lpq_command));
1121 * Update the cache time FIRST ! Stops others even
1122 * attempting to get the lock and doing this
1123 * if the lpq takes a long time.
1126 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1127 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1129 /* get the current queue using the appropriate interface */
1130 ZERO_STRUCT(status);
1132 qcount = (*(current_printif->queue_get))(sharename,
1133 current_printif->type,
1134 lpq_command, &queue, &status);
1136 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1137 qcount, (qcount != 1) ? "s" : "", sharename));
1139 /* Sort the queue by submission time otherwise they are displayed
1140 in hash order. */
1142 TYPESAFE_QSORT(queue, qcount, printjob_comp);
1145 any job in the internal database that is marked as spooled
1146 and doesn't exist in the system queue is considered finished
1147 and removed from the database
1149 any job in the system database but not in the internal database
1150 is added as a unix job
1152 fill in any system job numbers as we go
1155 jcdata = get_jobs_changed_data(pdb);
1157 for (i=0; i<qcount; i++) {
1158 uint32 jobid = print_parse_jobid(queue[i].fs_file);
1160 if (jobid == (uint32)-1) {
1161 /* assume its a unix print job */
1162 print_unix_job(sharename, &queue[i], jobid);
1163 continue;
1166 /* we have an active SMB print job - update its status */
1167 pjob = print_job_find(sharename, jobid);
1168 if (!pjob) {
1169 /* err, somethings wrong. Probably smbd was restarted
1170 with jobs in the queue. All we can do is treat them
1171 like unix jobs. Pity. */
1172 print_unix_job(sharename, &queue[i], jobid);
1173 continue;
1176 pjob->sysjob = queue[i].job;
1178 /* don't reset the status on jobs to be deleted */
1180 if ( pjob->status != LPQ_DELETING )
1181 pjob->status = queue[i].status;
1183 pjob_store(sharename, jobid, pjob);
1185 check_job_changed(sharename, jcdata, jobid);
1188 SAFE_FREE(jcdata.dptr);
1190 /* now delete any queued entries that don't appear in the
1191 system queue */
1192 tstruct.queue = queue;
1193 tstruct.qcount = qcount;
1194 tstruct.snum = -1;
1195 tstruct.total_jobs = 0;
1196 tstruct.lpq_time = time(NULL);
1197 tstruct.sharename = sharename;
1198 tstruct.lprm_command = lprm_command;
1199 tstruct.print_if = current_printif;
1201 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1203 /* Store the linearised queue, max jobs only. */
1204 store_queue_struct(pdb, &tstruct);
1206 SAFE_FREE(tstruct.queue);
1208 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1209 sharename, tstruct.total_jobs ));
1211 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1213 get_queue_status(sharename, &old_status);
1214 if (old_status.qcount != qcount)
1215 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1216 old_status.qcount, qcount, sharename));
1218 /* store the new queue status structure */
1219 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1220 key = string_tdb_data(keystr);
1222 status.qcount = qcount;
1223 data.dptr = (uint8 *)&status;
1224 data.dsize = sizeof(status);
1225 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1228 * Update the cache time again. We want to do this call
1229 * as little as possible...
1232 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1233 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1235 /* clear the msg pending record for this queue */
1237 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1239 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1240 /* log a message but continue on */
1242 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1243 sharename));
1246 release_print_db( pdb );
1248 return;
1251 /****************************************************************************
1252 Update the internal database from the system print queue for a queue.
1253 obtain a lock on the print queue before proceeding (needed when mutiple
1254 smbd processes maytry to update the lpq cache concurrently).
1255 ****************************************************************************/
1257 static void print_queue_update_with_lock( const char *sharename,
1258 struct printif *current_printif,
1259 char *lpq_command, char *lprm_command )
1261 fstring keystr;
1262 struct tdb_print_db *pdb;
1264 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1265 pdb = get_print_db_byname(sharename);
1266 if (!pdb)
1267 return;
1269 if ( !print_cache_expired(sharename, False) ) {
1270 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1271 release_print_db(pdb);
1272 return;
1276 * Check to see if someone else is doing this update.
1277 * This is essentially a mutex on the update.
1280 if (get_updating_pid(sharename) != -1) {
1281 release_print_db(pdb);
1282 return;
1285 /* Lock the queue for the database update */
1287 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1288 /* Only wait 10 seconds for this. */
1289 if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) == -1) {
1290 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1291 release_print_db(pdb);
1292 return;
1296 * Ensure that no one else got in here.
1297 * If the updating pid is still -1 then we are
1298 * the winner.
1301 if (get_updating_pid(sharename) != -1) {
1303 * Someone else is doing the update, exit.
1305 tdb_unlock_bystring(pdb->tdb, keystr);
1306 release_print_db(pdb);
1307 return;
1311 * We're going to do the update ourselves.
1314 /* Tell others we're doing the update. */
1315 set_updating_pid(sharename, True);
1318 * Allow others to enter and notice we're doing
1319 * the update.
1322 tdb_unlock_bystring(pdb->tdb, keystr);
1324 /* do the main work now */
1326 print_queue_update_internal( sharename, current_printif,
1327 lpq_command, lprm_command );
1329 /* Delete our pid from the db. */
1330 set_updating_pid(sharename, False);
1331 release_print_db(pdb);
1334 /****************************************************************************
1335 this is the receive function of the background lpq updater
1336 ****************************************************************************/
1337 static void print_queue_receive(struct messaging_context *msg,
1338 void *private_data,
1339 uint32_t msg_type,
1340 struct server_id server_id,
1341 DATA_BLOB *data)
1343 fstring sharename;
1344 char *lpqcommand = NULL, *lprmcommand = NULL;
1345 int printing_type;
1346 size_t len;
1348 len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1349 sharename,
1350 &printing_type,
1351 &lpqcommand,
1352 &lprmcommand );
1354 if ( len == -1 ) {
1355 SAFE_FREE(lpqcommand);
1356 SAFE_FREE(lprmcommand);
1357 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1358 return;
1361 print_queue_update_with_lock(sharename,
1362 get_printer_fns_from_type((enum printing_types)printing_type),
1363 lpqcommand, lprmcommand );
1365 SAFE_FREE(lpqcommand);
1366 SAFE_FREE(lprmcommand);
1367 return;
1370 static void printing_pause_fd_handler(struct tevent_context *ev,
1371 struct tevent_fd *fde,
1372 uint16_t flags,
1373 void *private_data)
1376 * If pause_pipe[1] is closed it means the parent smbd
1377 * and children exited or aborted.
1379 exit_server_cleanly(NULL);
1382 static void add_child_pid(pid_t pid)
1384 extern struct child_pid *children;
1385 struct child_pid *child;
1386 extern int num_children;
1388 child = SMB_MALLOC_P(struct child_pid);
1389 if (child == NULL) {
1390 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
1391 return;
1393 child->pid = pid;
1394 DLIST_ADD(children, child);
1395 num_children += 1;
1398 static pid_t background_lpq_updater_pid = -1;
1400 /****************************************************************************
1401 main thread of the background lpq updater
1402 ****************************************************************************/
1403 void start_background_queue(void)
1405 /* Use local variables for this as we don't
1406 * need to save the parent side of this, just
1407 * ensure it closes when the process exits.
1409 int pause_pipe[2];
1411 DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
1413 if (pipe(pause_pipe) == -1) {
1414 DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
1415 exit(1);
1418 background_lpq_updater_pid = sys_fork();
1420 if (background_lpq_updater_pid == -1) {
1421 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
1422 exit(1);
1425 /* Track the printing pid along with other smbd children */
1426 add_child_pid(background_lpq_updater_pid);
1428 if(background_lpq_updater_pid == 0) {
1429 struct tevent_fd *fde;
1430 int ret;
1432 /* Child. */
1433 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
1435 close(pause_pipe[0]);
1436 pause_pipe[0] = -1;
1438 if (!NT_STATUS_IS_OK(reinit_after_fork(smbd_messaging_context(),
1439 smbd_event_context(),
1440 true))) {
1441 DEBUG(0,("reinit_after_fork() failed\n"));
1442 smb_panic("reinit_after_fork() failed");
1445 smbd_setup_sig_term_handler();
1446 smbd_setup_sig_hup_handler();
1448 if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_SMBD
1449 |FLAG_MSG_PRINT_GENERAL)) {
1450 exit(1);
1453 if (!locking_init()) {
1454 exit(1);
1457 messaging_register(smbd_messaging_context(), NULL,
1458 MSG_PRINTER_UPDATE, print_queue_receive);
1460 fde = tevent_add_fd(smbd_event_context(), smbd_event_context(),
1461 pause_pipe[1], TEVENT_FD_READ,
1462 printing_pause_fd_handler,
1463 NULL);
1464 if (!fde) {
1465 DEBUG(0,("tevent_add_fd() failed for pause_pipe\n"));
1466 smb_panic("tevent_add_fd() failed for pause_pipe");
1469 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
1470 ret = tevent_loop_wait(smbd_event_context());
1471 /* should not be reached */
1472 DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
1473 ret, (ret == 0) ? "out of events" : strerror(errno)));
1474 exit(1);
1477 close(pause_pipe[1]);
1480 /****************************************************************************
1481 update the internal database from the system print queue for a queue
1482 ****************************************************************************/
1484 static void print_queue_update(int snum, bool force)
1486 fstring key;
1487 fstring sharename;
1488 char *lpqcommand = NULL;
1489 char *lprmcommand = NULL;
1490 uint8 *buffer = NULL;
1491 size_t len = 0;
1492 size_t newlen;
1493 struct tdb_print_db *pdb;
1494 int type;
1495 struct printif *current_printif;
1496 TALLOC_CTX *ctx = talloc_tos();
1498 fstrcpy( sharename, lp_const_servicename(snum));
1500 /* don't strip out characters like '$' from the printername */
1502 lpqcommand = talloc_string_sub2(ctx,
1503 lp_lpqcommand(snum),
1504 "%p",
1505 PRINTERNAME(snum),
1506 false, false, false);
1507 if (!lpqcommand) {
1508 return;
1510 lpqcommand = talloc_sub_advanced(ctx,
1511 lp_servicename(snum),
1512 current_user_info.unix_name,
1514 current_user.ut.gid,
1515 get_current_username(),
1516 current_user_info.domain,
1517 lpqcommand);
1518 if (!lpqcommand) {
1519 return;
1522 lprmcommand = talloc_string_sub2(ctx,
1523 lp_lprmcommand(snum),
1524 "%p",
1525 PRINTERNAME(snum),
1526 false, false, false);
1527 if (!lprmcommand) {
1528 return;
1530 lprmcommand = talloc_sub_advanced(ctx,
1531 lp_servicename(snum),
1532 current_user_info.unix_name,
1534 current_user.ut.gid,
1535 get_current_username(),
1536 current_user_info.domain,
1537 lprmcommand);
1538 if (!lprmcommand) {
1539 return;
1543 * Make sure that the background queue process exists.
1544 * Otherwise just do the update ourselves
1547 if ( force || background_lpq_updater_pid == -1 ) {
1548 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1549 current_printif = get_printer_fns( snum );
1550 print_queue_update_with_lock( sharename, current_printif, lpqcommand, lprmcommand );
1552 return;
1555 type = lp_printing(snum);
1557 /* get the length */
1559 len = tdb_pack( NULL, 0, "fdPP",
1560 sharename,
1561 type,
1562 lpqcommand,
1563 lprmcommand );
1565 buffer = SMB_XMALLOC_ARRAY( uint8, len );
1567 /* now pack the buffer */
1568 newlen = tdb_pack( buffer, len, "fdPP",
1569 sharename,
1570 type,
1571 lpqcommand,
1572 lprmcommand );
1574 SMB_ASSERT( newlen == len );
1576 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1577 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1578 sharename, type, lpqcommand, lprmcommand ));
1580 /* here we set a msg pending record for other smbd processes
1581 to throttle the number of duplicate print_queue_update msgs
1582 sent. */
1584 pdb = get_print_db_byname(sharename);
1585 if (!pdb) {
1586 SAFE_FREE(buffer);
1587 return;
1590 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1592 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1593 /* log a message but continue on */
1595 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1596 sharename));
1599 release_print_db( pdb );
1601 /* finally send the message */
1603 messaging_send_buf(smbd_messaging_context(),
1604 pid_to_procid(background_lpq_updater_pid),
1605 MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1607 SAFE_FREE( buffer );
1609 return;
1612 /****************************************************************************
1613 Create/Update an entry in the print tdb that will allow us to send notify
1614 updates only to interested smbd's.
1615 ****************************************************************************/
1617 bool print_notify_register_pid(int snum)
1619 TDB_DATA data;
1620 struct tdb_print_db *pdb = NULL;
1621 TDB_CONTEXT *tdb = NULL;
1622 const char *printername;
1623 uint32 mypid = (uint32)sys_getpid();
1624 bool ret = False;
1625 size_t i;
1627 /* if (snum == -1), then the change notify request was
1628 on a print server handle and we need to register on
1629 all print queus */
1631 if (snum == -1)
1633 int num_services = lp_numservices();
1634 int idx;
1636 for ( idx=0; idx<num_services; idx++ ) {
1637 if (lp_snum_ok(idx) && lp_print_ok(idx) )
1638 print_notify_register_pid(idx);
1641 return True;
1643 else /* register for a specific printer */
1645 printername = lp_const_servicename(snum);
1646 pdb = get_print_db_byname(printername);
1647 if (!pdb)
1648 return False;
1649 tdb = pdb->tdb;
1652 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1653 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1654 printername));
1655 if (pdb)
1656 release_print_db(pdb);
1657 return False;
1660 data = get_printer_notify_pid_list( tdb, printername, True );
1662 /* Add ourselves and increase the refcount. */
1664 for (i = 0; i < data.dsize; i += 8) {
1665 if (IVAL(data.dptr,i) == mypid) {
1666 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1667 SIVAL(data.dptr, i+4, new_refcount);
1668 break;
1672 if (i == data.dsize) {
1673 /* We weren't in the list. Realloc. */
1674 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1675 if (!data.dptr) {
1676 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1677 printername));
1678 goto done;
1680 data.dsize += 8;
1681 SIVAL(data.dptr,data.dsize - 8,mypid);
1682 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1685 /* Store back the record. */
1686 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1687 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1688 list for printer %s\n", printername));
1689 goto done;
1692 ret = True;
1694 done:
1696 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1697 if (pdb)
1698 release_print_db(pdb);
1699 SAFE_FREE(data.dptr);
1700 return ret;
1703 /****************************************************************************
1704 Update an entry in the print tdb that will allow us to send notify
1705 updates only to interested smbd's.
1706 ****************************************************************************/
1708 bool print_notify_deregister_pid(int snum)
1710 TDB_DATA data;
1711 struct tdb_print_db *pdb = NULL;
1712 TDB_CONTEXT *tdb = NULL;
1713 const char *printername;
1714 uint32 mypid = (uint32)sys_getpid();
1715 size_t i;
1716 bool ret = False;
1718 /* if ( snum == -1 ), we are deregister a print server handle
1719 which means to deregister on all print queues */
1721 if (snum == -1)
1723 int num_services = lp_numservices();
1724 int idx;
1726 for ( idx=0; idx<num_services; idx++ ) {
1727 if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1728 print_notify_deregister_pid(idx);
1731 return True;
1733 else /* deregister a specific printer */
1735 printername = lp_const_servicename(snum);
1736 pdb = get_print_db_byname(printername);
1737 if (!pdb)
1738 return False;
1739 tdb = pdb->tdb;
1742 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1743 DEBUG(0,("print_notify_register_pid: Failed to lock \
1744 printer %s database\n", printername));
1745 if (pdb)
1746 release_print_db(pdb);
1747 return False;
1750 data = get_printer_notify_pid_list( tdb, printername, True );
1752 /* Reduce refcount. Remove ourselves if zero. */
1754 for (i = 0; i < data.dsize; ) {
1755 if (IVAL(data.dptr,i) == mypid) {
1756 uint32 refcount = IVAL(data.dptr, i+4);
1758 refcount--;
1760 if (refcount == 0) {
1761 if (data.dsize - i > 8)
1762 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1763 data.dsize -= 8;
1764 continue;
1766 SIVAL(data.dptr, i+4, refcount);
1769 i += 8;
1772 if (data.dsize == 0)
1773 SAFE_FREE(data.dptr);
1775 /* Store back the record. */
1776 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1777 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1778 list for printer %s\n", printername));
1779 goto done;
1782 ret = True;
1784 done:
1786 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1787 if (pdb)
1788 release_print_db(pdb);
1789 SAFE_FREE(data.dptr);
1790 return ret;
1793 /****************************************************************************
1794 Check if a jobid is valid. It is valid if it exists in the database.
1795 ****************************************************************************/
1797 bool print_job_exists(const char* sharename, uint32 jobid)
1799 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1800 bool ret;
1801 uint32_t tmp;
1803 if (!pdb)
1804 return False;
1805 ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
1806 release_print_db(pdb);
1807 return ret;
1810 /****************************************************************************
1811 Give the fd used for a jobid.
1812 ****************************************************************************/
1814 int print_job_fd(const char* sharename, uint32 jobid)
1816 struct printjob *pjob = print_job_find(sharename, jobid);
1817 if (!pjob)
1818 return -1;
1819 /* don't allow another process to get this info - it is meaningless */
1820 if (pjob->pid != sys_getpid())
1821 return -1;
1822 return pjob->fd;
1825 /****************************************************************************
1826 Give the filename used for a jobid.
1827 Only valid for the process doing the spooling and when the job
1828 has not been spooled.
1829 ****************************************************************************/
1831 char *print_job_fname(const char* sharename, uint32 jobid)
1833 struct printjob *pjob = print_job_find(sharename, jobid);
1834 if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
1835 return NULL;
1836 return pjob->filename;
1840 /****************************************************************************
1841 Give the filename used for a jobid.
1842 Only valid for the process doing the spooling and when the job
1843 has not been spooled.
1844 ****************************************************************************/
1846 NT_DEVICEMODE *print_job_devmode(const char* sharename, uint32 jobid)
1848 struct printjob *pjob = print_job_find(sharename, jobid);
1850 if ( !pjob )
1851 return NULL;
1853 return pjob->nt_devmode;
1856 /****************************************************************************
1857 Set the place in the queue for a job.
1858 ****************************************************************************/
1860 bool print_job_set_place(const char *sharename, uint32 jobid, int place)
1862 DEBUG(2,("print_job_set_place not implemented yet\n"));
1863 return False;
1866 /****************************************************************************
1867 Set the name of a job. Only possible for owner.
1868 ****************************************************************************/
1870 bool print_job_set_name(const char *sharename, uint32 jobid, char *name)
1872 struct printjob *pjob;
1874 pjob = print_job_find(sharename, jobid);
1875 if (!pjob || pjob->pid != sys_getpid())
1876 return False;
1878 fstrcpy(pjob->jobname, name);
1879 return pjob_store(sharename, jobid, pjob);
1882 /***************************************************************************
1883 Remove a jobid from the 'jobs changed' list.
1884 ***************************************************************************/
1886 static bool remove_from_jobs_changed(const char* sharename, uint32 jobid)
1888 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1889 TDB_DATA data, key;
1890 size_t job_count, i;
1891 bool ret = False;
1892 bool gotlock = False;
1894 if (!pdb) {
1895 return False;
1898 ZERO_STRUCT(data);
1900 key = string_tdb_data("INFO/jobs_changed");
1902 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
1903 goto out;
1905 gotlock = True;
1907 data = tdb_fetch(pdb->tdb, key);
1909 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
1910 goto out;
1912 job_count = data.dsize / 4;
1913 for (i = 0; i < job_count; i++) {
1914 uint32 ch_jobid;
1916 ch_jobid = IVAL(data.dptr, i*4);
1917 if (ch_jobid == jobid) {
1918 if (i < job_count -1 )
1919 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
1920 data.dsize -= 4;
1921 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
1922 goto out;
1923 break;
1927 ret = True;
1928 out:
1930 if (gotlock)
1931 tdb_chainunlock(pdb->tdb, key);
1932 SAFE_FREE(data.dptr);
1933 release_print_db(pdb);
1934 if (ret)
1935 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
1936 else
1937 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
1938 return ret;
1941 /****************************************************************************
1942 Delete a print job - don't update queue.
1943 ****************************************************************************/
1945 static bool print_job_delete1(int snum, uint32 jobid)
1947 const char* sharename = lp_const_servicename(snum);
1948 struct printjob *pjob = print_job_find(sharename, jobid);
1949 int result = 0;
1950 struct printif *current_printif = get_printer_fns( snum );
1952 if (!pjob)
1953 return False;
1956 * If already deleting just return.
1959 if (pjob->status == LPQ_DELETING)
1960 return True;
1962 /* Hrm - we need to be able to cope with deleting a job before it
1963 has reached the spooler. Just mark it as LPQ_DELETING and
1964 let the print_queue_update() code rmeove the record */
1967 if (pjob->sysjob == -1) {
1968 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
1971 /* Set the tdb entry to be deleting. */
1973 pjob->status = LPQ_DELETING;
1974 pjob_store(sharename, jobid, pjob);
1976 if (pjob->spooled && pjob->sysjob != -1)
1978 result = (*(current_printif->job_delete))(
1979 PRINTERNAME(snum),
1980 lp_lprmcommand(snum),
1981 pjob);
1983 /* Delete the tdb entry if the delete succeeded or the job hasn't
1984 been spooled. */
1986 if (result == 0) {
1987 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1988 int njobs = 1;
1990 if (!pdb)
1991 return False;
1992 pjob_delete(sharename, jobid);
1993 /* Ensure we keep a rough count of the number of total jobs... */
1994 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
1995 release_print_db(pdb);
1999 remove_from_jobs_changed( sharename, jobid );
2001 return (result == 0);
2004 /****************************************************************************
2005 Return true if the current user owns the print job.
2006 ****************************************************************************/
2008 static bool is_owner(struct auth_serversupplied_info *server_info,
2009 const char *servicename,
2010 uint32 jobid)
2012 struct printjob *pjob = print_job_find(servicename, jobid);
2014 if (!pjob || !server_info)
2015 return False;
2017 return strequal(pjob->user, server_info->sanitized_username);
2020 /****************************************************************************
2021 Delete a print job.
2022 ****************************************************************************/
2024 bool print_job_delete(struct auth_serversupplied_info *server_info, int snum,
2025 uint32 jobid, WERROR *errcode)
2027 const char* sharename = lp_const_servicename( snum );
2028 struct printjob *pjob;
2029 bool owner;
2030 char *fname;
2032 *errcode = WERR_OK;
2034 owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2036 /* Check access against security descriptor or whether the user
2037 owns their job. */
2039 if (!owner &&
2040 !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2041 DEBUG(3, ("delete denied by security descriptor\n"));
2042 *errcode = WERR_ACCESS_DENIED;
2044 /* BEGIN_ADMIN_LOG */
2045 sys_adminlog( LOG_ERR,
2046 "Permission denied-- user not allowed to delete, \
2047 pause, or resume print job. User name: %s. Printer name: %s.",
2048 uidtoname(server_info->utok.uid),
2049 PRINTERNAME(snum) );
2050 /* END_ADMIN_LOG */
2052 return False;
2056 * get the spooled filename of the print job
2057 * if this works, then the file has not been spooled
2058 * to the underlying print system. Just delete the
2059 * spool file & return.
2062 if ( (fname = print_job_fname( sharename, jobid )) != NULL )
2064 /* remove the spool file */
2065 DEBUG(10,("print_job_delete: Removing spool file [%s]\n", fname ));
2066 if ( unlink( fname ) == -1 ) {
2067 *errcode = map_werror_from_unix(errno);
2068 return False;
2072 if (!print_job_delete1(snum, jobid)) {
2073 *errcode = WERR_ACCESS_DENIED;
2074 return False;
2077 /* force update the database and say the delete failed if the
2078 job still exists */
2080 print_queue_update(snum, True);
2082 pjob = print_job_find(sharename, jobid);
2083 if ( pjob && (pjob->status != LPQ_DELETING) )
2084 *errcode = WERR_ACCESS_DENIED;
2086 return (pjob == NULL );
2089 /****************************************************************************
2090 Pause a job.
2091 ****************************************************************************/
2093 bool print_job_pause(struct auth_serversupplied_info *server_info, int snum,
2094 uint32 jobid, WERROR *errcode)
2096 const char* sharename = lp_const_servicename(snum);
2097 struct printjob *pjob;
2098 int ret = -1;
2099 struct printif *current_printif = get_printer_fns( snum );
2101 pjob = print_job_find(sharename, jobid);
2103 if (!pjob || !server_info) {
2104 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2105 (unsigned int)jobid ));
2106 return False;
2109 if (!pjob->spooled || pjob->sysjob == -1) {
2110 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2111 (int)pjob->sysjob, (unsigned int)jobid ));
2112 return False;
2115 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2116 !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2117 DEBUG(3, ("pause denied by security descriptor\n"));
2119 /* BEGIN_ADMIN_LOG */
2120 sys_adminlog( LOG_ERR,
2121 "Permission denied-- user not allowed to delete, \
2122 pause, or resume print job. User name: %s. Printer name: %s.",
2123 uidtoname(server_info->utok.uid),
2124 PRINTERNAME(snum) );
2125 /* END_ADMIN_LOG */
2127 *errcode = WERR_ACCESS_DENIED;
2128 return False;
2131 /* need to pause the spooled entry */
2132 ret = (*(current_printif->job_pause))(snum, pjob);
2134 if (ret != 0) {
2135 *errcode = WERR_INVALID_PARAM;
2136 return False;
2139 /* force update the database */
2140 print_cache_flush(lp_const_servicename(snum));
2142 /* Send a printer notify message */
2144 notify_job_status(sharename, jobid, JOB_STATUS_PAUSED);
2146 /* how do we tell if this succeeded? */
2148 return True;
2151 /****************************************************************************
2152 Resume a job.
2153 ****************************************************************************/
2155 bool print_job_resume(struct auth_serversupplied_info *server_info, int snum,
2156 uint32 jobid, WERROR *errcode)
2158 const char *sharename = lp_const_servicename(snum);
2159 struct printjob *pjob;
2160 int ret;
2161 struct printif *current_printif = get_printer_fns( snum );
2163 pjob = print_job_find(sharename, jobid);
2165 if (!pjob || !server_info) {
2166 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2167 (unsigned int)jobid ));
2168 return False;
2171 if (!pjob->spooled || pjob->sysjob == -1) {
2172 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2173 (int)pjob->sysjob, (unsigned int)jobid ));
2174 return False;
2177 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2178 !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2179 DEBUG(3, ("resume denied by security descriptor\n"));
2180 *errcode = WERR_ACCESS_DENIED;
2182 /* BEGIN_ADMIN_LOG */
2183 sys_adminlog( LOG_ERR,
2184 "Permission denied-- user not allowed to delete, \
2185 pause, or resume print job. User name: %s. Printer name: %s.",
2186 uidtoname(server_info->utok.uid),
2187 PRINTERNAME(snum) );
2188 /* END_ADMIN_LOG */
2189 return False;
2192 ret = (*(current_printif->job_resume))(snum, pjob);
2194 if (ret != 0) {
2195 *errcode = WERR_INVALID_PARAM;
2196 return False;
2199 /* force update the database */
2200 print_cache_flush(lp_const_servicename(snum));
2202 /* Send a printer notify message */
2204 notify_job_status(sharename, jobid, JOB_STATUS_QUEUED);
2206 return True;
2209 /****************************************************************************
2210 Write to a print file.
2211 ****************************************************************************/
2213 ssize_t print_job_write(int snum, uint32 jobid, const char *buf, SMB_OFF_T pos, size_t size)
2215 const char* sharename = lp_const_servicename(snum);
2216 ssize_t return_code;
2217 struct printjob *pjob;
2219 pjob = print_job_find(sharename, jobid);
2221 if (!pjob)
2222 return -1;
2223 /* don't allow another process to get this info - it is meaningless */
2224 if (pjob->pid != sys_getpid())
2225 return -1;
2227 return_code = write_data_at_offset(pjob->fd, buf, size, pos);
2229 if (return_code>0) {
2230 pjob->size += size;
2231 pjob_store(sharename, jobid, pjob);
2233 return return_code;
2236 /****************************************************************************
2237 Get the queue status - do not update if db is out of date.
2238 ****************************************************************************/
2240 static int get_queue_status(const char* sharename, print_status_struct *status)
2242 fstring keystr;
2243 TDB_DATA data;
2244 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2245 int len;
2247 if (status) {
2248 ZERO_STRUCTP(status);
2251 if (!pdb)
2252 return 0;
2254 if (status) {
2255 fstr_sprintf(keystr, "STATUS/%s", sharename);
2256 data = tdb_fetch(pdb->tdb, string_tdb_data(keystr));
2257 if (data.dptr) {
2258 if (data.dsize == sizeof(print_status_struct))
2259 /* this memcpy is ok since the status struct was
2260 not packed before storing it in the tdb */
2261 memcpy(status, data.dptr, sizeof(print_status_struct));
2262 SAFE_FREE(data.dptr);
2265 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2266 release_print_db(pdb);
2267 return (len == -1 ? 0 : len);
2270 /****************************************************************************
2271 Determine the number of jobs in a queue.
2272 ****************************************************************************/
2274 int print_queue_length(int snum, print_status_struct *pstatus)
2276 const char* sharename = lp_const_servicename( snum );
2277 print_status_struct status;
2278 int len;
2280 ZERO_STRUCT( status );
2282 /* make sure the database is up to date */
2283 if (print_cache_expired(lp_const_servicename(snum), True))
2284 print_queue_update(snum, False);
2286 /* also fetch the queue status */
2287 memset(&status, 0, sizeof(status));
2288 len = get_queue_status(sharename, &status);
2290 if (pstatus)
2291 *pstatus = status;
2293 return len;
2296 /***************************************************************************
2297 Allocate a jobid. Hold the lock for as short a time as possible.
2298 ***************************************************************************/
2300 static bool allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char *sharename, uint32 *pjobid)
2302 int i;
2303 uint32 jobid;
2305 *pjobid = (uint32)-1;
2307 for (i = 0; i < 3; i++) {
2308 /* Lock the database - only wait 20 seconds. */
2309 if (tdb_lock_bystring_with_timeout(pdb->tdb, "INFO/nextjob", 20) == -1) {
2310 DEBUG(0,("allocate_print_jobid: failed to lock printing database %s\n", sharename));
2311 return False;
2314 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2315 if (tdb_error(pdb->tdb) != TDB_ERR_NOEXIST) {
2316 DEBUG(0, ("allocate_print_jobid: failed to fetch INFO/nextjob for print queue %s\n",
2317 sharename));
2318 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2319 return False;
2321 DEBUG(10,("allocate_print_jobid: no existing jobid in %s\n", sharename));
2322 jobid = 0;
2325 DEBUG(10,("allocate_print_jobid: read jobid %u from %s\n", jobid, sharename));
2327 jobid = NEXT_JOBID(jobid);
2329 if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
2330 DEBUG(3, ("allocate_print_jobid: failed to store INFO/nextjob.\n"));
2331 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2332 return False;
2335 /* We've finished with the INFO/nextjob lock. */
2336 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2338 if (!print_job_exists(sharename, jobid)) {
2339 break;
2341 DEBUG(10,("allocate_print_jobid: found jobid %u in %s\n", jobid, sharename));
2344 if (i > 2) {
2345 DEBUG(0, ("allocate_print_jobid: failed to allocate a print job for queue %s\n",
2346 sharename));
2347 /* Probably full... */
2348 errno = ENOSPC;
2349 return False;
2352 /* Store a dummy placeholder. */
2354 uint32_t tmp;
2355 TDB_DATA dum;
2356 dum.dptr = NULL;
2357 dum.dsize = 0;
2358 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2359 TDB_INSERT) == -1) {
2360 DEBUG(3, ("allocate_print_jobid: jobid (%d) failed to store placeholder.\n",
2361 jobid ));
2362 return False;
2366 *pjobid = jobid;
2367 return True;
2370 /***************************************************************************
2371 Append a jobid to the 'jobs changed' list.
2372 ***************************************************************************/
2374 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32 jobid)
2376 TDB_DATA data;
2377 uint32 store_jobid;
2379 SIVAL(&store_jobid, 0, jobid);
2380 data.dptr = (uint8 *)&store_jobid;
2381 data.dsize = 4;
2383 DEBUG(10,("add_to_jobs_changed: Added jobid %u\n", (unsigned int)jobid ));
2385 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
2386 data) == 0);
2389 /***************************************************************************
2390 Start spooling a job - return the jobid.
2391 ***************************************************************************/
2393 uint32 print_job_start(struct auth_serversupplied_info *server_info, int snum,
2394 const char *jobname, NT_DEVICEMODE *nt_devmode )
2396 uint32 jobid;
2397 char *path;
2398 struct printjob pjob;
2399 const char *sharename = lp_const_servicename(snum);
2400 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2401 int njobs;
2403 errno = 0;
2405 if (!pdb)
2406 return (uint32)-1;
2408 if (!print_access_check(server_info, snum, PRINTER_ACCESS_USE)) {
2409 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
2410 release_print_db(pdb);
2411 return (uint32)-1;
2414 if (!print_time_access_check(lp_servicename(snum))) {
2415 DEBUG(3, ("print_job_start: job start denied by time check\n"));
2416 release_print_db(pdb);
2417 return (uint32)-1;
2420 path = lp_pathname(snum);
2422 /* see if we have sufficient disk space */
2423 if (lp_minprintspace(snum)) {
2424 uint64_t dspace, dsize;
2425 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
2426 dspace < 2*(uint64_t)lp_minprintspace(snum)) {
2427 DEBUG(3, ("print_job_start: disk space check failed.\n"));
2428 release_print_db(pdb);
2429 errno = ENOSPC;
2430 return (uint32)-1;
2434 /* for autoloaded printers, check that the printcap entry still exists */
2435 if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum))) {
2436 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
2437 release_print_db(pdb);
2438 errno = ENOENT;
2439 return (uint32)-1;
2442 /* Insure the maximum queue size is not violated */
2443 if ((njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
2444 DEBUG(3, ("print_job_start: Queue %s number of jobs (%d) larger than max printjobs per queue (%d).\n",
2445 sharename, njobs, lp_maxprintjobs(snum) ));
2446 release_print_db(pdb);
2447 errno = ENOSPC;
2448 return (uint32)-1;
2451 DEBUG(10,("print_job_start: Queue %s number of jobs (%d), max printjobs = %d\n",
2452 sharename, njobs, lp_maxprintjobs(snum) ));
2454 if (!allocate_print_jobid(pdb, snum, sharename, &jobid))
2455 goto fail;
2457 /* create the database entry */
2459 ZERO_STRUCT(pjob);
2461 pjob.pid = sys_getpid();
2462 pjob.sysjob = -1;
2463 pjob.fd = -1;
2464 pjob.starttime = time(NULL);
2465 pjob.status = LPQ_SPOOLING;
2466 pjob.size = 0;
2467 pjob.spooled = False;
2468 pjob.smbjob = True;
2469 pjob.nt_devmode = nt_devmode;
2471 fstrcpy(pjob.jobname, jobname);
2473 fstrcpy(pjob.user, lp_printjob_username(snum));
2474 standard_sub_advanced(sharename, server_info->sanitized_username,
2475 path, server_info->utok.gid,
2476 server_info->sanitized_username,
2477 pdb_get_domain(server_info->sam_account),
2478 pjob.user, sizeof(pjob.user)-1);
2479 /* ensure NULL termination */
2480 pjob.user[sizeof(pjob.user)-1] = '\0';
2482 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2484 /* we have a job entry - now create the spool file */
2485 slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX",
2486 path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2487 pjob.fd = mkstemp(pjob.filename);
2489 if (pjob.fd == -1) {
2490 if (errno == EACCES) {
2491 /* Common setup error, force a report. */
2492 DEBUG(0, ("print_job_start: insufficient permissions \
2493 to open spool file %s.\n", pjob.filename));
2494 } else {
2495 /* Normal case, report at level 3 and above. */
2496 DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
2497 DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
2499 goto fail;
2502 pjob_store(sharename, jobid, &pjob);
2504 /* Update the 'jobs changed' entry used by print_queue_status. */
2505 add_to_jobs_changed(pdb, jobid);
2507 /* Ensure we keep a rough count of the number of total jobs... */
2508 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2510 release_print_db(pdb);
2512 return jobid;
2514 fail:
2515 if (jobid != -1)
2516 pjob_delete(sharename, jobid);
2518 release_print_db(pdb);
2520 DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
2521 return (uint32)-1;
2524 /****************************************************************************
2525 Update the number of pages spooled to jobid
2526 ****************************************************************************/
2528 void print_job_endpage(int snum, uint32 jobid)
2530 const char* sharename = lp_const_servicename(snum);
2531 struct printjob *pjob;
2533 pjob = print_job_find(sharename, jobid);
2534 if (!pjob)
2535 return;
2536 /* don't allow another process to get this info - it is meaningless */
2537 if (pjob->pid != sys_getpid())
2538 return;
2540 pjob->page_count++;
2541 pjob_store(sharename, jobid, pjob);
2544 /****************************************************************************
2545 Print a file - called on closing the file. This spools the job.
2546 If normal close is false then we're tearing down the jobs - treat as an
2547 error.
2548 ****************************************************************************/
2550 bool print_job_end(int snum, uint32 jobid, enum file_close_type close_type)
2552 const char* sharename = lp_const_servicename(snum);
2553 struct printjob *pjob;
2554 int ret;
2555 SMB_STRUCT_STAT sbuf;
2556 struct printif *current_printif = get_printer_fns( snum );
2558 pjob = print_job_find(sharename, jobid);
2560 if (!pjob)
2561 return False;
2563 if (pjob->spooled || pjob->pid != sys_getpid())
2564 return False;
2566 if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
2567 (sys_fstat(pjob->fd, &sbuf, false) == 0)) {
2568 pjob->size = sbuf.st_ex_size;
2569 close(pjob->fd);
2570 pjob->fd = -1;
2571 } else {
2574 * Not a normal close or we couldn't stat the job file,
2575 * so something has gone wrong. Cleanup.
2577 close(pjob->fd);
2578 pjob->fd = -1;
2579 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
2580 goto fail;
2583 /* Technically, this is not quite right. If the printer has a separator
2584 * page turned on, the NT spooler prints the separator page even if the
2585 * print job is 0 bytes. 010215 JRR */
2586 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
2587 /* don't bother spooling empty files or something being deleted. */
2588 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
2589 pjob->filename, pjob->size ? "deleted" : "zero length" ));
2590 unlink(pjob->filename);
2591 pjob_delete(sharename, jobid);
2592 return True;
2595 pjob->smbjob = jobid;
2597 ret = (*(current_printif->job_submit))(snum, pjob);
2599 if (ret)
2600 goto fail;
2602 /* The print job has been successfully handed over to the back-end */
2604 pjob->spooled = True;
2605 pjob->status = LPQ_QUEUED;
2606 pjob_store(sharename, jobid, pjob);
2608 /* make sure the database is up to date */
2609 if (print_cache_expired(lp_const_servicename(snum), True))
2610 print_queue_update(snum, False);
2612 return True;
2614 fail:
2616 /* The print job was not successfully started. Cleanup */
2617 /* Still need to add proper error return propagation! 010122:JRR */
2618 unlink(pjob->filename);
2619 pjob_delete(sharename, jobid);
2620 return False;
2623 /****************************************************************************
2624 Get a snapshot of jobs in the system without traversing.
2625 ****************************************************************************/
2627 static bool get_stored_queue_info(struct tdb_print_db *pdb, int snum, int *pcount, print_queue_struct **ppqueue)
2629 TDB_DATA data, cgdata;
2630 print_queue_struct *queue = NULL;
2631 uint32 qcount = 0;
2632 uint32 extra_count = 0;
2633 int total_count = 0;
2634 size_t len = 0;
2635 uint32 i;
2636 int max_reported_jobs = lp_max_reported_jobs(snum);
2637 bool ret = False;
2638 const char* sharename = lp_servicename(snum);
2640 /* make sure the database is up to date */
2641 if (print_cache_expired(lp_const_servicename(snum), True))
2642 print_queue_update(snum, False);
2644 *pcount = 0;
2645 *ppqueue = NULL;
2647 ZERO_STRUCT(data);
2648 ZERO_STRUCT(cgdata);
2650 /* Get the stored queue data. */
2651 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
2653 if (data.dptr && data.dsize >= sizeof(qcount))
2654 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
2656 /* Get the changed jobs list. */
2657 cgdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
2658 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
2659 extra_count = cgdata.dsize/4;
2661 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
2663 /* Allocate the queue size. */
2664 if (qcount == 0 && extra_count == 0)
2665 goto out;
2667 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
2668 goto out;
2670 /* Retrieve the linearised queue data. */
2672 for( i = 0; i < qcount; i++) {
2673 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
2674 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
2675 &qjob,
2676 &qsize,
2677 &qpage_count,
2678 &qstatus,
2679 &qpriority,
2680 &qtime,
2681 queue[i].fs_user,
2682 queue[i].fs_file);
2683 queue[i].job = qjob;
2684 queue[i].size = qsize;
2685 queue[i].page_count = qpage_count;
2686 queue[i].status = qstatus;
2687 queue[i].priority = qpriority;
2688 queue[i].time = qtime;
2691 total_count = qcount;
2693 /* Add in the changed jobids. */
2694 for( i = 0; i < extra_count; i++) {
2695 uint32 jobid;
2696 struct printjob *pjob;
2698 jobid = IVAL(cgdata.dptr, i*4);
2699 DEBUG(5,("get_stored_queue_info: changed job = %u\n", (unsigned int)jobid));
2700 pjob = print_job_find(lp_const_servicename(snum), jobid);
2701 if (!pjob) {
2702 DEBUG(5,("get_stored_queue_info: failed to find changed job = %u\n", (unsigned int)jobid));
2703 remove_from_jobs_changed(sharename, jobid);
2704 continue;
2707 queue[total_count].job = jobid;
2708 queue[total_count].size = pjob->size;
2709 queue[total_count].page_count = pjob->page_count;
2710 queue[total_count].status = pjob->status;
2711 queue[total_count].priority = 1;
2712 queue[total_count].time = pjob->starttime;
2713 fstrcpy(queue[total_count].fs_user, pjob->user);
2714 fstrcpy(queue[total_count].fs_file, pjob->jobname);
2715 total_count++;
2718 /* Sort the queue by submission time otherwise they are displayed
2719 in hash order. */
2721 TYPESAFE_QSORT(queue, total_count, printjob_comp);
2723 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
2725 if (max_reported_jobs && total_count > max_reported_jobs)
2726 total_count = max_reported_jobs;
2728 *ppqueue = queue;
2729 *pcount = total_count;
2731 ret = True;
2733 out:
2735 SAFE_FREE(data.dptr);
2736 SAFE_FREE(cgdata.dptr);
2737 return ret;
2740 /****************************************************************************
2741 Get a printer queue listing.
2742 set queue = NULL and status = NULL if you just want to update the cache
2743 ****************************************************************************/
2745 int print_queue_status(int snum,
2746 print_queue_struct **ppqueue,
2747 print_status_struct *status)
2749 fstring keystr;
2750 TDB_DATA data, key;
2751 const char *sharename;
2752 struct tdb_print_db *pdb;
2753 int count = 0;
2755 /* make sure the database is up to date */
2757 if (print_cache_expired(lp_const_servicename(snum), True))
2758 print_queue_update(snum, False);
2760 /* return if we are done */
2761 if ( !ppqueue || !status )
2762 return 0;
2764 *ppqueue = NULL;
2765 sharename = lp_const_servicename(snum);
2766 pdb = get_print_db_byname(sharename);
2768 if (!pdb)
2769 return 0;
2772 * Fetch the queue status. We must do this first, as there may
2773 * be no jobs in the queue.
2776 ZERO_STRUCTP(status);
2777 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
2778 key = string_tdb_data(keystr);
2780 data = tdb_fetch(pdb->tdb, key);
2781 if (data.dptr) {
2782 if (data.dsize == sizeof(*status)) {
2783 /* this memcpy is ok since the status struct was
2784 not packed before storing it in the tdb */
2785 memcpy(status, data.dptr, sizeof(*status));
2787 SAFE_FREE(data.dptr);
2791 * Now, fetch the print queue information. We first count the number
2792 * of entries, and then only retrieve the queue if necessary.
2795 if (!get_stored_queue_info(pdb, snum, &count, ppqueue)) {
2796 release_print_db(pdb);
2797 return 0;
2800 release_print_db(pdb);
2801 return count;
2804 /****************************************************************************
2805 Pause a queue.
2806 ****************************************************************************/
2808 WERROR print_queue_pause(struct auth_serversupplied_info *server_info, int snum)
2810 int ret;
2811 struct printif *current_printif = get_printer_fns( snum );
2813 if (!print_access_check(server_info, snum,
2814 PRINTER_ACCESS_ADMINISTER)) {
2815 return WERR_ACCESS_DENIED;
2819 become_root();
2821 ret = (*(current_printif->queue_pause))(snum);
2823 unbecome_root();
2825 if (ret != 0) {
2826 return WERR_INVALID_PARAM;
2829 /* force update the database */
2830 print_cache_flush(lp_const_servicename(snum));
2832 /* Send a printer notify message */
2834 notify_printer_status(snum, PRINTER_STATUS_PAUSED);
2836 return WERR_OK;
2839 /****************************************************************************
2840 Resume a queue.
2841 ****************************************************************************/
2843 WERROR print_queue_resume(struct auth_serversupplied_info *server_info, int snum)
2845 int ret;
2846 struct printif *current_printif = get_printer_fns( snum );
2848 if (!print_access_check(server_info, snum,
2849 PRINTER_ACCESS_ADMINISTER)) {
2850 return WERR_ACCESS_DENIED;
2853 become_root();
2855 ret = (*(current_printif->queue_resume))(snum);
2857 unbecome_root();
2859 if (ret != 0) {
2860 return WERR_INVALID_PARAM;
2863 /* make sure the database is up to date */
2864 if (print_cache_expired(lp_const_servicename(snum), True))
2865 print_queue_update(snum, True);
2867 /* Send a printer notify message */
2869 notify_printer_status(snum, PRINTER_STATUS_OK);
2871 return WERR_OK;
2874 /****************************************************************************
2875 Purge a queue - implemented by deleting all jobs that we can delete.
2876 ****************************************************************************/
2878 WERROR print_queue_purge(struct auth_serversupplied_info *server_info, int snum)
2880 print_queue_struct *queue;
2881 print_status_struct status;
2882 int njobs, i;
2883 bool can_job_admin;
2885 /* Force and update so the count is accurate (i.e. not a cached count) */
2886 print_queue_update(snum, True);
2888 can_job_admin = print_access_check(server_info, snum,
2889 JOB_ACCESS_ADMINISTER);
2890 njobs = print_queue_status(snum, &queue, &status);
2892 if ( can_job_admin )
2893 become_root();
2895 for (i=0;i<njobs;i++) {
2896 bool owner = is_owner(server_info, lp_const_servicename(snum),
2897 queue[i].job);
2899 if (owner || can_job_admin) {
2900 print_job_delete1(snum, queue[i].job);
2904 if ( can_job_admin )
2905 unbecome_root();
2907 /* update the cache */
2908 print_queue_update( snum, True );
2910 SAFE_FREE(queue);
2912 return WERR_OK;