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 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/>.
24 #include "librpc/gen_ndr/messaging.h"
25 #include "../librpc/gen_ndr/ndr_spoolss.h"
26 #include "nt_printing.h"
27 #include "../librpc/gen_ndr/netlogon.h"
29 extern struct current_user current_user;
30 extern userdom_struct current_user_info;
32 /* Current printer interface */
33 static bool remove_from_jobs_changed(const char* sharename, uint32 jobid);
36 the printing backend revolves around a tdb database that stores the
37 SMB view of the print queue
39 The key for this database is a jobid - a internally generated number that
40 uniquely identifies a print job
42 reading the print queue involves two steps:
43 - possibly running lpq and updating the internal database from that
44 - reading entries from the database
46 jobids are assigned when a job starts spooling.
49 static TDB_CONTEXT *rap_tdb;
50 static uint16 next_rap_jobid;
51 struct rap_jobid_key {
56 /***************************************************************************
57 Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
58 bit RPC jobids.... JRA.
59 ***************************************************************************/
61 uint16 pjobid_to_rap(const char* sharename, uint32 jobid)
65 struct rap_jobid_key jinfo;
68 DEBUG(10,("pjobid_to_rap: called.\n"));
71 /* Create the in-memory tdb. */
72 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
78 fstrcpy( jinfo.sharename, sharename );
80 key.dptr = (uint8 *)&jinfo;
81 key.dsize = sizeof(jinfo);
83 data = tdb_fetch(rap_tdb, key);
84 if (data.dptr && data.dsize == sizeof(uint16)) {
85 rap_jobid = SVAL(data.dptr, 0);
87 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
88 (unsigned int)jobid, (unsigned int)rap_jobid));
92 /* Not found - create and store mapping. */
93 rap_jobid = ++next_rap_jobid;
95 rap_jobid = ++next_rap_jobid;
96 SSVAL(buf,0,rap_jobid);
98 data.dsize = sizeof(rap_jobid);
99 tdb_store(rap_tdb, key, data, TDB_REPLACE);
100 tdb_store(rap_tdb, data, key, TDB_REPLACE);
102 DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
103 (unsigned int)jobid, (unsigned int)rap_jobid));
107 bool rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
112 DEBUG(10,("rap_to_pjobid called.\n"));
117 SSVAL(buf,0,rap_jobid);
119 key.dsize = sizeof(rap_jobid);
120 data = tdb_fetch(rap_tdb, key);
121 if ( data.dptr && data.dsize == sizeof(struct rap_jobid_key) )
123 struct rap_jobid_key *jinfo = (struct rap_jobid_key*)data.dptr;
124 if (sharename != NULL) {
125 fstrcpy( sharename, jinfo->sharename );
127 *pjobid = jinfo->jobid;
128 DEBUG(10,("rap_to_pjobid: jobid %u maps to RAP jobid %u\n",
129 (unsigned int)*pjobid, (unsigned int)rap_jobid));
130 SAFE_FREE(data.dptr);
134 DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
135 (unsigned int)rap_jobid));
136 SAFE_FREE(data.dptr);
140 void rap_jobid_delete(const char* sharename, uint32 jobid)
144 struct rap_jobid_key jinfo;
147 DEBUG(10,("rap_jobid_delete: called.\n"));
152 ZERO_STRUCT( jinfo );
153 fstrcpy( jinfo.sharename, sharename );
155 key.dptr = (uint8 *)&jinfo;
156 key.dsize = sizeof(jinfo);
158 data = tdb_fetch(rap_tdb, key);
159 if (!data.dptr || (data.dsize != sizeof(uint16))) {
160 DEBUG(10,("rap_jobid_delete: cannot find jobid %u\n",
161 (unsigned int)jobid ));
162 SAFE_FREE(data.dptr);
166 DEBUG(10,("rap_jobid_delete: deleting jobid %u\n",
167 (unsigned int)jobid ));
169 rap_jobid = SVAL(data.dptr, 0);
170 SAFE_FREE(data.dptr);
171 SSVAL(buf,0,rap_jobid);
173 data.dsize = sizeof(rap_jobid);
174 tdb_delete(rap_tdb, key);
175 tdb_delete(rap_tdb, data);
178 static int get_queue_status(const char* sharename, print_status_struct *);
180 /****************************************************************************
181 Initialise the printing backend. Called once at startup before the fork().
182 ****************************************************************************/
184 bool print_backend_init(struct messaging_context *msg_ctx)
186 const char *sversion = "INFO/version";
187 int services = lp_numservices();
190 unlink(cache_path("printing.tdb"));
191 mkdir(cache_path("printing"),0755);
193 /* handle a Samba upgrade */
195 for (snum = 0; snum < services; snum++) {
196 struct tdb_print_db *pdb;
197 if (!lp_print_ok(snum))
200 pdb = get_print_db_byname(lp_const_servicename(snum));
203 if (tdb_lock_bystring(pdb->tdb, sversion) == -1) {
204 DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
205 release_print_db(pdb);
208 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
209 tdb_wipe_all(pdb->tdb);
210 tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
212 tdb_unlock_bystring(pdb->tdb, sversion);
213 release_print_db(pdb);
216 close_all_print_db(); /* Don't leave any open. */
218 /* do NT print initialization... */
219 return nt_printing_init(msg_ctx);
222 /****************************************************************************
223 Shut down printing backend. Called once at shutdown to close the tdb.
224 ****************************************************************************/
226 void printing_end(void)
228 close_all_print_db(); /* Don't leave any open. */
231 /****************************************************************************
232 Retrieve the set of printing functions for a given service. This allows
233 us to set the printer function table based on the value of the 'printing'
236 Use the generic interface as the default and only use cups interface only
237 when asked for (and only when supported)
238 ****************************************************************************/
240 static struct printif *get_printer_fns_from_type( enum printing_types type )
242 struct printif *printer_fns = &generic_printif;
245 if ( type == PRINT_CUPS ) {
246 printer_fns = &cups_printif;
248 #endif /* HAVE_CUPS */
251 if ( type == PRINT_IPRINT ) {
252 printer_fns = &iprint_printif;
254 #endif /* HAVE_IPRINT */
256 printer_fns->type = type;
261 static struct printif *get_printer_fns( int snum )
263 return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
267 /****************************************************************************
268 Useful function to generate a tdb key.
269 ****************************************************************************/
271 static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
275 SIVAL(tmp, 0, jobid);
276 ret.dptr = (uint8 *)tmp;
277 ret.dsize = sizeof(*tmp);
281 /****************************************************************************
282 Pack the devicemode to store it in a tdb.
283 ****************************************************************************/
284 static int pack_devicemode(struct spoolss_DeviceMode *devmode, uint8 *buf, int buflen)
286 enum ndr_err_code ndr_err;
291 ndr_err = ndr_push_struct_blob(&blob, talloc_tos(),
293 (ndr_push_flags_fn_t)
294 ndr_push_spoolss_DeviceMode);
295 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
296 DEBUG(10, ("pack_devicemode: "
297 "error encoding spoolss_DeviceMode\n"));
304 len = tdb_pack(buf, buflen, "B", blob.length, blob.data);
307 DEBUG(8, ("Packed devicemode [%s]\n", devmode->formname));
314 /****************************************************************************
315 Unpack the devicemode to store it in a tdb.
316 ****************************************************************************/
317 static int unpack_devicemode(TALLOC_CTX *mem_ctx,
318 const uint8 *buf, int buflen,
319 struct spoolss_DeviceMode **devmode)
321 struct spoolss_DeviceMode *dm;
322 enum ndr_err_code ndr_err;
330 len = tdb_unpack(buf, buflen, "B", &data_len, &data);
335 dm = talloc_zero(mem_ctx, struct spoolss_DeviceMode);
340 blob = data_blob_const(data, data_len);
342 ndr_err = ndr_pull_struct_blob(&blob, dm, dm,
343 (ndr_pull_flags_fn_t)ndr_pull_spoolss_DeviceMode);
344 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
345 DEBUG(10, ("unpack_devicemode: "
346 "error parsing spoolss_DeviceMode\n"));
350 DEBUG(8, ("Unpacked devicemode [%s](%s)\n",
351 dm->devicename, dm->formname));
352 if (dm->driverextra_data.data) {
353 DEBUG(8, ("with a private section of %d bytes\n",
354 dm->__driverextra_length));
364 /***********************************************************************
365 unpack a pjob from a tdb buffer
366 ***********************************************************************/
368 int unpack_pjob( uint8 *buf, int buflen, struct printjob *pjob )
372 uint32 pjpid, pjsysjob, pjfd, pjstarttime, pjstatus;
373 uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
378 len += tdb_unpack(buf+len, buflen-len, "dddddddddffff",
396 used = unpack_devicemode(NULL, buf+len, buflen-len, &pjob->devmode);
404 pjob->sysjob = pjsysjob;
406 pjob->starttime = pjstarttime;
407 pjob->status = pjstatus;
409 pjob->page_count = pjpage_count;
410 pjob->spooled = pjspooled;
411 pjob->smbjob = pjsmbjob;
417 /****************************************************************************
418 Useful function to find a print job in the database.
419 ****************************************************************************/
421 static struct printjob *print_job_find(const char *sharename, uint32 jobid)
423 static struct printjob pjob;
426 struct tdb_print_db *pdb = get_print_db_byname(sharename);
428 DEBUG(10,("print_job_find: looking up job %u for share %s\n",
429 (unsigned int)jobid, sharename ));
435 ret = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
436 release_print_db(pdb);
439 DEBUG(10,("print_job_find: failed to find jobid %u.\n", (unsigned int)jobid ));
443 talloc_free(pjob.devmode);
447 if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
448 DEBUG(10,("print_job_find: failed to unpack jobid %u.\n", (unsigned int)jobid ));
455 DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
456 (int)pjob.sysjob, (unsigned int)jobid ));
461 /* Convert a unix jobid to a smb jobid */
463 struct unixjob_traverse_state {
465 uint32 sysjob_to_jobid_value;
468 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
469 TDB_DATA data, void *private_data)
471 struct printjob *pjob;
472 struct unixjob_traverse_state *state =
473 (struct unixjob_traverse_state *)private_data;
475 if (!data.dptr || data.dsize == 0)
478 pjob = (struct printjob *)data.dptr;
479 if (key.dsize != sizeof(uint32))
482 if (state->sysjob == pjob->sysjob) {
483 uint32 jobid = IVAL(key.dptr,0);
485 state->sysjob_to_jobid_value = jobid;
492 /****************************************************************************
493 This is a *horribly expensive call as we have to iterate through all the
494 current printer tdb's. Don't do this often ! JRA.
495 ****************************************************************************/
497 uint32 sysjob_to_jobid(int unix_jobid)
499 int services = lp_numservices();
501 struct unixjob_traverse_state state;
503 state.sysjob = unix_jobid;
504 state.sysjob_to_jobid_value = (uint32)-1;
506 for (snum = 0; snum < services; snum++) {
507 struct tdb_print_db *pdb;
508 if (!lp_print_ok(snum))
510 pdb = get_print_db_byname(lp_const_servicename(snum));
514 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
515 release_print_db(pdb);
516 if (state.sysjob_to_jobid_value != (uint32)-1)
517 return state.sysjob_to_jobid_value;
522 /****************************************************************************
523 Send notifications based on what has changed after a pjob_store.
524 ****************************************************************************/
526 static const struct {
528 uint32 spoolss_status;
529 } lpq_to_spoolss_status_map[] = {
530 { LPQ_QUEUED, JOB_STATUS_QUEUED },
531 { LPQ_PAUSED, JOB_STATUS_PAUSED },
532 { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
533 { LPQ_PRINTING, JOB_STATUS_PRINTING },
534 { LPQ_DELETING, JOB_STATUS_DELETING },
535 { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
536 { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
537 { LPQ_PRINTED, JOB_STATUS_PRINTED },
538 { LPQ_DELETED, JOB_STATUS_DELETED },
539 { LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
540 { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
544 /* Convert a lpq status value stored in printing.tdb into the
545 appropriate win32 API constant. */
547 static uint32 map_to_spoolss_status(uint32 lpq_status)
551 while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
552 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
553 return lpq_to_spoolss_status_map[i].spoolss_status;
560 static void pjob_store_notify(const char* sharename, uint32 jobid, struct printjob *old_data,
561 struct printjob *new_data)
563 bool new_job = False;
568 /* Job attributes that can't be changed. We only send
569 notification for these on a new job. */
571 /* ACHTUNG! Due to a bug in Samba's spoolss parsing of the
572 NOTIFY_INFO_DATA buffer, we *have* to send the job submission
573 time first or else we'll end up with potential alignment
574 errors. I don't think the systemtime should be spooled as
575 a string, but this gets us around that error.
576 --jerry (i'll feel dirty for this) */
579 notify_job_submitted(sharename, jobid, new_data->starttime);
580 notify_job_username(sharename, jobid, new_data->user);
583 if (new_job || !strequal(old_data->jobname, new_data->jobname))
584 notify_job_name(sharename, jobid, new_data->jobname);
586 /* Job attributes of a new job or attributes that can be
589 if (new_job || !strequal(old_data->jobname, new_data->jobname))
590 notify_job_name(sharename, jobid, new_data->jobname);
592 if (new_job || old_data->status != new_data->status)
593 notify_job_status(server_event_context(),
594 server_messaging_context(),
596 map_to_spoolss_status(new_data->status));
598 if (new_job || old_data->size != new_data->size)
599 notify_job_total_bytes(server_event_context(),
600 server_messaging_context(),
601 sharename, jobid, new_data->size);
603 if (new_job || old_data->page_count != new_data->page_count)
604 notify_job_total_pages(server_event_context(),
605 server_messaging_context(),
606 sharename, jobid, new_data->page_count);
609 /****************************************************************************
610 Store a job structure back to the database.
611 ****************************************************************************/
613 static bool pjob_store(const char* sharename, uint32 jobid, struct printjob *pjob)
616 TDB_DATA old_data, new_data;
618 struct tdb_print_db *pdb = get_print_db_byname(sharename);
620 int len, newlen, buflen;
628 old_data = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
630 /* Doh! Now we have to pack/unpack data since the NT_DEVICEMODE was added */
637 len += tdb_pack(buf+len, buflen-len, "dddddddddffff",
639 (uint32)pjob->sysjob,
641 (uint32)pjob->starttime,
642 (uint32)pjob->status,
644 (uint32)pjob->page_count,
645 (uint32)pjob->spooled,
646 (uint32)pjob->smbjob,
652 len += pack_devicemode(pjob->devmode, buf+len, buflen-len);
655 buf = (uint8 *)SMB_REALLOC(buf, len);
657 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
662 } while ( buflen != len );
668 new_data.dsize = len;
669 ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
672 release_print_db(pdb);
674 /* Send notify updates for what has changed */
677 struct printjob old_pjob;
679 if ( old_data.dsize )
681 if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
683 pjob_store_notify( sharename, jobid, &old_pjob , pjob );
684 talloc_free(old_pjob.devmode);
689 pjob_store_notify( sharename, jobid, NULL, pjob );
694 SAFE_FREE( old_data.dptr );
700 /****************************************************************************
701 Remove a job structure from the database.
702 ****************************************************************************/
704 void pjob_delete(const char* sharename, uint32 jobid)
707 struct printjob *pjob;
708 uint32 job_status = 0;
709 struct tdb_print_db *pdb;
711 pdb = get_print_db_byname( sharename );
716 pjob = print_job_find( sharename, jobid );
719 DEBUG(5, ("pjob_delete: we were asked to delete nonexistent job %u\n",
720 (unsigned int)jobid));
721 release_print_db(pdb);
725 /* We must cycle through JOB_STATUS_DELETING and
726 JOB_STATUS_DELETED for the port monitor to delete the job
729 job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
730 notify_job_status(server_event_context(),
731 server_messaging_context(),
732 sharename, jobid, job_status);
734 /* Remove from printing.tdb */
736 tdb_delete(pdb->tdb, print_key(jobid, &tmp));
737 remove_from_jobs_changed(sharename, jobid);
738 release_print_db( pdb );
739 rap_jobid_delete(sharename, jobid);
742 /****************************************************************************
743 List a unix job in the print database.
744 ****************************************************************************/
746 static void print_unix_job(const char *sharename, print_queue_struct *q, uint32 jobid)
748 struct printjob pj, *old_pj;
750 if (jobid == (uint32)-1)
751 jobid = q->job + UNIX_JOB_START;
753 /* Preserve the timestamp on an existing unix print job */
755 old_pj = print_job_find(sharename, jobid);
762 pj.starttime = old_pj ? old_pj->starttime : q->time;
763 pj.status = q->status;
766 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
767 if (jobid < UNIX_JOB_START) {
769 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
772 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
774 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
775 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
777 pjob_store(sharename, jobid, &pj);
781 struct traverse_struct {
782 print_queue_struct *queue;
783 int qcount, snum, maxcount, total_jobs;
784 const char *sharename;
786 const char *lprm_command;
787 struct printif *print_if;
790 /****************************************************************************
791 Utility fn to delete any jobs that are no longer active.
792 ****************************************************************************/
794 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
796 struct traverse_struct *ts = (struct traverse_struct *)state;
797 struct printjob pjob;
801 if ( key.dsize != sizeof(jobid) )
804 jobid = IVAL(key.dptr, 0);
805 if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
807 talloc_free(pjob.devmode);
811 /* remove a unix job if it isn't in the system queue any more */
813 for (i=0;i<ts->qcount;i++) {
814 uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
815 if (jobid == u_jobid)
818 if (i == ts->qcount) {
819 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
820 (unsigned int)jobid ));
821 pjob_delete(ts->sharename, jobid);
825 /* need to continue the the bottom of the function to
826 save the correct attributes */
829 /* maybe it hasn't been spooled yet */
831 /* if a job is not spooled and the process doesn't
832 exist then kill it. This cleans up after smbd
834 if (!process_exists_by_pid(pjob.pid)) {
835 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
836 (unsigned int)jobid, (unsigned int)pjob.pid ));
837 pjob_delete(ts->sharename, jobid);
843 /* this check only makes sense for jobs submitted from Windows clients */
846 for (i=0;i<ts->qcount;i++) {
849 if ( pjob.status == LPQ_DELETED )
852 curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
854 if (jobid == curr_jobid) {
856 /* try to clean up any jobs that need to be deleted */
858 if ( pjob.status == LPQ_DELETING ) {
861 result = (*(ts->print_if->job_delete))(
862 ts->sharename, ts->lprm_command, &pjob );
865 /* if we can't delete, then reset the job status */
866 pjob.status = LPQ_QUEUED;
867 pjob_store(ts->sharename, jobid, &pjob);
870 /* if we deleted the job, the remove the tdb record */
871 pjob_delete(ts->sharename, jobid);
872 pjob.status = LPQ_DELETED;
882 /* The job isn't in the system queue - we have to assume it has
883 completed, so delete the database entry. */
885 if (i == ts->qcount) {
887 /* A race can occur between the time a job is spooled and
888 when it appears in the lpq output. This happens when
889 the job is added to printing.tdb when another smbd
890 running print_queue_update() has completed a lpq and
891 is currently traversing the printing tdb and deleting jobs.
892 Don't delete the job if it was submitted after the lpq_time. */
894 if (pjob.starttime < ts->lpq_time) {
895 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
897 (unsigned int)pjob.starttime,
898 (unsigned int)ts->lpq_time ));
899 pjob_delete(ts->sharename, jobid);
905 /* Save the pjob attributes we will store.
906 FIXME!!! This is the only place where queue->job
907 represents the SMB jobid --jerry */
909 ts->queue[i].job = jobid;
910 ts->queue[i].size = pjob.size;
911 ts->queue[i].page_count = pjob.page_count;
912 ts->queue[i].status = pjob.status;
913 ts->queue[i].priority = 1;
914 ts->queue[i].time = pjob.starttime;
915 fstrcpy(ts->queue[i].fs_user, pjob.user);
916 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
923 /****************************************************************************
924 Check if the print queue has been updated recently enough.
925 ****************************************************************************/
927 static void print_cache_flush(const char *sharename)
930 struct tdb_print_db *pdb = get_print_db_byname(sharename);
934 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
935 tdb_store_int32(pdb->tdb, key, -1);
936 release_print_db(pdb);
939 /****************************************************************************
940 Check if someone already thinks they are doing the update.
941 ****************************************************************************/
943 static pid_t get_updating_pid(const char *sharename)
948 struct tdb_print_db *pdb = get_print_db_byname(sharename);
952 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
953 key = string_tdb_data(keystr);
955 data = tdb_fetch(pdb->tdb, key);
956 release_print_db(pdb);
957 if (!data.dptr || data.dsize != sizeof(pid_t)) {
958 SAFE_FREE(data.dptr);
962 updating_pid = IVAL(data.dptr, 0);
963 SAFE_FREE(data.dptr);
965 if (process_exists_by_pid(updating_pid))
971 /****************************************************************************
972 Set the fact that we're doing the update, or have finished doing the update
974 ****************************************************************************/
976 static void set_updating_pid(const fstring sharename, bool updating)
981 pid_t updating_pid = sys_getpid();
984 struct tdb_print_db *pdb = get_print_db_byname(sharename);
989 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
990 key = string_tdb_data(keystr);
992 DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
993 updating ? "" : "not ",
997 tdb_delete(pdb->tdb, key);
998 release_print_db(pdb);
1002 SIVAL( buffer, 0, updating_pid);
1004 data.dsize = 4; /* we always assume this is a 4 byte value */
1006 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1007 release_print_db(pdb);
1010 /****************************************************************************
1011 Sort print jobs by submittal time.
1012 ****************************************************************************/
1014 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1025 /* Sort on job start time */
1027 if (j1->time == j2->time)
1029 return (j1->time > j2->time) ? 1 : -1;
1032 /****************************************************************************
1033 Store the sorted queue representation for later portmon retrieval.
1035 ****************************************************************************/
1037 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
1040 int max_reported_jobs = lp_max_reported_jobs(pts->snum);
1041 print_queue_struct *queue = pts->queue;
1044 unsigned int qcount;
1046 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
1047 pts->qcount = max_reported_jobs;
1050 /* Work out the size. */
1052 data.dsize += tdb_pack(NULL, 0, "d", qcount);
1054 for (i = 0; i < pts->qcount; i++) {
1055 if ( queue[i].status == LPQ_DELETED )
1059 data.dsize += tdb_pack(NULL, 0, "ddddddff",
1060 (uint32)queue[i].job,
1061 (uint32)queue[i].size,
1062 (uint32)queue[i].page_count,
1063 (uint32)queue[i].status,
1064 (uint32)queue[i].priority,
1065 (uint32)queue[i].time,
1070 if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
1074 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
1075 for (i = 0; i < pts->qcount; i++) {
1076 if ( queue[i].status == LPQ_DELETED )
1079 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
1080 (uint32)queue[i].job,
1081 (uint32)queue[i].size,
1082 (uint32)queue[i].page_count,
1083 (uint32)queue[i].status,
1084 (uint32)queue[i].priority,
1085 (uint32)queue[i].time,
1090 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
1092 SAFE_FREE(data.dptr);
1096 static TDB_DATA get_jobs_changed_data(struct tdb_print_db *pdb)
1102 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
1103 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1104 SAFE_FREE(data.dptr);
1111 static void check_job_changed(const char *sharename, TDB_DATA data, uint32 jobid)
1114 unsigned int job_count = data.dsize / 4;
1116 for (i = 0; i < job_count; i++) {
1119 ch_jobid = IVAL(data.dptr, i*4);
1120 if (ch_jobid == jobid)
1121 remove_from_jobs_changed(sharename, jobid);
1125 /****************************************************************************
1126 Check if the print queue has been updated recently enough.
1127 ****************************************************************************/
1129 static bool print_cache_expired(const char *sharename, bool check_pending)
1132 time_t last_qscan_time, time_now = time(NULL);
1133 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1134 bool result = False;
1139 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1140 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1143 * Invalidate the queue for 3 reasons.
1144 * (1). last queue scan time == -1.
1145 * (2). Current time - last queue scan time > allowed cache time.
1146 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1147 * This last test picks up machines for which the clock has been moved
1148 * forward, an lpq scan done and then the clock moved back. Otherwise
1149 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1152 if (last_qscan_time == ((time_t)-1)
1153 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1154 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1157 time_t msg_pending_time;
1159 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1160 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1161 sharename, (int)last_qscan_time, (int)time_now,
1162 (int)lp_lpqcachetime() ));
1164 /* check if another smbd has already sent a message to update the
1165 queue. Give the pending message one minute to clear and
1166 then send another message anyways. Make sure to check for
1167 clocks that have been run forward and then back again. */
1169 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1172 && tdb_fetch_uint32( pdb->tdb, key, &u )
1173 && (msg_pending_time=u) > 0
1174 && msg_pending_time <= time_now
1175 && (time_now - msg_pending_time) < 60 )
1177 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1186 release_print_db(pdb);
1190 /****************************************************************************
1191 main work for updating the lpq cahe for a printer queue
1192 ****************************************************************************/
1194 static void print_queue_update_internal( const char *sharename,
1195 struct printif *current_printif,
1196 char *lpq_command, char *lprm_command )
1199 print_queue_struct *queue = NULL;
1200 print_status_struct status;
1201 print_status_struct old_status;
1202 struct printjob *pjob;
1203 struct traverse_struct tstruct;
1206 fstring keystr, cachestr;
1207 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1213 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1214 sharename, current_printif->type, lpq_command));
1217 * Update the cache time FIRST ! Stops others even
1218 * attempting to get the lock and doing this
1219 * if the lpq takes a long time.
1222 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1223 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1225 /* get the current queue using the appropriate interface */
1226 ZERO_STRUCT(status);
1228 qcount = (*(current_printif->queue_get))(sharename,
1229 current_printif->type,
1230 lpq_command, &queue, &status);
1232 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1233 qcount, (qcount != 1) ? "s" : "", sharename));
1235 /* Sort the queue by submission time otherwise they are displayed
1238 TYPESAFE_QSORT(queue, qcount, printjob_comp);
1241 any job in the internal database that is marked as spooled
1242 and doesn't exist in the system queue is considered finished
1243 and removed from the database
1245 any job in the system database but not in the internal database
1246 is added as a unix job
1248 fill in any system job numbers as we go
1251 jcdata = get_jobs_changed_data(pdb);
1253 for (i=0; i<qcount; i++) {
1254 uint32 jobid = print_parse_jobid(queue[i].fs_file);
1256 if (jobid == (uint32)-1) {
1257 /* assume its a unix print job */
1258 print_unix_job(sharename, &queue[i], jobid);
1262 /* we have an active SMB print job - update its status */
1263 pjob = print_job_find(sharename, jobid);
1265 /* err, somethings wrong. Probably smbd was restarted
1266 with jobs in the queue. All we can do is treat them
1267 like unix jobs. Pity. */
1268 print_unix_job(sharename, &queue[i], jobid);
1272 pjob->sysjob = queue[i].job;
1274 /* don't reset the status on jobs to be deleted */
1276 if ( pjob->status != LPQ_DELETING )
1277 pjob->status = queue[i].status;
1279 pjob_store(sharename, jobid, pjob);
1281 check_job_changed(sharename, jcdata, jobid);
1284 SAFE_FREE(jcdata.dptr);
1286 /* now delete any queued entries that don't appear in the
1288 tstruct.queue = queue;
1289 tstruct.qcount = qcount;
1291 tstruct.total_jobs = 0;
1292 tstruct.lpq_time = time(NULL);
1293 tstruct.sharename = sharename;
1294 tstruct.lprm_command = lprm_command;
1295 tstruct.print_if = current_printif;
1297 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1299 /* Store the linearised queue, max jobs only. */
1300 store_queue_struct(pdb, &tstruct);
1302 SAFE_FREE(tstruct.queue);
1304 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1305 sharename, tstruct.total_jobs ));
1307 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1309 get_queue_status(sharename, &old_status);
1310 if (old_status.qcount != qcount)
1311 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1312 old_status.qcount, qcount, sharename));
1314 /* store the new queue status structure */
1315 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1316 key = string_tdb_data(keystr);
1318 status.qcount = qcount;
1319 data.dptr = (uint8 *)&status;
1320 data.dsize = sizeof(status);
1321 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1324 * Update the cache time again. We want to do this call
1325 * as little as possible...
1328 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1329 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1331 /* clear the msg pending record for this queue */
1333 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1335 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1336 /* log a message but continue on */
1338 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1342 release_print_db( pdb );
1347 /****************************************************************************
1348 Update the internal database from the system print queue for a queue.
1349 obtain a lock on the print queue before proceeding (needed when mutiple
1350 smbd processes maytry to update the lpq cache concurrently).
1351 ****************************************************************************/
1353 static void print_queue_update_with_lock( const char *sharename,
1354 struct printif *current_printif,
1355 char *lpq_command, char *lprm_command )
1358 struct tdb_print_db *pdb;
1360 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1361 pdb = get_print_db_byname(sharename);
1365 if ( !print_cache_expired(sharename, False) ) {
1366 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1367 release_print_db(pdb);
1372 * Check to see if someone else is doing this update.
1373 * This is essentially a mutex on the update.
1376 if (get_updating_pid(sharename) != -1) {
1377 release_print_db(pdb);
1381 /* Lock the queue for the database update */
1383 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1384 /* Only wait 10 seconds for this. */
1385 if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) == -1) {
1386 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1387 release_print_db(pdb);
1392 * Ensure that no one else got in here.
1393 * If the updating pid is still -1 then we are
1397 if (get_updating_pid(sharename) != -1) {
1399 * Someone else is doing the update, exit.
1401 tdb_unlock_bystring(pdb->tdb, keystr);
1402 release_print_db(pdb);
1407 * We're going to do the update ourselves.
1410 /* Tell others we're doing the update. */
1411 set_updating_pid(sharename, True);
1414 * Allow others to enter and notice we're doing
1418 tdb_unlock_bystring(pdb->tdb, keystr);
1420 /* do the main work now */
1422 print_queue_update_internal( sharename, current_printif,
1423 lpq_command, lprm_command );
1425 /* Delete our pid from the db. */
1426 set_updating_pid(sharename, False);
1427 release_print_db(pdb);
1430 /****************************************************************************
1431 this is the receive function of the background lpq updater
1432 ****************************************************************************/
1433 static void print_queue_receive(struct messaging_context *msg,
1436 struct server_id server_id,
1440 char *lpqcommand = NULL, *lprmcommand = NULL;
1444 len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1451 SAFE_FREE(lpqcommand);
1452 SAFE_FREE(lprmcommand);
1453 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1457 print_queue_update_with_lock(sharename,
1458 get_printer_fns_from_type((enum printing_types)printing_type),
1459 lpqcommand, lprmcommand );
1461 SAFE_FREE(lpqcommand);
1462 SAFE_FREE(lprmcommand);
1466 static void printing_pause_fd_handler(struct tevent_context *ev,
1467 struct tevent_fd *fde,
1472 * If pause_pipe[1] is closed it means the parent smbd
1473 * and children exited or aborted.
1475 exit_server_cleanly(NULL);
1478 extern struct child_pid *children;
1479 extern int num_children;
1481 static void add_child_pid(pid_t pid)
1483 struct child_pid *child;
1485 child = SMB_MALLOC_P(struct child_pid);
1486 if (child == NULL) {
1487 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
1491 DLIST_ADD(children, child);
1495 static pid_t background_lpq_updater_pid = -1;
1497 /****************************************************************************
1498 main thread of the background lpq updater
1499 ****************************************************************************/
1500 void start_background_queue(struct tevent_context *ev,
1501 struct messaging_context *msg_ctx)
1503 /* Use local variables for this as we don't
1504 * need to save the parent side of this, just
1505 * ensure it closes when the process exits.
1509 DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
1511 if (pipe(pause_pipe) == -1) {
1512 DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
1516 background_lpq_updater_pid = sys_fork();
1518 if (background_lpq_updater_pid == -1) {
1519 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
1523 /* Track the printing pid along with other smbd children */
1524 add_child_pid(background_lpq_updater_pid);
1526 if(background_lpq_updater_pid == 0) {
1527 struct tevent_fd *fde;
1532 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
1534 close(pause_pipe[0]);
1537 status = reinit_after_fork(msg_ctx, ev, procid_self(), true);
1539 if (!NT_STATUS_IS_OK(status)) {
1540 DEBUG(0,("reinit_after_fork() failed\n"));
1541 smb_panic("reinit_after_fork() failed");
1544 smbd_setup_sig_term_handler();
1545 smbd_setup_sig_hup_handler(ev, msg_ctx);
1547 if (!serverid_register(procid_self(),
1548 FLAG_MSG_GENERAL|FLAG_MSG_SMBD
1549 |FLAG_MSG_PRINT_GENERAL)) {
1553 if (!locking_init()) {
1557 messaging_register(msg_ctx, NULL, MSG_PRINTER_UPDATE,
1558 print_queue_receive);
1560 fde = tevent_add_fd(ev, ev, pause_pipe[1], TEVENT_FD_READ,
1561 printing_pause_fd_handler,
1564 DEBUG(0,("tevent_add_fd() failed for pause_pipe\n"));
1565 smb_panic("tevent_add_fd() failed for pause_pipe");
1568 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
1569 ret = tevent_loop_wait(ev);
1570 /* should not be reached */
1571 DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
1572 ret, (ret == 0) ? "out of events" : strerror(errno)));
1576 close(pause_pipe[1]);
1579 /****************************************************************************
1580 update the internal database from the system print queue for a queue
1581 ****************************************************************************/
1583 static void print_queue_update(struct messaging_context *msg_ctx,
1584 int snum, bool force)
1588 char *lpqcommand = NULL;
1589 char *lprmcommand = NULL;
1590 uint8 *buffer = NULL;
1593 struct tdb_print_db *pdb;
1595 struct printif *current_printif;
1596 TALLOC_CTX *ctx = talloc_tos();
1598 fstrcpy( sharename, lp_const_servicename(snum));
1600 /* don't strip out characters like '$' from the printername */
1602 lpqcommand = talloc_string_sub2(ctx,
1603 lp_lpqcommand(snum),
1605 lp_printername(snum),
1606 false, false, false);
1610 lpqcommand = talloc_sub_advanced(ctx,
1611 lp_servicename(snum),
1612 current_user_info.unix_name,
1614 current_user.ut.gid,
1615 get_current_username(),
1616 current_user_info.domain,
1622 lprmcommand = talloc_string_sub2(ctx,
1623 lp_lprmcommand(snum),
1625 lp_printername(snum),
1626 false, false, false);
1630 lprmcommand = talloc_sub_advanced(ctx,
1631 lp_servicename(snum),
1632 current_user_info.unix_name,
1634 current_user.ut.gid,
1635 get_current_username(),
1636 current_user_info.domain,
1643 * Make sure that the background queue process exists.
1644 * Otherwise just do the update ourselves
1647 if ( force || background_lpq_updater_pid == -1 ) {
1648 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1649 current_printif = get_printer_fns( snum );
1650 print_queue_update_with_lock( sharename, current_printif, lpqcommand, lprmcommand );
1655 type = lp_printing(snum);
1657 /* get the length */
1659 len = tdb_pack( NULL, 0, "fdPP",
1665 buffer = SMB_XMALLOC_ARRAY( uint8, len );
1667 /* now pack the buffer */
1668 newlen = tdb_pack( buffer, len, "fdPP",
1674 SMB_ASSERT( newlen == len );
1676 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1677 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1678 sharename, type, lpqcommand, lprmcommand ));
1680 /* here we set a msg pending record for other smbd processes
1681 to throttle the number of duplicate print_queue_update msgs
1684 pdb = get_print_db_byname(sharename);
1690 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1692 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1693 /* log a message but continue on */
1695 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1699 release_print_db( pdb );
1701 /* finally send the message */
1703 messaging_send_buf(msg_ctx, pid_to_procid(background_lpq_updater_pid),
1704 MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1706 SAFE_FREE( buffer );
1711 /****************************************************************************
1712 Create/Update an entry in the print tdb that will allow us to send notify
1713 updates only to interested smbd's.
1714 ****************************************************************************/
1716 bool print_notify_register_pid(int snum)
1719 struct tdb_print_db *pdb = NULL;
1720 TDB_CONTEXT *tdb = NULL;
1721 const char *printername;
1722 uint32 mypid = (uint32)sys_getpid();
1726 /* if (snum == -1), then the change notify request was
1727 on a print server handle and we need to register on
1732 int num_services = lp_numservices();
1735 for ( idx=0; idx<num_services; idx++ ) {
1736 if (lp_snum_ok(idx) && lp_print_ok(idx) )
1737 print_notify_register_pid(idx);
1742 else /* register for a specific printer */
1744 printername = lp_const_servicename(snum);
1745 pdb = get_print_db_byname(printername);
1751 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1752 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1755 release_print_db(pdb);
1759 data = get_printer_notify_pid_list( tdb, printername, True );
1761 /* Add ourselves and increase the refcount. */
1763 for (i = 0; i < data.dsize; i += 8) {
1764 if (IVAL(data.dptr,i) == mypid) {
1765 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1766 SIVAL(data.dptr, i+4, new_refcount);
1771 if (i == data.dsize) {
1772 /* We weren't in the list. Realloc. */
1773 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1775 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1780 SIVAL(data.dptr,data.dsize - 8,mypid);
1781 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1784 /* Store back the record. */
1785 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1786 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1787 list for printer %s\n", printername));
1795 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1797 release_print_db(pdb);
1798 SAFE_FREE(data.dptr);
1802 /****************************************************************************
1803 Update an entry in the print tdb that will allow us to send notify
1804 updates only to interested smbd's.
1805 ****************************************************************************/
1807 bool print_notify_deregister_pid(int snum)
1810 struct tdb_print_db *pdb = NULL;
1811 TDB_CONTEXT *tdb = NULL;
1812 const char *printername;
1813 uint32 mypid = (uint32)sys_getpid();
1817 /* if ( snum == -1 ), we are deregister a print server handle
1818 which means to deregister on all print queues */
1822 int num_services = lp_numservices();
1825 for ( idx=0; idx<num_services; idx++ ) {
1826 if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1827 print_notify_deregister_pid(idx);
1832 else /* deregister a specific printer */
1834 printername = lp_const_servicename(snum);
1835 pdb = get_print_db_byname(printername);
1841 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1842 DEBUG(0,("print_notify_register_pid: Failed to lock \
1843 printer %s database\n", printername));
1845 release_print_db(pdb);
1849 data = get_printer_notify_pid_list( tdb, printername, True );
1851 /* Reduce refcount. Remove ourselves if zero. */
1853 for (i = 0; i < data.dsize; ) {
1854 if (IVAL(data.dptr,i) == mypid) {
1855 uint32 refcount = IVAL(data.dptr, i+4);
1859 if (refcount == 0) {
1860 if (data.dsize - i > 8)
1861 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1865 SIVAL(data.dptr, i+4, refcount);
1871 if (data.dsize == 0)
1872 SAFE_FREE(data.dptr);
1874 /* Store back the record. */
1875 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1876 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1877 list for printer %s\n", printername));
1885 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1887 release_print_db(pdb);
1888 SAFE_FREE(data.dptr);
1892 /****************************************************************************
1893 Check if a jobid is valid. It is valid if it exists in the database.
1894 ****************************************************************************/
1896 bool print_job_exists(const char* sharename, uint32 jobid)
1898 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1904 ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
1905 release_print_db(pdb);
1909 /****************************************************************************
1910 Give the filename used for a jobid.
1911 Only valid for the process doing the spooling and when the job
1912 has not been spooled.
1913 ****************************************************************************/
1915 char *print_job_fname(const char* sharename, uint32 jobid)
1917 struct printjob *pjob = print_job_find(sharename, jobid);
1918 if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
1920 return pjob->filename;
1924 /****************************************************************************
1925 Give the filename used for a jobid.
1926 Only valid for the process doing the spooling and when the job
1927 has not been spooled.
1928 ****************************************************************************/
1930 struct spoolss_DeviceMode *print_job_devmode(const char* sharename, uint32 jobid)
1932 struct printjob *pjob = print_job_find(sharename, jobid);
1937 return pjob->devmode;
1940 /****************************************************************************
1941 Set the name of a job. Only possible for owner.
1942 ****************************************************************************/
1944 bool print_job_set_name(const char *sharename, uint32 jobid, const char *name)
1946 struct printjob *pjob;
1948 pjob = print_job_find(sharename, jobid);
1949 if (!pjob || pjob->pid != sys_getpid())
1952 fstrcpy(pjob->jobname, name);
1953 return pjob_store(sharename, jobid, pjob);
1956 /****************************************************************************
1957 Get the name of a job. Only possible for owner.
1958 ****************************************************************************/
1960 bool print_job_get_name(TALLOC_CTX *mem_ctx, const char *sharename, uint32_t jobid, char **name)
1962 struct printjob *pjob;
1964 pjob = print_job_find(sharename, jobid);
1965 if (!pjob || pjob->pid != sys_getpid()) {
1969 *name = talloc_strdup(mem_ctx, pjob->jobname);
1978 /***************************************************************************
1979 Remove a jobid from the 'jobs changed' list.
1980 ***************************************************************************/
1982 static bool remove_from_jobs_changed(const char* sharename, uint32 jobid)
1984 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1986 size_t job_count, i;
1988 bool gotlock = False;
1996 key = string_tdb_data("INFO/jobs_changed");
1998 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
2003 data = tdb_fetch(pdb->tdb, key);
2005 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
2008 job_count = data.dsize / 4;
2009 for (i = 0; i < job_count; i++) {
2012 ch_jobid = IVAL(data.dptr, i*4);
2013 if (ch_jobid == jobid) {
2014 if (i < job_count -1 )
2015 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
2017 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
2027 tdb_chainunlock(pdb->tdb, key);
2028 SAFE_FREE(data.dptr);
2029 release_print_db(pdb);
2031 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
2033 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
2037 /****************************************************************************
2038 Delete a print job - don't update queue.
2039 ****************************************************************************/
2041 static bool print_job_delete1(int snum, uint32 jobid)
2043 const char* sharename = lp_const_servicename(snum);
2044 struct printjob *pjob = print_job_find(sharename, jobid);
2046 struct printif *current_printif = get_printer_fns( snum );
2052 * If already deleting just return.
2055 if (pjob->status == LPQ_DELETING)
2058 /* Hrm - we need to be able to cope with deleting a job before it
2059 has reached the spooler. Just mark it as LPQ_DELETING and
2060 let the print_queue_update() code rmeove the record */
2063 if (pjob->sysjob == -1) {
2064 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
2067 /* Set the tdb entry to be deleting. */
2069 pjob->status = LPQ_DELETING;
2070 pjob_store(sharename, jobid, pjob);
2072 if (pjob->spooled && pjob->sysjob != -1)
2074 result = (*(current_printif->job_delete))(
2075 lp_printername(snum),
2076 lp_lprmcommand(snum),
2079 /* Delete the tdb entry if the delete succeeded or the job hasn't
2083 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2088 pjob_delete(sharename, jobid);
2089 /* Ensure we keep a rough count of the number of total jobs... */
2090 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
2091 release_print_db(pdb);
2095 remove_from_jobs_changed( sharename, jobid );
2097 return (result == 0);
2100 /****************************************************************************
2101 Return true if the current user owns the print job.
2102 ****************************************************************************/
2104 static bool is_owner(struct auth_serversupplied_info *server_info,
2105 const char *servicename,
2108 struct printjob *pjob = print_job_find(servicename, jobid);
2110 if (!pjob || !server_info)
2113 return strequal(pjob->user, server_info->sanitized_username);
2116 /****************************************************************************
2118 ****************************************************************************/
2120 WERROR print_job_delete(struct auth_serversupplied_info *server_info,
2121 struct messaging_context *msg_ctx,
2122 int snum, uint32_t jobid)
2124 const char* sharename = lp_const_servicename(snum);
2125 struct printjob *pjob;
2129 owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2131 /* Check access against security descriptor or whether the user
2135 !print_access_check(server_info, msg_ctx, snum,
2136 JOB_ACCESS_ADMINISTER)) {
2137 DEBUG(3, ("delete denied by security descriptor\n"));
2139 /* BEGIN_ADMIN_LOG */
2140 sys_adminlog( LOG_ERR,
2141 "Permission denied-- user not allowed to delete, \
2142 pause, or resume print job. User name: %s. Printer name: %s.",
2143 uidtoname(server_info->utok.uid),
2144 lp_printername(snum) );
2147 return WERR_ACCESS_DENIED;
2151 * get the spooled filename of the print job
2152 * if this works, then the file has not been spooled
2153 * to the underlying print system. Just delete the
2154 * spool file & return.
2157 fname = print_job_fname(sharename, jobid);
2158 if (fname != NULL) {
2159 /* remove the spool file */
2160 DEBUG(10, ("print_job_delete: "
2161 "Removing spool file [%s]\n", fname));
2162 if (unlink(fname) == -1) {
2163 return map_werror_from_unix(errno);
2167 if (!print_job_delete1(snum, jobid)) {
2168 return WERR_ACCESS_DENIED;
2171 /* force update the database and say the delete failed if the
2174 print_queue_update(msg_ctx, snum, True);
2176 pjob = print_job_find(sharename, jobid);
2177 if (pjob && (pjob->status != LPQ_DELETING)) {
2178 return WERR_ACCESS_DENIED;
2181 return WERR_PRINTER_HAS_JOBS_QUEUED;
2184 /****************************************************************************
2186 ****************************************************************************/
2188 bool print_job_pause(struct auth_serversupplied_info *server_info,
2189 struct messaging_context *msg_ctx,
2190 int snum, uint32 jobid, WERROR *errcode)
2192 const char* sharename = lp_const_servicename(snum);
2193 struct printjob *pjob;
2195 struct printif *current_printif = get_printer_fns( snum );
2197 pjob = print_job_find(sharename, jobid);
2199 if (!pjob || !server_info) {
2200 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2201 (unsigned int)jobid ));
2205 if (!pjob->spooled || pjob->sysjob == -1) {
2206 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2207 (int)pjob->sysjob, (unsigned int)jobid ));
2211 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2212 !print_access_check(server_info, msg_ctx, snum,
2213 JOB_ACCESS_ADMINISTER)) {
2214 DEBUG(3, ("pause denied by security descriptor\n"));
2216 /* BEGIN_ADMIN_LOG */
2217 sys_adminlog( LOG_ERR,
2218 "Permission denied-- user not allowed to delete, \
2219 pause, or resume print job. User name: %s. Printer name: %s.",
2220 uidtoname(server_info->utok.uid),
2221 lp_printername(snum) );
2224 *errcode = WERR_ACCESS_DENIED;
2228 /* need to pause the spooled entry */
2229 ret = (*(current_printif->job_pause))(snum, pjob);
2232 *errcode = WERR_INVALID_PARAM;
2236 /* force update the database */
2237 print_cache_flush(lp_const_servicename(snum));
2239 /* Send a printer notify message */
2241 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2244 /* how do we tell if this succeeded? */
2249 /****************************************************************************
2251 ****************************************************************************/
2253 bool print_job_resume(struct auth_serversupplied_info *server_info,
2254 struct messaging_context *msg_ctx,
2255 int snum, uint32 jobid, WERROR *errcode)
2257 const char *sharename = lp_const_servicename(snum);
2258 struct printjob *pjob;
2260 struct printif *current_printif = get_printer_fns( snum );
2262 pjob = print_job_find(sharename, jobid);
2264 if (!pjob || !server_info) {
2265 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2266 (unsigned int)jobid ));
2270 if (!pjob->spooled || pjob->sysjob == -1) {
2271 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2272 (int)pjob->sysjob, (unsigned int)jobid ));
2276 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2277 !print_access_check(server_info, msg_ctx, snum,
2278 JOB_ACCESS_ADMINISTER)) {
2279 DEBUG(3, ("resume denied by security descriptor\n"));
2280 *errcode = WERR_ACCESS_DENIED;
2282 /* BEGIN_ADMIN_LOG */
2283 sys_adminlog( LOG_ERR,
2284 "Permission denied-- user not allowed to delete, \
2285 pause, or resume print job. User name: %s. Printer name: %s.",
2286 uidtoname(server_info->utok.uid),
2287 lp_printername(snum) );
2292 ret = (*(current_printif->job_resume))(snum, pjob);
2295 *errcode = WERR_INVALID_PARAM;
2299 /* force update the database */
2300 print_cache_flush(lp_const_servicename(snum));
2302 /* Send a printer notify message */
2304 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2310 /****************************************************************************
2311 Write to a print file.
2312 ****************************************************************************/
2314 ssize_t print_job_write(int snum, uint32 jobid, const char *buf, SMB_OFF_T pos, size_t size)
2316 const char* sharename = lp_const_servicename(snum);
2317 ssize_t return_code;
2318 struct printjob *pjob;
2320 pjob = print_job_find(sharename, jobid);
2324 /* don't allow another process to get this info - it is meaningless */
2325 if (pjob->pid != sys_getpid())
2328 /* if SMBD is spooling this can't be allowed */
2329 if (pjob->status == PJOB_SMBD_SPOOLING) {
2333 return_code = write_data_at_offset(pjob->fd, buf, size, pos);
2335 if (return_code>0) {
2337 pjob_store(sharename, jobid, pjob);
2342 /****************************************************************************
2343 Get the queue status - do not update if db is out of date.
2344 ****************************************************************************/
2346 static int get_queue_status(const char* sharename, print_status_struct *status)
2350 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2354 ZERO_STRUCTP(status);
2361 fstr_sprintf(keystr, "STATUS/%s", sharename);
2362 data = tdb_fetch(pdb->tdb, string_tdb_data(keystr));
2364 if (data.dsize == sizeof(print_status_struct))
2365 /* this memcpy is ok since the status struct was
2366 not packed before storing it in the tdb */
2367 memcpy(status, data.dptr, sizeof(print_status_struct));
2368 SAFE_FREE(data.dptr);
2371 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2372 release_print_db(pdb);
2373 return (len == -1 ? 0 : len);
2376 /****************************************************************************
2377 Determine the number of jobs in a queue.
2378 ****************************************************************************/
2380 int print_queue_length(struct messaging_context *msg_ctx, int snum,
2381 print_status_struct *pstatus)
2383 const char* sharename = lp_const_servicename( snum );
2384 print_status_struct status;
2387 ZERO_STRUCT( status );
2389 /* make sure the database is up to date */
2390 if (print_cache_expired(lp_const_servicename(snum), True))
2391 print_queue_update(msg_ctx, snum, False);
2393 /* also fetch the queue status */
2394 memset(&status, 0, sizeof(status));
2395 len = get_queue_status(sharename, &status);
2403 /***************************************************************************
2404 Allocate a jobid. Hold the lock for as short a time as possible.
2405 ***************************************************************************/
2407 static WERROR allocate_print_jobid(struct tdb_print_db *pdb, int snum,
2408 const char *sharename, uint32 *pjobid)
2412 enum TDB_ERROR terr;
2415 *pjobid = (uint32)-1;
2417 for (i = 0; i < 3; i++) {
2418 /* Lock the database - only wait 20 seconds. */
2419 ret = tdb_lock_bystring_with_timeout(pdb->tdb,
2420 "INFO/nextjob", 20);
2422 DEBUG(0, ("allocate_print_jobid: "
2423 "Failed to lock printing database %s\n",
2425 terr = tdb_error(pdb->tdb);
2426 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2429 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2430 terr = tdb_error(pdb->tdb);
2431 if (terr != TDB_ERR_NOEXIST) {
2432 DEBUG(0, ("allocate_print_jobid: "
2433 "Failed to fetch INFO/nextjob "
2434 "for print queue %s\n", sharename));
2435 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2436 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2438 DEBUG(10, ("allocate_print_jobid: "
2439 "No existing jobid in %s\n", sharename));
2443 DEBUG(10, ("allocate_print_jobid: "
2444 "Read jobid %u from %s\n", jobid, sharename));
2446 jobid = NEXT_JOBID(jobid);
2448 ret = tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid);
2450 terr = tdb_error(pdb->tdb);
2451 DEBUG(3, ("allocate_print_jobid: "
2452 "Failed to store INFO/nextjob.\n"));
2453 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2454 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2457 /* We've finished with the INFO/nextjob lock. */
2458 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2460 if (!print_job_exists(sharename, jobid)) {
2463 DEBUG(10, ("allocate_print_jobid: "
2464 "Found jobid %u in %s\n", jobid, sharename));
2468 DEBUG(0, ("allocate_print_jobid: "
2469 "Failed to allocate a print job for queue %s\n",
2471 /* Probably full... */
2472 return WERR_NO_SPOOL_SPACE;
2475 /* Store a dummy placeholder. */
2481 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2482 TDB_INSERT) == -1) {
2483 DEBUG(3, ("allocate_print_jobid: "
2484 "jobid (%d) failed to store placeholder.\n",
2486 terr = tdb_error(pdb->tdb);
2487 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2495 /***************************************************************************
2496 Append a jobid to the 'jobs changed' list.
2497 ***************************************************************************/
2499 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32 jobid)
2504 SIVAL(&store_jobid, 0, jobid);
2505 data.dptr = (uint8 *)&store_jobid;
2508 DEBUG(10,("add_to_jobs_changed: Added jobid %u\n", (unsigned int)jobid ));
2510 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
2515 /***************************************************************************
2516 Do all checks needed to determine if we can start a job.
2517 ***************************************************************************/
2519 static WERROR print_job_checks(struct auth_serversupplied_info *server_info,
2520 struct messaging_context *msg_ctx,
2521 int snum, int *njobs)
2523 const char *sharename = lp_const_servicename(snum);
2524 uint64_t dspace, dsize;
2528 if (!print_access_check(server_info, msg_ctx, snum,
2529 PRINTER_ACCESS_USE)) {
2530 DEBUG(3, ("print_job_checks: "
2531 "job start denied by security descriptor\n"));
2532 return WERR_ACCESS_DENIED;
2535 if (!print_time_access_check(server_info, msg_ctx, sharename)) {
2536 DEBUG(3, ("print_job_checks: "
2537 "job start denied by time check\n"));
2538 return WERR_ACCESS_DENIED;
2541 /* see if we have sufficient disk space */
2542 if (lp_minprintspace(snum)) {
2543 minspace = lp_minprintspace(snum);
2544 ret = sys_fsusage(lp_pathname(snum), &dspace, &dsize);
2545 if (ret == 0 && dspace < 2*minspace) {
2546 DEBUG(3, ("print_job_checks: "
2547 "disk space check failed.\n"));
2548 return WERR_NO_SPOOL_SPACE;
2552 /* for autoloaded printers, check that the printcap entry still exists */
2553 if (lp_autoloaded(snum) && !pcap_printername_ok(sharename)) {
2554 DEBUG(3, ("print_job_checks: printer name %s check failed.\n",
2556 return WERR_ACCESS_DENIED;
2559 /* Insure the maximum queue size is not violated */
2560 *njobs = print_queue_length(msg_ctx, snum, NULL);
2561 if (*njobs > lp_maxprintjobs(snum)) {
2562 DEBUG(3, ("print_job_checks: Queue %s number of jobs (%d) "
2563 "larger than max printjobs per queue (%d).\n",
2564 sharename, *njobs, lp_maxprintjobs(snum)));
2565 return WERR_NO_SPOOL_SPACE;
2571 /***************************************************************************
2573 ***************************************************************************/
2575 static WERROR print_job_spool_file(int snum, uint32_t jobid,
2576 const char *output_file,
2577 struct printjob *pjob)
2584 /* if this file is within the printer path, it means that smbd
2585 * is spooling it and will pass us control when it is finished.
2586 * Verify that the file name is ok, within path, and it is
2587 * already already there */
2589 path = lp_pathname(snum);
2591 if (strncmp(output_file, path, len) == 0 &&
2592 (output_file[len - 1] == '/' || output_file[len] == '/')) {
2594 /* verify path is not too long */
2595 if (strlen(output_file) >= sizeof(pjob->filename)) {
2596 return WERR_INVALID_NAME;
2599 /* verify that the file exists */
2600 if (sys_stat(output_file, &st, false) != 0) {
2601 return WERR_INVALID_NAME;
2604 fstrcpy(pjob->filename, output_file);
2606 DEBUG(3, ("print_job_spool_file:"
2607 "External spooling activated"));
2609 /* we do not open the file until spooling is done */
2611 pjob->status = PJOB_SMBD_SPOOLING;
2617 slprintf(pjob->filename, sizeof(pjob->filename)-1,
2618 "%s/%s%.8u.XXXXXX", lp_pathname(snum),
2619 PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2620 pjob->fd = mkstemp(pjob->filename);
2622 if (pjob->fd == -1) {
2623 werr = map_werror_from_unix(errno);
2624 if (W_ERROR_EQUAL(werr, WERR_ACCESS_DENIED)) {
2625 /* Common setup error, force a report. */
2626 DEBUG(0, ("print_job_spool_file: "
2627 "insufficient permissions to open spool "
2628 "file %s.\n", pjob->filename));
2630 /* Normal case, report at level 3 and above. */
2631 DEBUG(3, ("print_job_spool_file: "
2632 "can't open spool file %s\n",
2641 /***************************************************************************
2642 Start spooling a job - return the jobid.
2643 ***************************************************************************/
2645 WERROR print_job_start(struct auth_serversupplied_info *server_info,
2646 struct messaging_context *msg_ctx,
2647 int snum, const char *docname, const char *filename,
2648 struct spoolss_DeviceMode *devmode, uint32_t *_jobid)
2652 struct printjob pjob;
2653 const char *sharename = lp_const_servicename(snum);
2654 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2659 return WERR_INTERNAL_DB_CORRUPTION;
2662 path = lp_pathname(snum);
2664 werr = print_job_checks(server_info, msg_ctx, snum, &njobs);
2665 if (!W_ERROR_IS_OK(werr)) {
2666 release_print_db(pdb);
2670 DEBUG(10, ("print_job_start: "
2671 "Queue %s number of jobs (%d), max printjobs = %d\n",
2672 sharename, njobs, lp_maxprintjobs(snum)));
2674 werr = allocate_print_jobid(pdb, snum, sharename, &jobid);
2675 if (!W_ERROR_IS_OK(werr)) {
2679 /* create the database entry */
2683 pjob.pid = sys_getpid();
2686 pjob.starttime = time(NULL);
2687 pjob.status = LPQ_SPOOLING;
2689 pjob.spooled = False;
2691 pjob.devmode = devmode;
2693 fstrcpy(pjob.jobname, docname);
2695 fstrcpy(pjob.user, lp_printjob_username(snum));
2696 standard_sub_advanced(sharename, server_info->sanitized_username,
2697 path, server_info->utok.gid,
2698 server_info->sanitized_username,
2699 server_info->info3->base.domain.string,
2700 pjob.user, sizeof(pjob.user)-1);
2701 /* ensure NULL termination */
2702 pjob.user[sizeof(pjob.user)-1] = '\0';
2704 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2706 /* we have a job entry - now create the spool file */
2707 werr = print_job_spool_file(snum, jobid, filename, &pjob);
2708 if (!W_ERROR_IS_OK(werr)) {
2712 pjob_store(sharename, jobid, &pjob);
2714 /* Update the 'jobs changed' entry used by print_queue_status. */
2715 add_to_jobs_changed(pdb, jobid);
2717 /* Ensure we keep a rough count of the number of total jobs... */
2718 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2720 release_print_db(pdb);
2727 pjob_delete(sharename, jobid);
2730 release_print_db(pdb);
2732 DEBUG(3, ("print_job_start: returning fail. "
2733 "Error = %s\n", win_errstr(werr)));
2737 /****************************************************************************
2738 Update the number of pages spooled to jobid
2739 ****************************************************************************/
2741 void print_job_endpage(int snum, uint32 jobid)
2743 const char* sharename = lp_const_servicename(snum);
2744 struct printjob *pjob;
2746 pjob = print_job_find(sharename, jobid);
2749 /* don't allow another process to get this info - it is meaningless */
2750 if (pjob->pid != sys_getpid())
2754 pjob_store(sharename, jobid, pjob);
2757 /****************************************************************************
2758 Print a file - called on closing the file. This spools the job.
2759 If normal close is false then we're tearing down the jobs - treat as an
2761 ****************************************************************************/
2763 NTSTATUS print_job_end(struct messaging_context *msg_ctx, int snum,
2764 uint32 jobid, enum file_close_type close_type)
2766 const char* sharename = lp_const_servicename(snum);
2767 struct printjob *pjob;
2769 SMB_STRUCT_STAT sbuf;
2770 struct printif *current_printif = get_printer_fns( snum );
2771 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2773 pjob = print_job_find(sharename, jobid);
2776 return NT_STATUS_PRINT_CANCELLED;
2779 if (pjob->spooled || pjob->pid != sys_getpid()) {
2780 return NT_STATUS_ACCESS_DENIED;
2783 if (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) {
2784 if (pjob->status == PJOB_SMBD_SPOOLING) {
2785 /* take over the file now, smbd is done */
2786 if (sys_stat(pjob->filename, &sbuf, false) != 0) {
2787 status = map_nt_error_from_unix(errno);
2788 DEBUG(3, ("print_job_end: "
2789 "stat file failed for jobid %d\n",
2794 pjob->status = LPQ_SPOOLING;
2798 if ((sys_fstat(pjob->fd, &sbuf, false) != 0)) {
2799 status = map_nt_error_from_unix(errno);
2801 DEBUG(3, ("print_job_end: "
2802 "stat file failed for jobid %d\n",
2810 pjob->size = sbuf.st_ex_size;
2814 * Not a normal close, something has gone wrong. Cleanup.
2816 if (pjob->fd != -1) {
2822 /* Technically, this is not quite right. If the printer has a separator
2823 * page turned on, the NT spooler prints the separator page even if the
2824 * print job is 0 bytes. 010215 JRR */
2825 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
2826 /* don't bother spooling empty files or something being deleted. */
2827 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
2828 pjob->filename, pjob->size ? "deleted" : "zero length" ));
2829 unlink(pjob->filename);
2830 pjob_delete(sharename, jobid);
2831 return NT_STATUS_OK;
2834 ret = (*(current_printif->job_submit))(snum, pjob);
2837 status = NT_STATUS_PRINT_CANCELLED;
2841 /* The print job has been successfully handed over to the back-end */
2843 pjob->spooled = True;
2844 pjob->status = LPQ_QUEUED;
2845 pjob_store(sharename, jobid, pjob);
2847 /* make sure the database is up to date */
2848 if (print_cache_expired(lp_const_servicename(snum), True))
2849 print_queue_update(msg_ctx, snum, False);
2851 return NT_STATUS_OK;
2855 /* The print job was not successfully started. Cleanup */
2856 /* Still need to add proper error return propagation! 010122:JRR */
2858 unlink(pjob->filename);
2859 pjob_delete(sharename, jobid);
2863 /****************************************************************************
2864 Get a snapshot of jobs in the system without traversing.
2865 ****************************************************************************/
2867 static bool get_stored_queue_info(struct messaging_context *msg_ctx,
2868 struct tdb_print_db *pdb, int snum,
2869 int *pcount, print_queue_struct **ppqueue)
2871 TDB_DATA data, cgdata;
2872 print_queue_struct *queue = NULL;
2874 uint32 extra_count = 0;
2875 int total_count = 0;
2878 int max_reported_jobs = lp_max_reported_jobs(snum);
2880 const char* sharename = lp_servicename(snum);
2882 /* make sure the database is up to date */
2883 if (print_cache_expired(lp_const_servicename(snum), True))
2884 print_queue_update(msg_ctx, snum, False);
2890 ZERO_STRUCT(cgdata);
2892 /* Get the stored queue data. */
2893 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
2895 if (data.dptr && data.dsize >= sizeof(qcount))
2896 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
2898 /* Get the changed jobs list. */
2899 cgdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
2900 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
2901 extra_count = cgdata.dsize/4;
2903 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
2905 /* Allocate the queue size. */
2906 if (qcount == 0 && extra_count == 0)
2909 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
2912 /* Retrieve the linearised queue data. */
2914 for( i = 0; i < qcount; i++) {
2915 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
2916 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
2925 queue[i].job = qjob;
2926 queue[i].size = qsize;
2927 queue[i].page_count = qpage_count;
2928 queue[i].status = qstatus;
2929 queue[i].priority = qpriority;
2930 queue[i].time = qtime;
2933 total_count = qcount;
2935 /* Add in the changed jobids. */
2936 for( i = 0; i < extra_count; i++) {
2938 struct printjob *pjob;
2940 jobid = IVAL(cgdata.dptr, i*4);
2941 DEBUG(5,("get_stored_queue_info: changed job = %u\n", (unsigned int)jobid));
2942 pjob = print_job_find(lp_const_servicename(snum), jobid);
2944 DEBUG(5,("get_stored_queue_info: failed to find changed job = %u\n", (unsigned int)jobid));
2945 remove_from_jobs_changed(sharename, jobid);
2949 queue[total_count].job = jobid;
2950 queue[total_count].size = pjob->size;
2951 queue[total_count].page_count = pjob->page_count;
2952 queue[total_count].status = pjob->status;
2953 queue[total_count].priority = 1;
2954 queue[total_count].time = pjob->starttime;
2955 fstrcpy(queue[total_count].fs_user, pjob->user);
2956 fstrcpy(queue[total_count].fs_file, pjob->jobname);
2960 /* Sort the queue by submission time otherwise they are displayed
2963 TYPESAFE_QSORT(queue, total_count, printjob_comp);
2965 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
2967 if (max_reported_jobs && total_count > max_reported_jobs)
2968 total_count = max_reported_jobs;
2971 *pcount = total_count;
2977 SAFE_FREE(data.dptr);
2978 SAFE_FREE(cgdata.dptr);
2982 /****************************************************************************
2983 Get a printer queue listing.
2984 set queue = NULL and status = NULL if you just want to update the cache
2985 ****************************************************************************/
2987 int print_queue_status(struct messaging_context *msg_ctx, int snum,
2988 print_queue_struct **ppqueue,
2989 print_status_struct *status)
2993 const char *sharename;
2994 struct tdb_print_db *pdb;
2997 /* make sure the database is up to date */
2999 if (print_cache_expired(lp_const_servicename(snum), True))
3000 print_queue_update(msg_ctx, snum, False);
3002 /* return if we are done */
3003 if ( !ppqueue || !status )
3007 sharename = lp_const_servicename(snum);
3008 pdb = get_print_db_byname(sharename);
3014 * Fetch the queue status. We must do this first, as there may
3015 * be no jobs in the queue.
3018 ZERO_STRUCTP(status);
3019 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
3020 key = string_tdb_data(keystr);
3022 data = tdb_fetch(pdb->tdb, key);
3024 if (data.dsize == sizeof(*status)) {
3025 /* this memcpy is ok since the status struct was
3026 not packed before storing it in the tdb */
3027 memcpy(status, data.dptr, sizeof(*status));
3029 SAFE_FREE(data.dptr);
3033 * Now, fetch the print queue information. We first count the number
3034 * of entries, and then only retrieve the queue if necessary.
3037 if (!get_stored_queue_info(msg_ctx, pdb, snum, &count, ppqueue)) {
3038 release_print_db(pdb);
3042 release_print_db(pdb);
3046 /****************************************************************************
3048 ****************************************************************************/
3050 WERROR print_queue_pause(struct auth_serversupplied_info *server_info,
3051 struct messaging_context *msg_ctx, int snum)
3054 struct printif *current_printif = get_printer_fns( snum );
3056 if (!print_access_check(server_info, msg_ctx, snum,
3057 PRINTER_ACCESS_ADMINISTER)) {
3058 return WERR_ACCESS_DENIED;
3064 ret = (*(current_printif->queue_pause))(snum);
3069 return WERR_INVALID_PARAM;
3072 /* force update the database */
3073 print_cache_flush(lp_const_servicename(snum));
3075 /* Send a printer notify message */
3077 notify_printer_status(server_event_context(), msg_ctx, snum,
3078 PRINTER_STATUS_PAUSED);
3083 /****************************************************************************
3085 ****************************************************************************/
3087 WERROR print_queue_resume(struct auth_serversupplied_info *server_info,
3088 struct messaging_context *msg_ctx, int snum)
3091 struct printif *current_printif = get_printer_fns( snum );
3093 if (!print_access_check(server_info, msg_ctx, snum,
3094 PRINTER_ACCESS_ADMINISTER)) {
3095 return WERR_ACCESS_DENIED;
3100 ret = (*(current_printif->queue_resume))(snum);
3105 return WERR_INVALID_PARAM;
3108 /* make sure the database is up to date */
3109 if (print_cache_expired(lp_const_servicename(snum), True))
3110 print_queue_update(msg_ctx, snum, True);
3112 /* Send a printer notify message */
3114 notify_printer_status(server_event_context(), msg_ctx, snum,
3120 /****************************************************************************
3121 Purge a queue - implemented by deleting all jobs that we can delete.
3122 ****************************************************************************/
3124 WERROR print_queue_purge(struct auth_serversupplied_info *server_info,
3125 struct messaging_context *msg_ctx, int snum)
3127 print_queue_struct *queue;
3128 print_status_struct status;
3132 /* Force and update so the count is accurate (i.e. not a cached count) */
3133 print_queue_update(msg_ctx, snum, True);
3135 can_job_admin = print_access_check(server_info,
3138 JOB_ACCESS_ADMINISTER);
3139 njobs = print_queue_status(msg_ctx, snum, &queue, &status);
3141 if ( can_job_admin )
3144 for (i=0;i<njobs;i++) {
3145 bool owner = is_owner(server_info, lp_const_servicename(snum),
3148 if (owner || can_job_admin) {
3149 print_job_delete1(snum, queue[i].job);
3153 if ( can_job_admin )
3156 /* update the cache */
3157 print_queue_update(msg_ctx, snum, True);