2 Unix SMB/Netbios implementation.
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 2 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, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 extern SIG_ATOMIC_T got_sig_term;
27 extern SIG_ATOMIC_T reload_after_sighup;
29 /* Current printer interface */
30 static BOOL remove_from_jobs_changed(const char* sharename, uint32 jobid);
33 the printing backend revolves around a tdb database that stores the
34 SMB view of the print queue
36 The key for this database is a jobid - a internally generated number that
37 uniquely identifies a print job
39 reading the print queue involves two steps:
40 - possibly running lpq and updating the internal database from that
41 - reading entries from the database
43 jobids are assigned when a job starts spooling.
46 static TDB_CONTEXT *rap_tdb;
47 static uint16 next_rap_jobid;
48 struct rap_jobid_key {
53 /***************************************************************************
54 Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
55 bit RPC jobids.... JRA.
56 ***************************************************************************/
58 uint16 pjobid_to_rap(const char* sharename, uint32 jobid)
62 struct rap_jobid_key jinfo;
65 DEBUG(10,("pjobid_to_rap: called.\n"));
68 /* Create the in-memory tdb. */
69 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
75 fstrcpy( jinfo.sharename, sharename );
77 key.dptr = (char*)&jinfo;
78 key.dsize = sizeof(jinfo);
80 data = tdb_fetch(rap_tdb, key);
81 if (data.dptr && data.dsize == sizeof(uint16)) {
82 rap_jobid = SVAL(data.dptr, 0);
84 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
85 (unsigned int)jobid, (unsigned int)rap_jobid));
89 /* Not found - create and store mapping. */
90 rap_jobid = ++next_rap_jobid;
92 rap_jobid = ++next_rap_jobid;
93 SSVAL(buf,0,rap_jobid);
95 data.dsize = sizeof(rap_jobid);
96 tdb_store(rap_tdb, key, data, TDB_REPLACE);
97 tdb_store(rap_tdb, data, key, TDB_REPLACE);
99 DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
100 (unsigned int)jobid, (unsigned int)rap_jobid));
104 BOOL rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
109 DEBUG(10,("rap_to_pjobid called.\n"));
114 SSVAL(buf,0,rap_jobid);
116 key.dsize = sizeof(rap_jobid);
117 data = tdb_fetch(rap_tdb, key);
118 if ( data.dptr && data.dsize == sizeof(struct rap_jobid_key) )
120 struct rap_jobid_key *jinfo = (struct rap_jobid_key*)data.dptr;
121 fstrcpy( sharename, jinfo->sharename );
122 *pjobid = jinfo->jobid;
123 DEBUG(10,("rap_to_pjobid: jobid %u maps to RAP jobid %u\n",
124 (unsigned int)*pjobid, (unsigned int)rap_jobid));
125 SAFE_FREE(data.dptr);
129 DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
130 (unsigned int)rap_jobid));
131 SAFE_FREE(data.dptr);
135 static void rap_jobid_delete(const char* sharename, uint32 jobid)
139 struct rap_jobid_key jinfo;
142 DEBUG(10,("rap_jobid_delete: called.\n"));
147 ZERO_STRUCT( jinfo );
148 fstrcpy( jinfo.sharename, sharename );
150 key.dptr = (char*)&jinfo;
151 key.dsize = sizeof(jinfo);
153 data = tdb_fetch(rap_tdb, key);
154 if (!data.dptr || (data.dsize != sizeof(uint16))) {
155 DEBUG(10,("rap_jobid_delete: cannot find jobid %u\n",
156 (unsigned int)jobid ));
157 SAFE_FREE(data.dptr);
161 DEBUG(10,("rap_jobid_delete: deleting jobid %u\n",
162 (unsigned int)jobid ));
164 rap_jobid = SVAL(data.dptr, 0);
165 SAFE_FREE(data.dptr);
166 SSVAL(buf,0,rap_jobid);
168 data.dsize = sizeof(rap_jobid);
169 tdb_delete(rap_tdb, key);
170 tdb_delete(rap_tdb, data);
173 static int get_queue_status(const char* sharename, print_status_struct *);
175 /****************************************************************************
176 Initialise the printing backend. Called once at startup before the fork().
177 ****************************************************************************/
179 BOOL print_backend_init(void)
181 const char *sversion = "INFO/version";
182 pstring printing_path;
183 int services = lp_numservices();
186 unlink(lock_path("printing.tdb"));
187 pstrcpy(printing_path,lock_path("printing"));
188 mkdir(printing_path,0755);
190 /* handle a Samba upgrade */
192 for (snum = 0; snum < services; snum++) {
193 struct tdb_print_db *pdb;
194 if (!lp_print_ok(snum))
197 pdb = get_print_db_byname(lp_const_servicename(snum));
200 if (tdb_lock_bystring(pdb->tdb, sversion, 0) == -1) {
201 DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
202 release_print_db(pdb);
205 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
206 tdb_traverse(pdb->tdb, tdb_traverse_delete_fn, NULL);
207 tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
209 tdb_unlock_bystring(pdb->tdb, sversion);
210 release_print_db(pdb);
213 close_all_print_db(); /* Don't leave any open. */
215 /* do NT print initialization... */
216 return nt_printing_init();
219 /****************************************************************************
220 Shut down printing backend. Called once at shutdown to close the tdb.
221 ****************************************************************************/
223 void printing_end(void)
225 close_all_print_db(); /* Don't leave any open. */
228 /****************************************************************************
229 Retrieve the set of printing functions for a given service. This allows
230 us to set the printer function table based on the value of the 'printing'
233 Use the generic interface as the default and only use cups interface only
234 when asked for (and only when supported)
235 ****************************************************************************/
237 static struct printif *get_printer_fns_from_type( int type )
239 struct printif *printer_fns = &generic_printif;
242 if ( type == PRINT_CUPS ) {
243 printer_fns = &cups_printif;
245 #endif /* HAVE_CUPS */
247 printer_fns->type = type;
252 static struct printif *get_printer_fns( int snum )
254 return get_printer_fns_from_type( lp_printing(snum) );
258 /****************************************************************************
259 Useful function to generate a tdb key.
260 ****************************************************************************/
262 static TDB_DATA print_key(uint32 jobid)
268 ret.dptr = (void *)&j;
269 ret.dsize = sizeof(j);
273 /***********************************************************************
274 unpack a pjob from a tdb buffer
275 ***********************************************************************/
277 int unpack_pjob( char* buf, int buflen, struct printjob *pjob )
281 uint32 pjpid, pjsysjob, pjfd, pjstarttime, pjstatus;
282 uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
287 len += tdb_unpack(buf+len, buflen-len, "dddddddddffff",
305 if ( (used = unpack_devicemode(&pjob->nt_devmode, buf+len, buflen-len)) == -1 )
311 pjob->sysjob = pjsysjob;
313 pjob->starttime = pjstarttime;
314 pjob->status = pjstatus;
316 pjob->page_count = pjpage_count;
317 pjob->spooled = pjspooled;
318 pjob->smbjob = pjsmbjob;
324 /****************************************************************************
325 Useful function to find a print job in the database.
326 ****************************************************************************/
328 static struct printjob *print_job_find(const char *sharename, uint32 jobid)
330 static struct printjob pjob;
332 struct tdb_print_db *pdb = get_print_db_byname(sharename);
338 ret = tdb_fetch(pdb->tdb, print_key(jobid));
339 release_print_db(pdb);
344 if ( pjob.nt_devmode )
345 free_nt_devicemode( &pjob.nt_devmode );
349 if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
358 /* Convert a unix jobid to a smb jobid */
360 static uint32 sysjob_to_jobid_value;
362 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
363 TDB_DATA data, void *state)
365 struct printjob *pjob;
366 int *sysjob = (int *)state;
368 if (!data.dptr || data.dsize == 0)
371 pjob = (struct printjob *)data.dptr;
372 if (key.dsize != sizeof(uint32))
375 if (*sysjob == pjob->sysjob) {
376 uint32 jobid = IVAL(key.dptr,0);
378 sysjob_to_jobid_value = jobid;
385 /****************************************************************************
386 This is a *horribly expensive call as we have to iterate through all the
387 current printer tdb's. Don't do this often ! JRA.
388 ****************************************************************************/
390 uint32 sysjob_to_jobid(int unix_jobid)
392 int services = lp_numservices();
395 sysjob_to_jobid_value = (uint32)-1;
397 for (snum = 0; snum < services; snum++) {
398 struct tdb_print_db *pdb;
399 if (!lp_print_ok(snum))
401 pdb = get_print_db_byname(lp_const_servicename(snum));
403 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &unix_jobid);
404 release_print_db(pdb);
405 if (sysjob_to_jobid_value != (uint32)-1)
406 return sysjob_to_jobid_value;
411 /****************************************************************************
412 Send notifications based on what has changed after a pjob_store.
413 ****************************************************************************/
417 uint32 spoolss_status;
418 } lpq_to_spoolss_status_map[] = {
419 { LPQ_QUEUED, JOB_STATUS_QUEUED },
420 { LPQ_PAUSED, JOB_STATUS_PAUSED },
421 { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
422 { LPQ_PRINTING, JOB_STATUS_PRINTING },
423 { LPQ_DELETING, JOB_STATUS_DELETING },
424 { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
425 { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
426 { LPQ_PRINTED, JOB_STATUS_PRINTED },
427 { LPQ_DELETED, JOB_STATUS_DELETED },
428 { LPQ_BLOCKED, JOB_STATUS_BLOCKED },
429 { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
433 /* Convert a lpq status value stored in printing.tdb into the
434 appropriate win32 API constant. */
436 static uint32 map_to_spoolss_status(uint32 lpq_status)
440 while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
441 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
442 return lpq_to_spoolss_status_map[i].spoolss_status;
449 static void pjob_store_notify(const char* sharename, uint32 jobid, struct printjob *old_data,
450 struct printjob *new_data)
452 BOOL new_job = False;
457 /* Job attributes that can't be changed. We only send
458 notification for these on a new job. */
460 /* ACHTUNG! Due to a bug in Samba's spoolss parsing of the
461 NOTIFY_INFO_DATA buffer, we *have* to send the job submission
462 time first or else we'll end up with potential alignment
463 errors. I don't think the systemtime should be spooled as
464 a string, but this gets us around that error.
465 --jerry (i'll feel dirty for this) */
468 notify_job_submitted(sharename, jobid, new_data->starttime);
469 notify_job_username(sharename, jobid, new_data->user);
472 if (new_job || !strequal(old_data->jobname, new_data->jobname))
473 notify_job_name(sharename, jobid, new_data->jobname);
475 /* Job attributes of a new job or attributes that can be
478 if (new_job || !strequal(old_data->jobname, new_data->jobname))
479 notify_job_name(sharename, jobid, new_data->jobname);
481 if (new_job || old_data->status != new_data->status)
482 notify_job_status(sharename, jobid, map_to_spoolss_status(new_data->status));
484 if (new_job || old_data->size != new_data->size)
485 notify_job_total_bytes(sharename, jobid, new_data->size);
487 if (new_job || old_data->page_count != new_data->page_count)
488 notify_job_total_pages(sharename, jobid, new_data->page_count);
491 /****************************************************************************
492 Store a job structure back to the database.
493 ****************************************************************************/
495 static BOOL pjob_store(const char* sharename, uint32 jobid, struct printjob *pjob)
497 TDB_DATA old_data, new_data;
499 struct tdb_print_db *pdb = get_print_db_byname(sharename);
501 int len, newlen, buflen;
509 old_data = tdb_fetch(pdb->tdb, print_key(jobid));
511 /* Doh! Now we have to pack/unpack data since the NT_DEVICEMODE was added */
518 len += tdb_pack(buf+len, buflen-len, "dddddddddffff",
520 (uint32)pjob->sysjob,
522 (uint32)pjob->starttime,
523 (uint32)pjob->status,
525 (uint32)pjob->page_count,
526 (uint32)pjob->spooled,
527 (uint32)pjob->smbjob,
533 len += pack_devicemode(pjob->nt_devmode, buf+len, buflen-len);
538 tb = (char *)SMB_REALLOC(buf, len);
540 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
547 } while ( buflen != len );
553 new_data.dsize = len;
554 ret = (tdb_store(pdb->tdb, print_key(jobid), new_data, TDB_REPLACE) == 0);
556 release_print_db(pdb);
558 /* Send notify updates for what has changed */
561 struct printjob old_pjob;
563 if ( old_data.dsize )
565 if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
567 pjob_store_notify( sharename, jobid, &old_pjob , pjob );
568 free_nt_devicemode( &old_pjob.nt_devmode );
573 pjob_store_notify( sharename, jobid, NULL, pjob );
578 SAFE_FREE( old_data.dptr );
584 /****************************************************************************
585 Remove a job structure from the database.
586 ****************************************************************************/
588 void pjob_delete(const char* sharename, uint32 jobid)
590 struct printjob *pjob;
591 uint32 job_status = 0;
592 struct tdb_print_db *pdb;
594 pdb = get_print_db_byname( sharename );
599 pjob = print_job_find( sharename, jobid );
602 DEBUG(5, ("pjob_delete: we were asked to delete nonexistent job %u\n",
603 (unsigned int)jobid));
604 release_print_db(pdb);
608 /* We must cycle through JOB_STATUS_DELETING and
609 JOB_STATUS_DELETED for the port monitor to delete the job
612 job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
613 notify_job_status(sharename, jobid, job_status);
615 /* Remove from printing.tdb */
617 tdb_delete(pdb->tdb, print_key(jobid));
618 remove_from_jobs_changed(sharename, jobid);
619 release_print_db( pdb );
620 rap_jobid_delete(sharename, jobid);
623 /****************************************************************************
624 Parse a file name from the system spooler to generate a jobid.
625 ****************************************************************************/
627 static uint32 print_parse_jobid(char *fname)
631 if (strncmp(fname,PRINT_SPOOL_PREFIX,strlen(PRINT_SPOOL_PREFIX)) != 0)
633 fname += strlen(PRINT_SPOOL_PREFIX);
639 return (uint32)jobid;
642 /****************************************************************************
643 List a unix job in the print database.
644 ****************************************************************************/
646 static void print_unix_job(const char *sharename, print_queue_struct *q, uint32 jobid)
648 struct printjob pj, *old_pj;
650 if (jobid == (uint32)-1)
651 jobid = q->job + UNIX_JOB_START;
653 /* Preserve the timestamp on an existing unix print job */
655 old_pj = print_job_find(sharename, jobid);
662 pj.starttime = old_pj ? old_pj->starttime : q->time;
663 pj.status = q->status;
666 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
667 if (jobid < UNIX_JOB_START) {
669 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
672 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
674 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
675 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
677 pjob_store(sharename, jobid, &pj);
681 struct traverse_struct {
682 print_queue_struct *queue;
683 int qcount, snum, maxcount, total_jobs;
684 const char *sharename;
688 /****************************************************************************
689 Utility fn to delete any jobs that are no longer active.
690 ****************************************************************************/
692 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
694 struct traverse_struct *ts = (struct traverse_struct *)state;
695 struct printjob pjob;
699 if ( key.dsize != sizeof(jobid) )
702 jobid = IVAL(key.dptr, 0);
703 if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
705 free_nt_devicemode( &pjob.nt_devmode );
709 /* remove a unix job if it isn't in the system queue any more */
711 for (i=0;i<ts->qcount;i++) {
712 uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
713 if (jobid == u_jobid)
716 if (i == ts->qcount) {
717 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
718 (unsigned int)jobid ));
719 pjob_delete(ts->sharename, jobid);
723 /* need to continue the the bottom of the function to
724 save the correct attributes */
727 /* maybe it hasn't been spooled yet */
729 /* if a job is not spooled and the process doesn't
730 exist then kill it. This cleans up after smbd
732 if (!process_exists(pjob.pid)) {
733 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
734 (unsigned int)jobid, (unsigned int)pjob.pid ));
735 pjob_delete(ts->sharename, jobid);
741 /* this check only makes sense for jobs submitted from Windows clients */
744 for (i=0;i<ts->qcount;i++) {
745 uint32 curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
746 if (jobid == curr_jobid)
751 /* The job isn't in the system queue - we have to assume it has
752 completed, so delete the database entry. */
754 if (i == ts->qcount) {
756 /* A race can occur between the time a job is spooled and
757 when it appears in the lpq output. This happens when
758 the job is added to printing.tdb when another smbd
759 running print_queue_update() has completed a lpq and
760 is currently traversing the printing tdb and deleting jobs.
761 Don't delete the job if it was submitted after the lpq_time. */
763 if (pjob.starttime < ts->lpq_time) {
764 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
766 (unsigned int)pjob.starttime,
767 (unsigned int)ts->lpq_time ));
768 pjob_delete(ts->sharename, jobid);
774 /* Save the pjob attributes we will store. */
775 /* FIXME!!! This is the only place where queue->job
776 represents the SMB jobid --jerry */
777 ts->queue[i].job = jobid;
778 ts->queue[i].size = pjob.size;
779 ts->queue[i].page_count = pjob.page_count;
780 ts->queue[i].status = pjob.status;
781 ts->queue[i].priority = 1;
782 ts->queue[i].time = pjob.starttime;
783 fstrcpy(ts->queue[i].fs_user, pjob.user);
784 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
791 /****************************************************************************
792 Check if the print queue has been updated recently enough.
793 ****************************************************************************/
795 static void print_cache_flush(int snum)
798 const char *sharename = lp_const_servicename(snum);
799 struct tdb_print_db *pdb = get_print_db_byname(sharename);
803 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
804 tdb_store_int32(pdb->tdb, key, -1);
805 release_print_db(pdb);
808 /****************************************************************************
809 Check if someone already thinks they are doing the update.
810 ****************************************************************************/
812 static pid_t get_updating_pid(const char *sharename)
817 struct tdb_print_db *pdb = get_print_db_byname(sharename);
821 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
823 key.dsize = strlen(keystr);
825 data = tdb_fetch(pdb->tdb, key);
826 release_print_db(pdb);
827 if (!data.dptr || data.dsize != sizeof(pid_t)) {
828 SAFE_FREE(data.dptr);
832 updating_pid = IVAL(data.dptr, 0);
833 SAFE_FREE(data.dptr);
835 if (process_exists(updating_pid))
841 /****************************************************************************
842 Set the fact that we're doing the update, or have finished doing the update
844 ****************************************************************************/
846 static void set_updating_pid(const fstring sharename, BOOL updating)
851 pid_t updating_pid = sys_getpid();
854 struct tdb_print_db *pdb = get_print_db_byname(sharename);
859 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
861 key.dsize = strlen(keystr);
863 DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
864 updating ? "" : "not ",
868 tdb_delete(pdb->tdb, key);
869 release_print_db(pdb);
873 SIVAL( buffer, 0, updating_pid);
874 data.dptr = (void *)buffer;
875 data.dsize = 4; /* we always assume this is a 4 byte value */
877 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
878 release_print_db(pdb);
881 /****************************************************************************
882 Sort print jobs by submittal time.
883 ****************************************************************************/
885 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
896 /* Sort on job start time */
898 if (j1->time == j2->time)
900 return (j1->time > j2->time) ? 1 : -1;
903 /****************************************************************************
904 Store the sorted queue representation for later portmon retrieval.
905 ****************************************************************************/
907 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
910 int max_reported_jobs = lp_max_reported_jobs(pts->snum);
911 print_queue_struct *queue = pts->queue;
916 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
917 pts->qcount = max_reported_jobs;
918 qcount = pts->qcount;
920 /* Work out the size. */
922 data.dsize += tdb_pack(NULL, 0, "d", qcount);
924 for (i = 0; i < pts->qcount; i++) {
925 data.dsize += tdb_pack(NULL, 0, "ddddddff",
926 (uint32)queue[i].job,
927 (uint32)queue[i].size,
928 (uint32)queue[i].page_count,
929 (uint32)queue[i].status,
930 (uint32)queue[i].priority,
931 (uint32)queue[i].time,
936 if ((data.dptr = SMB_MALLOC(data.dsize)) == NULL)
940 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
941 for (i = 0; i < pts->qcount; i++) {
942 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
943 (uint32)queue[i].job,
944 (uint32)queue[i].size,
945 (uint32)queue[i].page_count,
946 (uint32)queue[i].status,
947 (uint32)queue[i].priority,
948 (uint32)queue[i].time,
953 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
955 SAFE_FREE(data.dptr);
959 static TDB_DATA get_jobs_changed_data(struct tdb_print_db *pdb)
965 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
966 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
967 SAFE_FREE(data.dptr);
974 static void check_job_changed(const char *sharename, TDB_DATA data, uint32 jobid)
977 unsigned int job_count = data.dsize / 4;
979 for (i = 0; i < job_count; i++) {
982 ch_jobid = IVAL(data.dptr, i*4);
983 if (ch_jobid == jobid)
984 remove_from_jobs_changed(sharename, jobid);
988 /****************************************************************************
989 Check if the print queue has been updated recently enough.
990 ****************************************************************************/
992 static BOOL print_cache_expired(const char *sharename, BOOL check_pending)
995 time_t last_qscan_time, time_now = time(NULL);
996 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1002 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1003 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1006 * Invalidate the queue for 3 reasons.
1007 * (1). last queue scan time == -1.
1008 * (2). Current time - last queue scan time > allowed cache time.
1009 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1010 * This last test picks up machines for which the clock has been moved
1011 * forward, an lpq scan done and then the clock moved back. Otherwise
1012 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1015 if (last_qscan_time == ((time_t)-1)
1016 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1017 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1019 time_t msg_pending_time;
1021 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1022 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1023 sharename, (int)last_qscan_time, (int)time_now,
1024 (int)lp_lpqcachetime() ));
1026 /* check if another smbd has already sent a message to update the
1027 queue. Give the pending message one minute to clear and
1028 then send another message anyways. Make sure to check for
1029 clocks that have been run forward and then back again. */
1031 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1034 && tdb_fetch_uint32( pdb->tdb, key, (uint32*)&msg_pending_time )
1035 && msg_pending_time > 0
1036 && msg_pending_time <= time_now
1037 && (time_now - msg_pending_time) < 60 )
1039 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1048 release_print_db(pdb);
1052 /****************************************************************************
1053 main work for updating the lpq cahe for a printer queue
1054 ****************************************************************************/
1056 static void print_queue_update_internal( const char *sharename,
1057 struct printif *current_printif,
1061 print_queue_struct *queue = NULL;
1062 print_status_struct status;
1063 print_status_struct old_status;
1064 struct printjob *pjob;
1065 struct traverse_struct tstruct;
1068 fstring keystr, cachestr;
1069 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1071 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1072 sharename, current_printif->type, lpq_command));
1075 * Update the cache time FIRST ! Stops others even
1076 * attempting to get the lock and doing this
1077 * if the lpq takes a long time.
1080 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1081 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1083 /* get the current queue using the appropriate interface */
1084 ZERO_STRUCT(status);
1086 qcount = (*(current_printif->queue_get))(sharename,
1087 current_printif->type,
1088 lpq_command, &queue, &status);
1090 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1091 qcount, (qcount != 1) ? "s" : "", sharename));
1093 /* Sort the queue by submission time otherwise they are displayed
1096 qsort(queue, qcount, sizeof(print_queue_struct),
1097 QSORT_CAST(printjob_comp));
1100 any job in the internal database that is marked as spooled
1101 and doesn't exist in the system queue is considered finished
1102 and removed from the database
1104 any job in the system database but not in the internal database
1105 is added as a unix job
1107 fill in any system job numbers as we go
1110 jcdata = get_jobs_changed_data(pdb);
1112 for (i=0; i<qcount; i++) {
1113 uint32 jobid = print_parse_jobid(queue[i].fs_file);
1115 if (jobid == (uint32)-1) {
1116 /* assume its a unix print job */
1117 print_unix_job(sharename, &queue[i], jobid);
1121 /* we have an active SMB print job - update its status */
1122 pjob = print_job_find(sharename, jobid);
1124 /* err, somethings wrong. Probably smbd was restarted
1125 with jobs in the queue. All we can do is treat them
1126 like unix jobs. Pity. */
1127 print_unix_job(sharename, &queue[i], jobid);
1131 pjob->sysjob = queue[i].job;
1132 pjob->status = queue[i].status;
1133 pjob_store(sharename, jobid, pjob);
1134 check_job_changed(sharename, jcdata, jobid);
1137 SAFE_FREE(jcdata.dptr);
1139 /* now delete any queued entries that don't appear in the
1141 tstruct.queue = queue;
1142 tstruct.qcount = qcount;
1144 tstruct.total_jobs = 0;
1145 tstruct.lpq_time = time(NULL);
1146 tstruct.sharename = sharename;
1148 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1150 /* Store the linearised queue, max jobs only. */
1151 store_queue_struct(pdb, &tstruct);
1153 SAFE_FREE(tstruct.queue);
1155 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1156 sharename, tstruct.total_jobs ));
1158 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1160 get_queue_status(sharename, &old_status);
1161 if (old_status.qcount != qcount)
1162 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1163 old_status.qcount, qcount, sharename));
1165 /* store the new queue status structure */
1166 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1168 key.dsize = strlen(keystr);
1170 status.qcount = qcount;
1171 data.dptr = (void *)&status;
1172 data.dsize = sizeof(status);
1173 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1176 * Update the cache time again. We want to do this call
1177 * as little as possible...
1180 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1181 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1183 /* clear the msg pending record for this queue */
1185 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1187 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1188 /* log a message but continue on */
1190 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1194 release_print_db( pdb );
1199 /****************************************************************************
1200 Update the internal database from the system print queue for a queue.
1201 obtain a lock on the print queue before proceeding (needed when mutiple
1202 smbd processes maytry to update the lpq cache concurrently).
1203 ****************************************************************************/
1205 static void print_queue_update_with_lock( const char *sharename,
1206 struct printif *current_printif,
1210 struct tdb_print_db *pdb;
1212 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1213 pdb = get_print_db_byname(sharename);
1217 if ( !print_cache_expired(sharename, False) ) {
1218 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1219 release_print_db(pdb);
1224 * Check to see if someone else is doing this update.
1225 * This is essentially a mutex on the update.
1228 if (get_updating_pid(sharename) != -1) {
1229 release_print_db(pdb);
1233 /* Lock the queue for the database update */
1235 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1236 /* Only wait 10 seconds for this. */
1237 if (tdb_lock_bystring(pdb->tdb, keystr, 10) == -1) {
1238 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1239 release_print_db(pdb);
1244 * Ensure that no one else got in here.
1245 * If the updating pid is still -1 then we are
1249 if (get_updating_pid(sharename) != -1) {
1251 * Someone else is doing the update, exit.
1253 tdb_unlock_bystring(pdb->tdb, keystr);
1254 release_print_db(pdb);
1259 * We're going to do the update ourselves.
1262 /* Tell others we're doing the update. */
1263 set_updating_pid(sharename, True);
1266 * Allow others to enter and notice we're doing
1270 tdb_unlock_bystring(pdb->tdb, keystr);
1272 /* do the main work now */
1274 print_queue_update_internal( sharename, current_printif, lpq_command );
1276 /* Delete our pid from the db. */
1277 set_updating_pid(sharename, False);
1278 release_print_db(pdb);
1281 /****************************************************************************
1282 this is the receive function of the background lpq updater
1283 ****************************************************************************/
1284 static void print_queue_receive(int msg_type, pid_t src, void *buf, size_t msglen)
1291 len = tdb_unpack( buf, msglen, "fdP",
1297 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1301 print_queue_update_with_lock(sharename,
1302 get_printer_fns_from_type(printing_type),
1308 static pid_t background_lpq_updater_pid = -1;
1310 /****************************************************************************
1311 main thread of the background lpq updater
1312 ****************************************************************************/
1313 void start_background_queue(void)
1315 DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
1316 background_lpq_updater_pid = sys_fork();
1318 if (background_lpq_updater_pid == -1) {
1319 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
1323 if(background_lpq_updater_pid == 0) {
1325 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
1327 claim_connection( NULL, "smbd lpq backend", 0, False,
1328 FLAG_MSG_GENERAL|FLAG_MSG_SMBD|FLAG_MSG_PRINT_GENERAL);
1330 if (!locking_init(0)) {
1334 message_register(MSG_PRINTER_UPDATE, print_queue_receive);
1336 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
1340 /* check for some essential signals first */
1343 exit_server("Caught TERM signal");
1346 if (reload_after_sighup) {
1347 change_to_root_user();
1348 DEBUG(1,("Reloading services after SIGHUP\n"));
1349 reload_services(False);
1350 reload_after_sighup = 0;
1353 /* now check for messages */
1355 DEBUG(10,("start_background_queue: background LPQ thread got a message\n"));
1358 /* process any pending print change notify messages */
1360 print_notify_send_messages(0);
1365 /****************************************************************************
1366 update the internal database from the system print queue for a queue
1367 ****************************************************************************/
1369 static void print_queue_update(int snum, BOOL force)
1374 char *buffer = NULL;
1377 struct tdb_print_db *pdb;
1379 struct printif *current_printif;
1381 fstrcpy( sharename, lp_const_servicename(snum));
1383 /* don't strip out characters like '$' from the printername */
1385 pstrcpy( lpqcommand, lp_lpqcommand(snum));
1386 string_sub2( lpqcommand, "%p", PRINTERNAME(snum), sizeof(lpqcommand), False, False );
1387 standard_sub_snum( snum, lpqcommand, sizeof(lpqcommand) );
1390 * Make sure that the background queue process exists.
1391 * Otherwise just do the update ourselves
1394 if ( force || background_lpq_updater_pid == -1 ) {
1395 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1396 current_printif = get_printer_fns( snum );
1397 print_queue_update_with_lock( sharename, current_printif, lpqcommand );
1402 type = lp_printing(snum);
1404 /* get the length */
1406 len = tdb_pack( buffer, len, "fdP",
1411 buffer = SMB_XMALLOC_ARRAY( char, len );
1413 /* now pack the buffer */
1414 newlen = tdb_pack( buffer, len, "fdP",
1419 SMB_ASSERT( newlen == len );
1421 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1422 "type = %d, lpq command = [%s]\n", sharename, type, lpqcommand ));
1424 /* here we set a msg pending record for other smbd processes
1425 to throttle the number of duplicate print_queue_update msgs
1428 pdb = get_print_db_byname(sharename);
1429 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1431 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1432 /* log a message but continue on */
1434 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1438 release_print_db( pdb );
1440 /* finally send the message */
1443 message_send_pid(background_lpq_updater_pid,
1444 MSG_PRINTER_UPDATE, buffer, len, False);
1447 SAFE_FREE( buffer );
1452 /****************************************************************************
1453 Create/Update an entry in the print tdb that will allow us to send notify
1454 updates only to interested smbd's.
1455 ****************************************************************************/
1457 BOOL print_notify_register_pid(int snum)
1460 struct tdb_print_db *pdb = NULL;
1461 TDB_CONTEXT *tdb = NULL;
1462 const char *printername;
1463 uint32 mypid = (uint32)sys_getpid();
1467 /* if (snum == -1), then the change notify request was
1468 on a print server handle and we need to register on
1473 int num_services = lp_numservices();
1476 for ( idx=0; idx<num_services; idx++ ) {
1477 if (lp_snum_ok(idx) && lp_print_ok(idx) )
1478 print_notify_register_pid(idx);
1483 else /* register for a specific printer */
1485 printername = lp_const_servicename(snum);
1486 pdb = get_print_db_byname(printername);
1492 if (tdb_lock_bystring(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1493 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1496 release_print_db(pdb);
1500 data = get_printer_notify_pid_list( tdb, printername, True );
1502 /* Add ourselves and increase the refcount. */
1504 for (i = 0; i < data.dsize; i += 8) {
1505 if (IVAL(data.dptr,i) == mypid) {
1506 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1507 SIVAL(data.dptr, i+4, new_refcount);
1512 if (i == data.dsize) {
1513 /* We weren't in the list. Realloc. */
1514 data.dptr = SMB_REALLOC(data.dptr, data.dsize + 8);
1516 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1521 SIVAL(data.dptr,data.dsize - 8,mypid);
1522 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1525 /* Store back the record. */
1526 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1527 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1528 list for printer %s\n", printername));
1536 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1538 release_print_db(pdb);
1539 SAFE_FREE(data.dptr);
1543 /****************************************************************************
1544 Update an entry in the print tdb that will allow us to send notify
1545 updates only to interested smbd's.
1546 ****************************************************************************/
1548 BOOL print_notify_deregister_pid(int snum)
1551 struct tdb_print_db *pdb = NULL;
1552 TDB_CONTEXT *tdb = NULL;
1553 const char *printername;
1554 uint32 mypid = (uint32)sys_getpid();
1558 /* if ( snum == -1 ), we are deregister a print server handle
1559 which means to deregister on all print queues */
1563 int num_services = lp_numservices();
1566 for ( idx=0; idx<num_services; idx++ ) {
1567 if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1568 print_notify_deregister_pid(idx);
1573 else /* deregister a specific printer */
1575 printername = lp_const_servicename(snum);
1576 pdb = get_print_db_byname(printername);
1582 if (tdb_lock_bystring(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1583 DEBUG(0,("print_notify_register_pid: Failed to lock \
1584 printer %s database\n", printername));
1586 release_print_db(pdb);
1590 data = get_printer_notify_pid_list( tdb, printername, True );
1592 /* Reduce refcount. Remove ourselves if zero. */
1594 for (i = 0; i < data.dsize; ) {
1595 if (IVAL(data.dptr,i) == mypid) {
1596 uint32 refcount = IVAL(data.dptr, i+4);
1600 if (refcount == 0) {
1601 if (data.dsize - i > 8)
1602 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1606 SIVAL(data.dptr, i+4, refcount);
1612 if (data.dsize == 0)
1613 SAFE_FREE(data.dptr);
1615 /* Store back the record. */
1616 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1617 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1618 list for printer %s\n", printername));
1626 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1628 release_print_db(pdb);
1629 SAFE_FREE(data.dptr);
1633 /****************************************************************************
1634 Check if a jobid is valid. It is valid if it exists in the database.
1635 ****************************************************************************/
1637 BOOL print_job_exists(const char* sharename, uint32 jobid)
1639 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1644 ret = tdb_exists(pdb->tdb, print_key(jobid));
1645 release_print_db(pdb);
1649 /****************************************************************************
1650 Give the fd used for a jobid.
1651 ****************************************************************************/
1653 int print_job_fd(const char* sharename, uint32 jobid)
1655 struct printjob *pjob = print_job_find(sharename, jobid);
1658 /* don't allow another process to get this info - it is meaningless */
1659 if (pjob->pid != sys_getpid())
1664 /****************************************************************************
1665 Give the filename used for a jobid.
1666 Only valid for the process doing the spooling and when the job
1667 has not been spooled.
1668 ****************************************************************************/
1670 char *print_job_fname(const char* sharename, uint32 jobid)
1672 struct printjob *pjob = print_job_find(sharename, jobid);
1673 if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
1675 return pjob->filename;
1679 /****************************************************************************
1680 Give the filename used for a jobid.
1681 Only valid for the process doing the spooling and when the job
1682 has not been spooled.
1683 ****************************************************************************/
1685 NT_DEVICEMODE *print_job_devmode(const char* sharename, uint32 jobid)
1687 struct printjob *pjob = print_job_find(sharename, jobid);
1692 return pjob->nt_devmode;
1695 /****************************************************************************
1696 Set the place in the queue for a job.
1697 ****************************************************************************/
1699 BOOL print_job_set_place(int snum, uint32 jobid, int place)
1701 DEBUG(2,("print_job_set_place not implemented yet\n"));
1705 /****************************************************************************
1706 Set the name of a job. Only possible for owner.
1707 ****************************************************************************/
1709 BOOL print_job_set_name(int snum, uint32 jobid, char *name)
1711 const char* sharename = lp_const_servicename(snum);
1712 struct printjob *pjob;
1714 pjob = print_job_find(sharename, jobid);
1715 if (!pjob || pjob->pid != sys_getpid())
1718 fstrcpy(pjob->jobname, name);
1719 return pjob_store(sharename, jobid, pjob);
1722 /***************************************************************************
1723 Remove a jobid from the 'jobs changed' list.
1724 ***************************************************************************/
1726 static BOOL remove_from_jobs_changed(const char* sharename, uint32 jobid)
1728 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1730 size_t job_count, i;
1732 BOOL gotlock = False;
1736 key = string_tdb_data("INFO/jobs_changed");
1738 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
1743 data = tdb_fetch(pdb->tdb, key);
1745 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
1748 job_count = data.dsize / 4;
1749 for (i = 0; i < job_count; i++) {
1752 ch_jobid = IVAL(data.dptr, i*4);
1753 if (ch_jobid == jobid) {
1754 if (i < job_count -1 )
1755 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
1757 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
1767 tdb_chainunlock(pdb->tdb, key);
1768 SAFE_FREE(data.dptr);
1769 release_print_db(pdb);
1771 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
1773 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
1777 /****************************************************************************
1778 Delete a print job - don't update queue.
1779 ****************************************************************************/
1781 static BOOL print_job_delete1(int snum, uint32 jobid)
1783 const char* sharename = lp_const_servicename(snum);
1784 struct printjob *pjob = print_job_find(sharename, jobid);
1786 struct printif *current_printif = get_printer_fns( snum );
1788 pjob = print_job_find(sharename, jobid);
1794 * If already deleting just return.
1797 if (pjob->status == LPQ_DELETING)
1800 /* Hrm - we need to be able to cope with deleting a job before it
1801 has reached the spooler. */
1803 if (pjob->sysjob == -1) {
1804 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
1807 /* Set the tdb entry to be deleting. */
1809 pjob->status = LPQ_DELETING;
1810 pjob_store(sharename, jobid, pjob);
1812 if (pjob->spooled && pjob->sysjob != -1)
1813 result = (*(current_printif->job_delete))(snum, pjob);
1815 /* Delete the tdb entry if the delete succeeded or the job hasn't
1819 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1824 pjob_delete(sharename, jobid);
1825 /* Ensure we keep a rough count of the number of total jobs... */
1826 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
1827 release_print_db(pdb);
1830 return (result == 0);
1833 /****************************************************************************
1834 Return true if the current user owns the print job.
1835 ****************************************************************************/
1837 static BOOL is_owner(struct current_user *user, int snum, uint32 jobid)
1839 struct printjob *pjob = print_job_find(lp_const_servicename(snum), jobid);
1845 if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
1846 return strequal(pjob->user, vuser->user.smb_name);
1848 return strequal(pjob->user, uidtoname(user->uid));
1852 /****************************************************************************
1854 ****************************************************************************/
1856 BOOL print_job_delete(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1858 const char* sharename = lp_const_servicename( snum );
1859 BOOL owner, deleted;
1864 owner = is_owner(user, snum, jobid);
1866 /* Check access against security descriptor or whether the user
1870 !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1871 DEBUG(3, ("delete denied by security descriptor\n"));
1872 *errcode = WERR_ACCESS_DENIED;
1874 /* BEGIN_ADMIN_LOG */
1875 sys_adminlog( LOG_ERR,
1876 "Permission denied-- user not allowed to delete, \
1877 pause, or resume print job. User name: %s. Printer name: %s.",
1878 uidtoname(user->uid), PRINTERNAME(snum) );
1885 * get the spooled filename of the print job
1886 * if this works, then the file has not been spooled
1887 * to the underlying print system. Just delete the
1888 * spool file & return.
1891 if ( (fname = print_job_fname( sharename, jobid )) != NULL )
1893 /* remove the spool file */
1894 DEBUG(10,("print_job_delete: Removing spool file [%s]\n", fname ));
1895 if ( unlink( fname ) == -1 ) {
1896 *errcode = map_werror_from_unix(errno);
1901 if (!print_job_delete1(snum, jobid)) {
1902 *errcode = WERR_ACCESS_DENIED;
1906 /* force update the database and say the delete failed if the
1909 print_queue_update(snum, True);
1911 deleted = !print_job_exists(sharename, jobid);
1913 *errcode = WERR_ACCESS_DENIED;
1918 /****************************************************************************
1920 ****************************************************************************/
1922 BOOL print_job_pause(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1924 const char* sharename = lp_const_servicename(snum);
1925 struct printjob *pjob;
1927 struct printif *current_printif = get_printer_fns( snum );
1929 pjob = print_job_find(sharename, jobid);
1934 if (!pjob->spooled || pjob->sysjob == -1)
1937 if (!is_owner(user, snum, jobid) &&
1938 !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1939 DEBUG(3, ("pause denied by security descriptor\n"));
1941 /* BEGIN_ADMIN_LOG */
1942 sys_adminlog( LOG_ERR,
1943 "Permission denied-- user not allowed to delete, \
1944 pause, or resume print job. User name: %s. Printer name: %s.",
1945 uidtoname(user->uid), PRINTERNAME(snum) );
1948 *errcode = WERR_ACCESS_DENIED;
1952 /* need to pause the spooled entry */
1953 ret = (*(current_printif->job_pause))(snum, pjob);
1956 *errcode = WERR_INVALID_PARAM;
1960 /* force update the database */
1961 print_cache_flush(snum);
1963 /* Send a printer notify message */
1965 notify_job_status(sharename, jobid, JOB_STATUS_PAUSED);
1967 /* how do we tell if this succeeded? */
1972 /****************************************************************************
1974 ****************************************************************************/
1976 BOOL print_job_resume(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1978 const char *sharename = lp_const_servicename(snum);
1979 struct printjob *pjob;
1981 struct printif *current_printif = get_printer_fns( snum );
1983 pjob = print_job_find(sharename, jobid);
1988 if (!pjob->spooled || pjob->sysjob == -1)
1991 if (!is_owner(user, snum, jobid) &&
1992 !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1993 DEBUG(3, ("resume denied by security descriptor\n"));
1994 *errcode = WERR_ACCESS_DENIED;
1996 /* BEGIN_ADMIN_LOG */
1997 sys_adminlog( LOG_ERR,
1998 "Permission denied-- user not allowed to delete, \
1999 pause, or resume print job. User name: %s. Printer name: %s.",
2000 uidtoname(user->uid), PRINTERNAME(snum) );
2005 ret = (*(current_printif->job_resume))(snum, pjob);
2008 *errcode = WERR_INVALID_PARAM;
2012 /* force update the database */
2013 print_cache_flush(snum);
2015 /* Send a printer notify message */
2017 notify_job_status(sharename, jobid, JOB_STATUS_QUEUED);
2022 /****************************************************************************
2023 Write to a print file.
2024 ****************************************************************************/
2026 ssize_t print_job_write(int snum, uint32 jobid, const char *buf, SMB_OFF_T pos, size_t size)
2028 const char* sharename = lp_const_servicename(snum);
2030 struct printjob *pjob;
2032 pjob = print_job_find(sharename, jobid);
2036 /* don't allow another process to get this info - it is meaningless */
2037 if (pjob->pid != sys_getpid())
2040 return_code = write_data_at_offset(pjob->fd, buf, size, pos);
2042 if (return_code>0) {
2044 pjob_store(sharename, jobid, pjob);
2049 /****************************************************************************
2050 Get the queue status - do not update if db is out of date.
2051 ****************************************************************************/
2053 static int get_queue_status(const char* sharename, print_status_struct *status)
2057 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2064 ZERO_STRUCTP(status);
2065 fstr_sprintf(keystr, "STATUS/%s", sharename);
2066 data = tdb_fetch(pdb->tdb, string_tdb_data(keystr));
2068 if (data.dsize == sizeof(print_status_struct))
2069 /* this memcpy is ok since the status struct was
2070 not packed before storing it in the tdb */
2071 memcpy(status, data.dptr, sizeof(print_status_struct));
2072 SAFE_FREE(data.dptr);
2075 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2076 release_print_db(pdb);
2077 return (len == -1 ? 0 : len);
2080 /****************************************************************************
2081 Determine the number of jobs in a queue.
2082 ****************************************************************************/
2084 int print_queue_length(int snum, print_status_struct *pstatus)
2086 const char* sharename = lp_const_servicename( snum );
2087 print_status_struct status;
2090 ZERO_STRUCT( status );
2092 /* make sure the database is up to date */
2093 if (print_cache_expired(lp_const_servicename(snum), True))
2094 print_queue_update(snum, False);
2096 /* also fetch the queue status */
2097 memset(&status, 0, sizeof(status));
2098 len = get_queue_status(sharename, &status);
2106 /***************************************************************************
2107 Allocate a jobid. Hold the lock for as short a time as possible.
2108 ***************************************************************************/
2110 static BOOL allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char *sharename, uint32 *pjobid)
2115 *pjobid = (uint32)-1;
2117 for (i = 0; i < 3; i++) {
2118 /* Lock the database - only wait 20 seconds. */
2119 if (tdb_lock_bystring(pdb->tdb, "INFO/nextjob", 20) == -1) {
2120 DEBUG(0,("allocate_print_jobid: failed to lock printing database %s\n", sharename));
2124 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2125 if (tdb_error(pdb->tdb) != TDB_ERR_NOEXIST) {
2126 DEBUG(0, ("allocate_print_jobid: failed to fetch INFO/nextjob for print queue %s\n",
2133 jobid = NEXT_JOBID(jobid);
2135 if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
2136 DEBUG(3, ("allocate_print_jobid: failed to store INFO/nextjob.\n"));
2137 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2141 /* We've finished with the INFO/nextjob lock. */
2142 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2144 if (!print_job_exists(sharename, jobid))
2149 DEBUG(0, ("allocate_print_jobid: failed to allocate a print job for queue %s\n",
2151 /* Probably full... */
2156 /* Store a dummy placeholder. */
2161 if (tdb_store(pdb->tdb, print_key(jobid), dum, TDB_INSERT) == -1) {
2162 DEBUG(3, ("allocate_print_jobid: jobid (%d) failed to store placeholder.\n",
2172 /***************************************************************************
2173 Append a jobid to the 'jobs changed' list.
2174 ***************************************************************************/
2176 static BOOL add_to_jobs_changed(struct tdb_print_db *pdb, uint32 jobid)
2181 SIVAL(&store_jobid, 0, jobid);
2182 data.dptr = (char *)&store_jobid;
2185 DEBUG(10,("add_to_jobs_changed: Added jobid %u\n", (unsigned int)jobid ));
2187 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
2191 /***************************************************************************
2192 Start spooling a job - return the jobid.
2193 ***************************************************************************/
2195 uint32 print_job_start(struct current_user *user, int snum, char *jobname, NT_DEVICEMODE *nt_devmode )
2199 struct printjob pjob;
2201 const char *sharename = lp_const_servicename(snum);
2202 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2210 if (!print_access_check(user, snum, PRINTER_ACCESS_USE)) {
2211 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
2212 release_print_db(pdb);
2216 if (!print_time_access_check(snum)) {
2217 DEBUG(3, ("print_job_start: job start denied by time check\n"));
2218 release_print_db(pdb);
2222 path = lp_pathname(snum);
2224 /* see if we have sufficient disk space */
2225 if (lp_minprintspace(snum)) {
2226 SMB_BIG_UINT dspace, dsize;
2227 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
2228 dspace < 2*(SMB_BIG_UINT)lp_minprintspace(snum)) {
2229 DEBUG(3, ("print_job_start: disk space check failed.\n"));
2230 release_print_db(pdb);
2236 /* for autoloaded printers, check that the printcap entry still exists */
2237 if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum))) {
2238 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
2239 release_print_db(pdb);
2244 /* Insure the maximum queue size is not violated */
2245 if ((njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
2246 DEBUG(3, ("print_job_start: Queue %s number of jobs (%d) larger than max printjobs per queue (%d).\n",
2247 sharename, njobs, lp_maxprintjobs(snum) ));
2248 release_print_db(pdb);
2253 DEBUG(10,("print_job_start: Queue %s number of jobs (%d), max printjobs = %d\n",
2254 sharename, njobs, lp_maxprintjobs(snum) ));
2256 if (!allocate_print_jobid(pdb, snum, sharename, &jobid))
2259 /* create the database entry */
2263 pjob.pid = sys_getpid();
2266 pjob.starttime = time(NULL);
2267 pjob.status = LPQ_SPOOLING;
2269 pjob.spooled = False;
2271 pjob.nt_devmode = nt_devmode;
2273 fstrcpy(pjob.jobname, jobname);
2275 if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
2276 fstrcpy(pjob.user, vuser->user.smb_name);
2278 fstrcpy(pjob.user, uidtoname(user->uid));
2281 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2283 /* we have a job entry - now create the spool file */
2284 slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX",
2285 path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2286 pjob.fd = smb_mkstemp(pjob.filename);
2288 if (pjob.fd == -1) {
2289 if (errno == EACCES) {
2290 /* Common setup error, force a report. */
2291 DEBUG(0, ("print_job_start: insufficient permissions \
2292 to open spool file %s.\n", pjob.filename));
2294 /* Normal case, report at level 3 and above. */
2295 DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
2296 DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
2301 pjob_store(sharename, jobid, &pjob);
2303 /* Update the 'jobs changed' entry used by print_queue_status. */
2304 add_to_jobs_changed(pdb, jobid);
2306 /* Ensure we keep a rough count of the number of total jobs... */
2307 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2309 release_print_db(pdb);
2315 pjob_delete(sharename, jobid);
2317 release_print_db(pdb);
2319 DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
2323 /****************************************************************************
2324 Update the number of pages spooled to jobid
2325 ****************************************************************************/
2327 void print_job_endpage(int snum, uint32 jobid)
2329 const char* sharename = lp_const_servicename(snum);
2330 struct printjob *pjob;
2332 pjob = print_job_find(sharename, jobid);
2335 /* don't allow another process to get this info - it is meaningless */
2336 if (pjob->pid != sys_getpid())
2340 pjob_store(sharename, jobid, pjob);
2343 /****************************************************************************
2344 Print a file - called on closing the file. This spools the job.
2345 If normal close is false then we're tearing down the jobs - treat as an
2347 ****************************************************************************/
2349 BOOL print_job_end(int snum, uint32 jobid, BOOL normal_close)
2351 const char* sharename = lp_const_servicename(snum);
2352 struct printjob *pjob;
2354 SMB_STRUCT_STAT sbuf;
2355 struct printif *current_printif = get_printer_fns( snum );
2357 pjob = print_job_find(sharename, jobid);
2362 if (pjob->spooled || pjob->pid != sys_getpid())
2365 if (normal_close && (sys_fstat(pjob->fd, &sbuf) == 0)) {
2366 pjob->size = sbuf.st_size;
2372 * Not a normal close or we couldn't stat the job file,
2373 * so something has gone wrong. Cleanup.
2377 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
2381 /* Technically, this is not quite right. If the printer has a separator
2382 * page turned on, the NT spooler prints the separator page even if the
2383 * print job is 0 bytes. 010215 JRR */
2384 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
2385 /* don't bother spooling empty files or something being deleted. */
2386 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
2387 pjob->filename, pjob->size ? "deleted" : "zero length" ));
2388 unlink(pjob->filename);
2389 pjob_delete(sharename, jobid);
2393 pjob->smbjob = jobid;
2395 ret = (*(current_printif->job_submit))(snum, pjob);
2400 /* The print job has been sucessfully handed over to the back-end */
2402 pjob->spooled = True;
2403 pjob->status = LPQ_QUEUED;
2404 pjob_store(sharename, jobid, pjob);
2406 /* make sure the database is up to date */
2407 if (print_cache_expired(lp_const_servicename(snum), True))
2408 print_queue_update(snum, False);
2414 /* The print job was not succesfully started. Cleanup */
2415 /* Still need to add proper error return propagation! 010122:JRR */
2416 unlink(pjob->filename);
2417 pjob_delete(sharename, jobid);
2421 /****************************************************************************
2422 Get a snapshot of jobs in the system without traversing.
2423 ****************************************************************************/
2425 static BOOL get_stored_queue_info(struct tdb_print_db *pdb, int snum, int *pcount, print_queue_struct **ppqueue)
2427 TDB_DATA data, cgdata;
2428 print_queue_struct *queue = NULL;
2430 uint32 extra_count = 0;
2431 int total_count = 0;
2434 int max_reported_jobs = lp_max_reported_jobs(snum);
2436 const char* sharename = lp_servicename(snum);
2438 /* make sure the database is up to date */
2439 if (print_cache_expired(lp_const_servicename(snum), True))
2440 print_queue_update(snum, False);
2446 ZERO_STRUCT(cgdata);
2448 /* Get the stored queue data. */
2449 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
2451 if (data.dptr && data.dsize >= sizeof(qcount))
2452 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
2454 /* Get the changed jobs list. */
2455 cgdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
2456 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
2457 extra_count = cgdata.dsize/4;
2459 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
2461 /* Allocate the queue size. */
2462 if (qcount == 0 && extra_count == 0)
2465 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
2468 /* Retrieve the linearised queue data. */
2470 for( i = 0; i < qcount; i++) {
2471 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
2472 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
2481 queue[i].job = qjob;
2482 queue[i].size = qsize;
2483 queue[i].page_count = qpage_count;
2484 queue[i].status = qstatus;
2485 queue[i].priority = qpriority;
2486 queue[i].time = qtime;
2489 total_count = qcount;
2491 /* Add in the changed jobids. */
2492 for( i = 0; i < extra_count; i++) {
2494 struct printjob *pjob;
2496 jobid = IVAL(cgdata.dptr, i*4);
2497 DEBUG(5,("get_stored_queue_info: changed job = %u\n", (unsigned int)jobid));
2498 pjob = print_job_find(lp_const_servicename(snum), jobid);
2500 DEBUG(5,("get_stored_queue_info: failed to find changed job = %u\n", (unsigned int)jobid));
2501 remove_from_jobs_changed(sharename, jobid);
2505 queue[total_count].job = jobid;
2506 queue[total_count].size = pjob->size;
2507 queue[total_count].page_count = pjob->page_count;
2508 queue[total_count].status = pjob->status;
2509 queue[total_count].priority = 1;
2510 queue[total_count].time = pjob->starttime;
2511 fstrcpy(queue[total_count].fs_user, pjob->user);
2512 fstrcpy(queue[total_count].fs_file, pjob->jobname);
2516 /* Sort the queue by submission time otherwise they are displayed
2519 qsort(queue, total_count, sizeof(print_queue_struct), QSORT_CAST(printjob_comp));
2521 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
2523 if (max_reported_jobs && total_count > max_reported_jobs)
2524 total_count = max_reported_jobs;
2527 *pcount = total_count;
2533 SAFE_FREE(data.dptr);
2534 SAFE_FREE(cgdata.dptr);
2538 /****************************************************************************
2539 Get a printer queue listing.
2540 set queue = NULL and status = NULL if you just want to update the cache
2541 ****************************************************************************/
2543 int print_queue_status(int snum,
2544 print_queue_struct **ppqueue,
2545 print_status_struct *status)
2549 const char *sharename;
2550 struct tdb_print_db *pdb;
2553 /* make sure the database is up to date */
2555 if (print_cache_expired(lp_const_servicename(snum), True))
2556 print_queue_update(snum, False);
2558 /* return if we are done */
2559 if ( !ppqueue || !status )
2563 sharename = lp_const_servicename(snum);
2564 pdb = get_print_db_byname(sharename);
2570 * Fetch the queue status. We must do this first, as there may
2571 * be no jobs in the queue.
2574 ZERO_STRUCTP(status);
2575 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
2577 key.dsize = strlen(keystr);
2578 data = tdb_fetch(pdb->tdb, key);
2580 if (data.dsize == sizeof(*status)) {
2581 /* this memcpy is ok since the status struct was
2582 not packed before storing it in the tdb */
2583 memcpy(status, data.dptr, sizeof(*status));
2585 SAFE_FREE(data.dptr);
2589 * Now, fetch the print queue information. We first count the number
2590 * of entries, and then only retrieve the queue if necessary.
2593 if (!get_stored_queue_info(pdb, snum, &count, ppqueue)) {
2594 release_print_db(pdb);
2598 release_print_db(pdb);
2602 /****************************************************************************
2604 ****************************************************************************/
2606 BOOL print_queue_pause(struct current_user *user, int snum, WERROR *errcode)
2609 struct printif *current_printif = get_printer_fns( snum );
2611 if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
2612 *errcode = WERR_ACCESS_DENIED;
2619 ret = (*(current_printif->queue_pause))(snum);
2624 *errcode = WERR_INVALID_PARAM;
2628 /* force update the database */
2629 print_cache_flush(snum);
2631 /* Send a printer notify message */
2633 notify_printer_status(snum, PRINTER_STATUS_PAUSED);
2638 /****************************************************************************
2640 ****************************************************************************/
2642 BOOL print_queue_resume(struct current_user *user, int snum, WERROR *errcode)
2645 struct printif *current_printif = get_printer_fns( snum );
2647 if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
2648 *errcode = WERR_ACCESS_DENIED;
2654 ret = (*(current_printif->queue_resume))(snum);
2659 *errcode = WERR_INVALID_PARAM;
2663 /* make sure the database is up to date */
2664 if (print_cache_expired(lp_const_servicename(snum), True))
2665 print_queue_update(snum, True);
2667 /* Send a printer notify message */
2669 notify_printer_status(snum, PRINTER_STATUS_OK);
2674 /****************************************************************************
2675 Purge a queue - implemented by deleting all jobs that we can delete.
2676 ****************************************************************************/
2678 BOOL print_queue_purge(struct current_user *user, int snum, WERROR *errcode)
2680 print_queue_struct *queue;
2681 print_status_struct status;
2685 /* Force and update so the count is accurate (i.e. not a cached count) */
2686 print_queue_update(snum, True);
2688 can_job_admin = print_access_check(user, snum, JOB_ACCESS_ADMINISTER);
2689 njobs = print_queue_status(snum, &queue, &status);
2691 if ( can_job_admin )
2694 for (i=0;i<njobs;i++) {
2695 BOOL owner = is_owner(user, snum, queue[i].job);
2697 if (owner || can_job_admin) {
2698 print_job_delete1(snum, queue[i].job);
2702 if ( can_job_admin )
2705 /* update the cache */
2706 print_queue_update( snum, True );