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/>.
23 #include "system/syslog.h"
24 #include "system/filesys.h"
26 #include "../librpc/gen_ndr/ndr_spoolss.h"
27 #include "nt_printing.h"
28 #include "../librpc/gen_ndr/netlogon.h"
29 #include "printing/notify.h"
30 #include "printing/pcap.h"
32 #include "smbd/smbd.h"
37 extern struct current_user current_user;
38 extern userdom_struct current_user_info;
40 /* Current printer interface */
41 static bool remove_from_jobs_added(const char* sharename, uint32 jobid);
44 the printing backend revolves around a tdb database that stores the
45 SMB view of the print queue
47 The key for this database is a jobid - a internally generated number that
48 uniquely identifies a print job
50 reading the print queue involves two steps:
51 - possibly running lpq and updating the internal database from that
52 - reading entries from the database
54 jobids are assigned when a job starts spooling.
57 static TDB_CONTEXT *rap_tdb;
58 static uint16 next_rap_jobid;
59 struct rap_jobid_key {
64 /***************************************************************************
65 Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
66 bit RPC jobids.... JRA.
67 ***************************************************************************/
69 uint16 pjobid_to_rap(const char* sharename, uint32 jobid)
73 struct rap_jobid_key jinfo;
76 DEBUG(10,("pjobid_to_rap: called.\n"));
79 /* Create the in-memory tdb. */
80 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
86 fstrcpy( jinfo.sharename, sharename );
88 key.dptr = (uint8 *)&jinfo;
89 key.dsize = sizeof(jinfo);
91 data = tdb_fetch(rap_tdb, key);
92 if (data.dptr && data.dsize == sizeof(uint16)) {
93 rap_jobid = SVAL(data.dptr, 0);
95 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
96 (unsigned int)jobid, (unsigned int)rap_jobid));
100 /* Not found - create and store mapping. */
101 rap_jobid = ++next_rap_jobid;
103 rap_jobid = ++next_rap_jobid;
104 SSVAL(buf,0,rap_jobid);
106 data.dsize = sizeof(rap_jobid);
107 tdb_store(rap_tdb, key, data, TDB_REPLACE);
108 tdb_store(rap_tdb, data, key, TDB_REPLACE);
110 DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
111 (unsigned int)jobid, (unsigned int)rap_jobid));
115 bool rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
120 DEBUG(10,("rap_to_pjobid called.\n"));
125 SSVAL(buf,0,rap_jobid);
127 key.dsize = sizeof(rap_jobid);
128 data = tdb_fetch(rap_tdb, key);
129 if ( data.dptr && data.dsize == sizeof(struct rap_jobid_key) )
131 struct rap_jobid_key *jinfo = (struct rap_jobid_key*)data.dptr;
132 if (sharename != NULL) {
133 fstrcpy( sharename, jinfo->sharename );
135 *pjobid = jinfo->jobid;
136 DEBUG(10,("rap_to_pjobid: jobid %u maps to RAP jobid %u\n",
137 (unsigned int)*pjobid, (unsigned int)rap_jobid));
138 SAFE_FREE(data.dptr);
142 DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
143 (unsigned int)rap_jobid));
144 SAFE_FREE(data.dptr);
148 void rap_jobid_delete(const char* sharename, uint32 jobid)
152 struct rap_jobid_key jinfo;
155 DEBUG(10,("rap_jobid_delete: called.\n"));
160 ZERO_STRUCT( jinfo );
161 fstrcpy( jinfo.sharename, sharename );
163 key.dptr = (uint8 *)&jinfo;
164 key.dsize = sizeof(jinfo);
166 data = tdb_fetch(rap_tdb, key);
167 if (!data.dptr || (data.dsize != sizeof(uint16))) {
168 DEBUG(10,("rap_jobid_delete: cannot find jobid %u\n",
169 (unsigned int)jobid ));
170 SAFE_FREE(data.dptr);
174 DEBUG(10,("rap_jobid_delete: deleting jobid %u\n",
175 (unsigned int)jobid ));
177 rap_jobid = SVAL(data.dptr, 0);
178 SAFE_FREE(data.dptr);
179 SSVAL(buf,0,rap_jobid);
181 data.dsize = sizeof(rap_jobid);
182 tdb_delete(rap_tdb, key);
183 tdb_delete(rap_tdb, data);
186 static int get_queue_status(const char* sharename, print_status_struct *);
188 /****************************************************************************
189 Initialise the printing backend. Called once at startup before the fork().
190 ****************************************************************************/
192 bool print_backend_init(struct messaging_context *msg_ctx)
194 const char *sversion = "INFO/version";
195 int services = lp_numservices();
198 unlink(cache_path("printing.tdb"));
199 mkdir(cache_path("printing"),0755);
201 /* handle a Samba upgrade */
203 for (snum = 0; snum < services; snum++) {
204 struct tdb_print_db *pdb;
205 if (!lp_print_ok(snum))
208 pdb = get_print_db_byname(lp_const_servicename(snum));
211 if (tdb_lock_bystring(pdb->tdb, sversion) == -1) {
212 DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
213 release_print_db(pdb);
216 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
217 tdb_wipe_all(pdb->tdb);
218 tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
220 tdb_unlock_bystring(pdb->tdb, sversion);
221 release_print_db(pdb);
224 close_all_print_db(); /* Don't leave any open. */
226 /* do NT print initialization... */
227 return nt_printing_init(msg_ctx);
230 /****************************************************************************
231 Shut down printing backend. Called once at shutdown to close the tdb.
232 ****************************************************************************/
234 void printing_end(void)
236 close_all_print_db(); /* Don't leave any open. */
239 /****************************************************************************
240 Retrieve the set of printing functions for a given service. This allows
241 us to set the printer function table based on the value of the 'printing'
244 Use the generic interface as the default and only use cups interface only
245 when asked for (and only when supported)
246 ****************************************************************************/
248 static struct printif *get_printer_fns_from_type( enum printing_types type )
250 struct printif *printer_fns = &generic_printif;
253 if ( type == PRINT_CUPS ) {
254 printer_fns = &cups_printif;
256 #endif /* HAVE_CUPS */
259 if ( type == PRINT_IPRINT ) {
260 printer_fns = &iprint_printif;
262 #endif /* HAVE_IPRINT */
264 printer_fns->type = type;
269 static struct printif *get_printer_fns( int snum )
271 return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
275 /****************************************************************************
276 Useful function to generate a tdb key.
277 ****************************************************************************/
279 static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
283 SIVAL(tmp, 0, jobid);
284 ret.dptr = (uint8 *)tmp;
285 ret.dsize = sizeof(*tmp);
289 /****************************************************************************
290 Pack the devicemode to store it in a tdb.
291 ****************************************************************************/
292 static int pack_devicemode(struct spoolss_DeviceMode *devmode, uint8 *buf, int buflen)
294 enum ndr_err_code ndr_err;
299 ndr_err = ndr_push_struct_blob(&blob, talloc_tos(),
301 (ndr_push_flags_fn_t)
302 ndr_push_spoolss_DeviceMode);
303 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
304 DEBUG(10, ("pack_devicemode: "
305 "error encoding spoolss_DeviceMode\n"));
312 len = tdb_pack(buf, buflen, "B", blob.length, blob.data);
315 DEBUG(8, ("Packed devicemode [%s]\n", devmode->formname));
322 /****************************************************************************
323 Unpack the devicemode to store it in a tdb.
324 ****************************************************************************/
325 static int unpack_devicemode(TALLOC_CTX *mem_ctx,
326 const uint8 *buf, int buflen,
327 struct spoolss_DeviceMode **devmode)
329 struct spoolss_DeviceMode *dm;
330 enum ndr_err_code ndr_err;
338 len = tdb_unpack(buf, buflen, "B", &data_len, &data);
343 dm = talloc_zero(mem_ctx, struct spoolss_DeviceMode);
348 blob = data_blob_const(data, data_len);
350 ndr_err = ndr_pull_struct_blob(&blob, dm, dm,
351 (ndr_pull_flags_fn_t)ndr_pull_spoolss_DeviceMode);
352 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
353 DEBUG(10, ("unpack_devicemode: "
354 "error parsing spoolss_DeviceMode\n"));
358 DEBUG(8, ("Unpacked devicemode [%s](%s)\n",
359 dm->devicename, dm->formname));
360 if (dm->driverextra_data.data) {
361 DEBUG(8, ("with a private section of %d bytes\n",
362 dm->__driverextra_length));
372 /***********************************************************************
373 unpack a pjob from a tdb buffer
374 ***********************************************************************/
376 static int unpack_pjob(uint8 *buf, int buflen, struct printjob *pjob)
380 uint32 pjpid, pjjobid, pjsysjob, pjfd, pjstarttime, pjstatus;
381 uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
387 len += tdb_unpack(buf+len, buflen-len, "ddddddddddfffff",
408 used = unpack_devicemode(NULL, buf+len, buflen-len, &pjob->devmode);
416 pjob->jobid = pjjobid;
417 pjob->sysjob = pjsysjob;
419 pjob->starttime = pjstarttime;
420 pjob->status = pjstatus;
422 pjob->page_count = pjpage_count;
423 pjob->spooled = pjspooled;
424 pjob->smbjob = pjsmbjob;
430 /****************************************************************************
431 Useful function to find a print job in the database.
432 ****************************************************************************/
434 static struct printjob *print_job_find(const char *sharename, uint32 jobid)
436 static struct printjob pjob;
439 struct tdb_print_db *pdb = get_print_db_byname(sharename);
441 DEBUG(10,("print_job_find: looking up job %u for share %s\n",
442 (unsigned int)jobid, sharename ));
448 ret = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
449 release_print_db(pdb);
452 DEBUG(10,("print_job_find: failed to find jobid %u.\n", (unsigned int)jobid ));
456 talloc_free(pjob.devmode);
460 if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
461 DEBUG(10,("print_job_find: failed to unpack jobid %u.\n", (unsigned int)jobid ));
468 DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
469 (int)pjob.sysjob, (unsigned int)jobid ));
470 SMB_ASSERT(pjob.jobid == jobid);
475 /* Convert a unix jobid to a smb jobid */
477 struct unixjob_traverse_state {
479 uint32 sysjob_to_jobid_value;
482 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
483 TDB_DATA data, void *private_data)
485 struct printjob *pjob;
486 struct unixjob_traverse_state *state =
487 (struct unixjob_traverse_state *)private_data;
489 if (!data.dptr || data.dsize == 0)
492 pjob = (struct printjob *)data.dptr;
493 if (key.dsize != sizeof(uint32))
496 if (state->sysjob == pjob->sysjob) {
497 state->sysjob_to_jobid_value = pjob->jobid;
504 static uint32 sysjob_to_jobid_pdb(struct tdb_print_db *pdb, int sysjob)
506 struct unixjob_traverse_state state;
508 state.sysjob = sysjob;
509 state.sysjob_to_jobid_value = (uint32)-1;
511 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
513 return state.sysjob_to_jobid_value;
516 /****************************************************************************
517 This is a *horribly expensive call as we have to iterate through all the
518 current printer tdb's. Don't do this often ! JRA.
519 ****************************************************************************/
521 uint32 sysjob_to_jobid(int unix_jobid)
523 int services = lp_numservices();
525 struct unixjob_traverse_state state;
527 state.sysjob = unix_jobid;
528 state.sysjob_to_jobid_value = (uint32)-1;
530 for (snum = 0; snum < services; snum++) {
531 struct tdb_print_db *pdb;
532 if (!lp_print_ok(snum))
534 pdb = get_print_db_byname(lp_const_servicename(snum));
538 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
539 release_print_db(pdb);
540 if (state.sysjob_to_jobid_value != (uint32)-1)
541 return state.sysjob_to_jobid_value;
546 /****************************************************************************
547 Send notifications based on what has changed after a pjob_store.
548 ****************************************************************************/
550 static const struct {
552 uint32_t spoolss_status;
553 } lpq_to_spoolss_status_map[] = {
554 { LPQ_QUEUED, JOB_STATUS_QUEUED },
555 { LPQ_PAUSED, JOB_STATUS_PAUSED },
556 { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
557 { LPQ_PRINTING, JOB_STATUS_PRINTING },
558 { LPQ_DELETING, JOB_STATUS_DELETING },
559 { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
560 { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
561 { LPQ_PRINTED, JOB_STATUS_PRINTED },
562 { LPQ_DELETED, JOB_STATUS_DELETED },
563 { LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
564 { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
568 /* Convert a lpq status value stored in printing.tdb into the
569 appropriate win32 API constant. */
571 static uint32 map_to_spoolss_status(uint32 lpq_status)
575 while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
576 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
577 return lpq_to_spoolss_status_map[i].spoolss_status;
584 /***************************************************************************
585 Append a jobid to the 'jobs changed' list.
586 ***************************************************************************/
588 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32_t jobid)
591 uint32_t store_jobid;
593 SIVAL(&store_jobid, 0, jobid);
594 data.dptr = (uint8 *) &store_jobid;
597 DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
599 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
603 /***************************************************************************
604 Remove a jobid from the 'jobs changed' list.
605 ***************************************************************************/
607 static bool remove_from_jobs_changed(const char* sharename, uint32_t jobid)
609 struct tdb_print_db *pdb = get_print_db_byname(sharename);
613 bool gotlock = False;
621 key = string_tdb_data("INFO/jobs_changed");
623 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
628 data = tdb_fetch(pdb->tdb, key);
630 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
633 job_count = data.dsize / 4;
634 for (i = 0; i < job_count; i++) {
637 ch_jobid = IVAL(data.dptr, i*4);
638 if (ch_jobid == jobid) {
639 if (i < job_count -1 )
640 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
642 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
652 tdb_chainunlock(pdb->tdb, key);
653 SAFE_FREE(data.dptr);
654 release_print_db(pdb);
656 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
658 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
662 static void pjob_store_notify(struct tevent_context *ev,
663 struct messaging_context *msg_ctx,
664 const char* sharename, uint32 jobid,
665 struct printjob *old_data,
666 struct printjob *new_data,
669 bool new_job = false;
670 bool changed = false;
672 if (old_data == NULL) {
676 /* ACHTUNG! Due to a bug in Samba's spoolss parsing of the
677 NOTIFY_INFO_DATA buffer, we *have* to send the job submission
678 time first or else we'll end up with potential alignment
679 errors. I don't think the systemtime should be spooled as
680 a string, but this gets us around that error.
681 --jerry (i'll feel dirty for this) */
684 notify_job_submitted(ev, msg_ctx,
685 sharename, jobid, new_data->starttime);
686 notify_job_username(ev, msg_ctx,
687 sharename, jobid, new_data->user);
688 notify_job_name(ev, msg_ctx,
689 sharename, jobid, new_data->jobname);
690 notify_job_status(ev, msg_ctx,
691 sharename, jobid, map_to_spoolss_status(new_data->status));
692 notify_job_total_bytes(ev, msg_ctx,
693 sharename, jobid, new_data->size);
694 notify_job_total_pages(ev, msg_ctx,
695 sharename, jobid, new_data->page_count);
697 if (!strequal(old_data->jobname, new_data->jobname)) {
698 notify_job_name(ev, msg_ctx, sharename,
699 jobid, new_data->jobname);
703 if (old_data->status != new_data->status) {
704 notify_job_status(ev, msg_ctx,
706 map_to_spoolss_status(new_data->status));
709 if (old_data->size != new_data->size) {
710 notify_job_total_bytes(ev, msg_ctx,
711 sharename, jobid, new_data->size);
714 if (old_data->page_count != new_data->page_count) {
715 notify_job_total_pages(ev, msg_ctx,
717 new_data->page_count);
724 /****************************************************************************
725 Store a job structure back to the database.
726 ****************************************************************************/
728 static bool pjob_store(struct tevent_context *ev,
729 struct messaging_context *msg_ctx,
730 const char* sharename, uint32 jobid,
731 struct printjob *pjob)
734 TDB_DATA old_data, new_data;
736 struct tdb_print_db *pdb = get_print_db_byname(sharename);
738 int len, newlen, buflen;
746 old_data = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
748 /* Doh! Now we have to pack/unpack data since the NT_DEVICEMODE was added */
755 len += tdb_pack(buf+len, buflen-len, "ddddddddddfffff",
758 (uint32)pjob->sysjob,
760 (uint32)pjob->starttime,
761 (uint32)pjob->status,
763 (uint32)pjob->page_count,
764 (uint32)pjob->spooled,
765 (uint32)pjob->smbjob,
772 len += pack_devicemode(pjob->devmode, buf+len, buflen-len);
775 buf = (uint8 *)SMB_REALLOC(buf, len);
777 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
782 } while ( buflen != len );
788 new_data.dsize = len;
789 ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
792 /* Send notify updates for what has changed */
795 bool changed = false;
796 struct printjob old_pjob;
798 if ( old_data.dsize )
800 if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
802 pjob_store_notify(server_event_context(),
804 sharename, jobid, &old_pjob,
807 talloc_free(old_pjob.devmode);
810 add_to_jobs_changed(pdb, jobid);
817 pjob_store_notify(server_event_context(), msg_ctx,
818 sharename, jobid, NULL, pjob,
824 release_print_db(pdb);
825 SAFE_FREE( old_data.dptr );
831 /****************************************************************************
832 Remove a job structure from the database.
833 ****************************************************************************/
835 static void pjob_delete(struct tevent_context *ev,
836 struct messaging_context *msg_ctx,
837 const char* sharename, uint32 jobid)
840 struct printjob *pjob;
841 uint32 job_status = 0;
842 struct tdb_print_db *pdb;
844 pdb = get_print_db_byname( sharename );
849 pjob = print_job_find( sharename, jobid );
852 DEBUG(5, ("pjob_delete: we were asked to delete nonexistent job %u\n",
853 (unsigned int)jobid));
854 release_print_db(pdb);
858 /* We must cycle through JOB_STATUS_DELETING and
859 JOB_STATUS_DELETED for the port monitor to delete the job
862 job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
863 notify_job_status(ev, msg_ctx, sharename, jobid, job_status);
865 /* Remove from printing.tdb */
867 tdb_delete(pdb->tdb, print_key(jobid, &tmp));
868 remove_from_jobs_added(sharename, jobid);
869 release_print_db( pdb );
870 rap_jobid_delete(sharename, jobid);
873 /****************************************************************************
874 List a unix job in the print database.
875 ****************************************************************************/
877 static void print_unix_job(struct tevent_context *ev,
878 struct messaging_context *msg_ctx,
879 const char *sharename, print_queue_struct *q,
882 struct printjob pj, *old_pj;
884 if (jobid == (uint32)-1)
885 jobid = q->sysjob + UNIX_JOB_START;
887 /* Preserve the timestamp on an existing unix print job */
889 old_pj = print_job_find(sharename, jobid);
895 pj.sysjob = q->sysjob;
897 pj.starttime = old_pj ? old_pj->starttime : q->time;
898 pj.status = q->status;
901 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
902 if (jobid < UNIX_JOB_START) {
904 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
907 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
909 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
910 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
912 pjob_store(ev, msg_ctx, sharename, jobid, &pj);
916 struct traverse_struct {
917 print_queue_struct *queue;
918 int qcount, snum, maxcount, total_jobs;
919 const char *sharename;
921 const char *lprm_command;
922 struct printif *print_if;
923 struct tevent_context *ev;
924 struct messaging_context *msg_ctx;
927 /****************************************************************************
928 Utility fn to delete any jobs that are no longer active.
929 ****************************************************************************/
931 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
933 struct traverse_struct *ts = (struct traverse_struct *)state;
934 struct printjob pjob;
938 if ( key.dsize != sizeof(jobid) )
941 if (unpack_pjob(data.dptr, data.dsize, &pjob) == -1)
943 talloc_free(pjob.devmode);
947 /* remove a unix job if it isn't in the system queue any more */
948 for (i=0;i<ts->qcount;i++) {
949 if (ts->queue[i].sysjob == pjob.sysjob) {
953 if (i == ts->qcount) {
954 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
955 (unsigned int)jobid ));
956 pjob_delete(ts->ev, ts->msg_ctx,
957 ts->sharename, jobid);
961 /* need to continue the the bottom of the function to
962 save the correct attributes */
965 /* maybe it hasn't been spooled yet */
967 /* if a job is not spooled and the process doesn't
968 exist then kill it. This cleans up after smbd
970 if (!process_exists_by_pid(pjob.pid)) {
971 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
972 (unsigned int)jobid, (unsigned int)pjob.pid ));
973 pjob_delete(ts->ev, ts->msg_ctx,
974 ts->sharename, jobid);
980 /* this check only makes sense for jobs submitted from Windows clients */
983 for (i=0;i<ts->qcount;i++) {
984 if ( pjob.status == LPQ_DELETED )
987 if (ts->queue[i].sysjob == pjob.sysjob) {
989 /* try to clean up any jobs that need to be deleted */
991 if ( pjob.status == LPQ_DELETING ) {
994 result = (*(ts->print_if->job_delete))(
995 ts->sharename, ts->lprm_command, &pjob );
998 /* if we can't delete, then reset the job status */
999 pjob.status = LPQ_QUEUED;
1000 pjob_store(ts->ev, ts->msg_ctx,
1001 ts->sharename, jobid, &pjob);
1004 /* if we deleted the job, the remove the tdb record */
1007 ts->sharename, jobid);
1008 pjob.status = LPQ_DELETED;
1018 /* The job isn't in the system queue - we have to assume it has
1019 completed, so delete the database entry. */
1021 if (i == ts->qcount) {
1023 /* A race can occur between the time a job is spooled and
1024 when it appears in the lpq output. This happens when
1025 the job is added to printing.tdb when another smbd
1026 running print_queue_update() has completed a lpq and
1027 is currently traversing the printing tdb and deleting jobs.
1028 Don't delete the job if it was submitted after the lpq_time. */
1030 if (pjob.starttime < ts->lpq_time) {
1031 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
1032 (unsigned int)jobid,
1033 (unsigned int)pjob.starttime,
1034 (unsigned int)ts->lpq_time ));
1035 pjob_delete(ts->ev, ts->msg_ctx,
1036 ts->sharename, jobid);
1042 /* Save the pjob attributes we will store. */
1043 ts->queue[i].sysjob = pjob.sysjob;
1044 ts->queue[i].size = pjob.size;
1045 ts->queue[i].page_count = pjob.page_count;
1046 ts->queue[i].status = pjob.status;
1047 ts->queue[i].priority = 1;
1048 ts->queue[i].time = pjob.starttime;
1049 fstrcpy(ts->queue[i].fs_user, pjob.user);
1050 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1057 /****************************************************************************
1058 Check if the print queue has been updated recently enough.
1059 ****************************************************************************/
1061 static void print_cache_flush(const char *sharename)
1064 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1068 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
1069 tdb_store_int32(pdb->tdb, key, -1);
1070 release_print_db(pdb);
1073 /****************************************************************************
1074 Check if someone already thinks they are doing the update.
1075 ****************************************************************************/
1077 static pid_t get_updating_pid(const char *sharename)
1082 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1086 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1087 key = string_tdb_data(keystr);
1089 data = tdb_fetch(pdb->tdb, key);
1090 release_print_db(pdb);
1091 if (!data.dptr || data.dsize != sizeof(pid_t)) {
1092 SAFE_FREE(data.dptr);
1096 updating_pid = IVAL(data.dptr, 0);
1097 SAFE_FREE(data.dptr);
1099 if (process_exists_by_pid(updating_pid))
1100 return updating_pid;
1105 /****************************************************************************
1106 Set the fact that we're doing the update, or have finished doing the update
1108 ****************************************************************************/
1110 static void set_updating_pid(const fstring sharename, bool updating)
1115 pid_t updating_pid = sys_getpid();
1118 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1123 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1124 key = string_tdb_data(keystr);
1126 DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
1127 updating ? "" : "not ",
1131 tdb_delete(pdb->tdb, key);
1132 release_print_db(pdb);
1136 SIVAL( buffer, 0, updating_pid);
1138 data.dsize = 4; /* we always assume this is a 4 byte value */
1140 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1141 release_print_db(pdb);
1144 /****************************************************************************
1145 Sort print jobs by submittal time.
1146 ****************************************************************************/
1148 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1159 /* Sort on job start time */
1161 if (j1->time == j2->time)
1163 return (j1->time > j2->time) ? 1 : -1;
1166 /****************************************************************************
1167 Store the sorted queue representation for later portmon retrieval.
1169 ****************************************************************************/
1171 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
1174 int max_reported_jobs = lp_max_reported_jobs(pts->snum);
1175 print_queue_struct *queue = pts->queue;
1178 unsigned int qcount;
1180 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
1181 pts->qcount = max_reported_jobs;
1184 /* Work out the size. */
1186 data.dsize += tdb_pack(NULL, 0, "d", qcount);
1188 for (i = 0; i < pts->qcount; i++) {
1189 if ( queue[i].status == LPQ_DELETED )
1193 data.dsize += tdb_pack(NULL, 0, "ddddddff",
1194 (uint32)queue[i].sysjob,
1195 (uint32)queue[i].size,
1196 (uint32)queue[i].page_count,
1197 (uint32)queue[i].status,
1198 (uint32)queue[i].priority,
1199 (uint32)queue[i].time,
1204 if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
1208 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
1209 for (i = 0; i < pts->qcount; i++) {
1210 if ( queue[i].status == LPQ_DELETED )
1213 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
1214 (uint32)queue[i].sysjob,
1215 (uint32)queue[i].size,
1216 (uint32)queue[i].page_count,
1217 (uint32)queue[i].status,
1218 (uint32)queue[i].priority,
1219 (uint32)queue[i].time,
1224 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
1226 SAFE_FREE(data.dptr);
1230 static TDB_DATA get_jobs_added_data(struct tdb_print_db *pdb)
1236 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_added"));
1237 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1238 SAFE_FREE(data.dptr);
1245 static void check_job_added(const char *sharename, TDB_DATA data, uint32 jobid)
1248 unsigned int job_count = data.dsize / 4;
1250 for (i = 0; i < job_count; i++) {
1253 ch_jobid = IVAL(data.dptr, i*4);
1254 if (ch_jobid == jobid)
1255 remove_from_jobs_added(sharename, jobid);
1259 /****************************************************************************
1260 Check if the print queue has been updated recently enough.
1261 ****************************************************************************/
1263 static bool print_cache_expired(const char *sharename, bool check_pending)
1266 time_t last_qscan_time, time_now = time(NULL);
1267 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1268 bool result = False;
1273 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1274 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1277 * Invalidate the queue for 3 reasons.
1278 * (1). last queue scan time == -1.
1279 * (2). Current time - last queue scan time > allowed cache time.
1280 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1281 * This last test picks up machines for which the clock has been moved
1282 * forward, an lpq scan done and then the clock moved back. Otherwise
1283 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1286 if (last_qscan_time == ((time_t)-1)
1287 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1288 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1291 time_t msg_pending_time;
1293 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1294 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1295 sharename, (int)last_qscan_time, (int)time_now,
1296 (int)lp_lpqcachetime() ));
1298 /* check if another smbd has already sent a message to update the
1299 queue. Give the pending message one minute to clear and
1300 then send another message anyways. Make sure to check for
1301 clocks that have been run forward and then back again. */
1303 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1306 && tdb_fetch_uint32( pdb->tdb, key, &u )
1307 && (msg_pending_time=u) > 0
1308 && msg_pending_time <= time_now
1309 && (time_now - msg_pending_time) < 60 )
1311 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1320 release_print_db(pdb);
1324 /****************************************************************************
1325 main work for updating the lpq cache for a printer queue
1326 ****************************************************************************/
1328 static void print_queue_update_internal(struct tevent_context *ev,
1329 struct messaging_context *msg_ctx,
1330 const char *sharename,
1331 struct printif *current_printif,
1332 char *lpq_command, char *lprm_command)
1335 print_queue_struct *queue = NULL;
1336 print_status_struct status;
1337 print_status_struct old_status;
1338 struct printjob *pjob;
1339 struct traverse_struct tstruct;
1342 fstring keystr, cachestr;
1343 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1349 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1350 sharename, current_printif->type, lpq_command));
1353 * Update the cache time FIRST ! Stops others even
1354 * attempting to get the lock and doing this
1355 * if the lpq takes a long time.
1358 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1359 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1361 /* get the current queue using the appropriate interface */
1362 ZERO_STRUCT(status);
1364 qcount = (*(current_printif->queue_get))(sharename,
1365 current_printif->type,
1366 lpq_command, &queue, &status);
1368 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1369 qcount, (qcount != 1) ? "s" : "", sharename));
1371 /* Sort the queue by submission time otherwise they are displayed
1374 TYPESAFE_QSORT(queue, qcount, printjob_comp);
1377 any job in the internal database that is marked as spooled
1378 and doesn't exist in the system queue is considered finished
1379 and removed from the database
1381 any job in the system database but not in the internal database
1382 is added as a unix job
1384 fill in any system job numbers as we go
1387 jcdata = get_jobs_added_data(pdb);
1389 for (i=0; i<qcount; i++) {
1390 uint32 jobid = sysjob_to_jobid_pdb(pdb, queue[i].sysjob);
1391 if (jobid == (uint32)-1) {
1392 /* assume its a unix print job */
1393 print_unix_job(ev, msg_ctx,
1394 sharename, &queue[i], jobid);
1398 /* we have an active SMB print job - update its status */
1399 pjob = print_job_find(sharename, jobid);
1401 /* err, somethings wrong. Probably smbd was restarted
1402 with jobs in the queue. All we can do is treat them
1403 like unix jobs. Pity. */
1404 DEBUG(1, ("queued print job %d not found in jobs list, "
1405 "assuming unix job\n", jobid));
1406 print_unix_job(ev, msg_ctx,
1407 sharename, &queue[i], jobid);
1411 /* don't reset the status on jobs to be deleted */
1413 if ( pjob->status != LPQ_DELETING )
1414 pjob->status = queue[i].status;
1416 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
1418 check_job_added(sharename, jcdata, jobid);
1421 SAFE_FREE(jcdata.dptr);
1423 /* now delete any queued entries that don't appear in the
1425 tstruct.queue = queue;
1426 tstruct.qcount = qcount;
1428 tstruct.total_jobs = 0;
1429 tstruct.lpq_time = time(NULL);
1430 tstruct.sharename = sharename;
1431 tstruct.lprm_command = lprm_command;
1432 tstruct.print_if = current_printif;
1434 tstruct.msg_ctx = msg_ctx;
1436 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1438 /* Store the linearised queue, max jobs only. */
1439 store_queue_struct(pdb, &tstruct);
1441 SAFE_FREE(tstruct.queue);
1443 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1444 sharename, tstruct.total_jobs ));
1446 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1448 get_queue_status(sharename, &old_status);
1449 if (old_status.qcount != qcount)
1450 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1451 old_status.qcount, qcount, sharename));
1453 /* store the new queue status structure */
1454 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1455 key = string_tdb_data(keystr);
1457 status.qcount = qcount;
1458 data.dptr = (uint8 *)&status;
1459 data.dsize = sizeof(status);
1460 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1463 * Update the cache time again. We want to do this call
1464 * as little as possible...
1467 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1468 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1470 /* clear the msg pending record for this queue */
1472 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1474 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1475 /* log a message but continue on */
1477 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1481 release_print_db( pdb );
1486 /****************************************************************************
1487 Update the internal database from the system print queue for a queue.
1488 obtain a lock on the print queue before proceeding (needed when mutiple
1489 smbd processes maytry to update the lpq cache concurrently).
1490 ****************************************************************************/
1492 static void print_queue_update_with_lock( struct tevent_context *ev,
1493 struct messaging_context *msg_ctx,
1494 const char *sharename,
1495 struct printif *current_printif,
1496 char *lpq_command, char *lprm_command )
1499 struct tdb_print_db *pdb;
1501 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1502 pdb = get_print_db_byname(sharename);
1506 if ( !print_cache_expired(sharename, False) ) {
1507 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1508 release_print_db(pdb);
1513 * Check to see if someone else is doing this update.
1514 * This is essentially a mutex on the update.
1517 if (get_updating_pid(sharename) != -1) {
1518 release_print_db(pdb);
1522 /* Lock the queue for the database update */
1524 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1525 /* Only wait 10 seconds for this. */
1526 if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) == -1) {
1527 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1528 release_print_db(pdb);
1533 * Ensure that no one else got in here.
1534 * If the updating pid is still -1 then we are
1538 if (get_updating_pid(sharename) != -1) {
1540 * Someone else is doing the update, exit.
1542 tdb_unlock_bystring(pdb->tdb, keystr);
1543 release_print_db(pdb);
1548 * We're going to do the update ourselves.
1551 /* Tell others we're doing the update. */
1552 set_updating_pid(sharename, True);
1555 * Allow others to enter and notice we're doing
1559 tdb_unlock_bystring(pdb->tdb, keystr);
1561 /* do the main work now */
1563 print_queue_update_internal(ev, msg_ctx,
1564 sharename, current_printif,
1565 lpq_command, lprm_command);
1567 /* Delete our pid from the db. */
1568 set_updating_pid(sharename, False);
1569 release_print_db(pdb);
1572 /****************************************************************************
1573 this is the receive function of the background lpq updater
1574 ****************************************************************************/
1575 void print_queue_receive(struct messaging_context *msg,
1578 struct server_id server_id,
1582 char *lpqcommand = NULL, *lprmcommand = NULL;
1586 len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1593 SAFE_FREE(lpqcommand);
1594 SAFE_FREE(lprmcommand);
1595 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1599 print_queue_update_with_lock(server_event_context(), msg, sharename,
1600 get_printer_fns_from_type((enum printing_types)printing_type),
1601 lpqcommand, lprmcommand );
1603 SAFE_FREE(lpqcommand);
1604 SAFE_FREE(lprmcommand);
1608 static void printing_pause_fd_handler(struct tevent_context *ev,
1609 struct tevent_fd *fde,
1614 * If pause_pipe[1] is closed it means the parent smbd
1615 * and children exited or aborted.
1617 exit_server_cleanly(NULL);
1620 extern struct child_pid *children;
1621 extern int num_children;
1623 static void add_child_pid(pid_t pid)
1625 struct child_pid *child;
1627 child = SMB_MALLOC_P(struct child_pid);
1628 if (child == NULL) {
1629 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
1633 DLIST_ADD(children, child);
1637 static pid_t background_lpq_updater_pid = -1;
1639 /****************************************************************************
1640 main thread of the background lpq updater
1641 ****************************************************************************/
1642 void start_background_queue(struct tevent_context *ev,
1643 struct messaging_context *msg_ctx)
1645 /* Use local variables for this as we don't
1646 * need to save the parent side of this, just
1647 * ensure it closes when the process exits.
1651 DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
1653 if (pipe(pause_pipe) == -1) {
1654 DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
1658 background_lpq_updater_pid = sys_fork();
1660 if (background_lpq_updater_pid == -1) {
1661 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
1665 /* Track the printing pid along with other smbd children */
1666 add_child_pid(background_lpq_updater_pid);
1668 if(background_lpq_updater_pid == 0) {
1669 struct tevent_fd *fde;
1674 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
1676 close(pause_pipe[0]);
1679 status = reinit_after_fork(msg_ctx, ev, procid_self(), true);
1681 if (!NT_STATUS_IS_OK(status)) {
1682 DEBUG(0,("reinit_after_fork() failed\n"));
1683 smb_panic("reinit_after_fork() failed");
1686 smbd_setup_sig_term_handler();
1687 smbd_setup_sig_hup_handler(ev, msg_ctx);
1689 if (!serverid_register(procid_self(),
1690 FLAG_MSG_GENERAL|FLAG_MSG_SMBD
1691 |FLAG_MSG_PRINT_GENERAL)) {
1695 if (!locking_init()) {
1699 messaging_register(msg_ctx, NULL, MSG_PRINTER_UPDATE,
1700 print_queue_receive);
1702 fde = tevent_add_fd(ev, ev, pause_pipe[1], TEVENT_FD_READ,
1703 printing_pause_fd_handler,
1706 DEBUG(0,("tevent_add_fd() failed for pause_pipe\n"));
1707 smb_panic("tevent_add_fd() failed for pause_pipe");
1710 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
1711 ret = tevent_loop_wait(ev);
1712 /* should not be reached */
1713 DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
1714 ret, (ret == 0) ? "out of events" : strerror(errno)));
1718 close(pause_pipe[1]);
1721 /****************************************************************************
1722 update the internal database from the system print queue for a queue
1723 ****************************************************************************/
1725 static void print_queue_update(struct messaging_context *msg_ctx,
1726 int snum, bool force)
1730 char *lpqcommand = NULL;
1731 char *lprmcommand = NULL;
1732 uint8 *buffer = NULL;
1735 struct tdb_print_db *pdb;
1737 struct printif *current_printif;
1738 TALLOC_CTX *ctx = talloc_tos();
1740 fstrcpy( sharename, lp_const_servicename(snum));
1742 /* don't strip out characters like '$' from the printername */
1744 lpqcommand = talloc_string_sub2(ctx,
1745 lp_lpqcommand(snum),
1747 lp_printername(snum),
1748 false, false, false);
1752 lpqcommand = talloc_sub_advanced(ctx,
1753 lp_servicename(snum),
1754 current_user_info.unix_name,
1756 current_user.ut.gid,
1757 get_current_username(),
1758 current_user_info.domain,
1764 lprmcommand = talloc_string_sub2(ctx,
1765 lp_lprmcommand(snum),
1767 lp_printername(snum),
1768 false, false, false);
1772 lprmcommand = talloc_sub_advanced(ctx,
1773 lp_servicename(snum),
1774 current_user_info.unix_name,
1776 current_user.ut.gid,
1777 get_current_username(),
1778 current_user_info.domain,
1785 * Make sure that the background queue process exists.
1786 * Otherwise just do the update ourselves
1789 if ( force || background_lpq_updater_pid == -1 ) {
1790 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1791 current_printif = get_printer_fns( snum );
1792 print_queue_update_with_lock(server_event_context(), msg_ctx,
1793 sharename, current_printif,
1794 lpqcommand, lprmcommand);
1799 type = lp_printing(snum);
1801 /* get the length */
1803 len = tdb_pack( NULL, 0, "fdPP",
1809 buffer = SMB_XMALLOC_ARRAY( uint8, len );
1811 /* now pack the buffer */
1812 newlen = tdb_pack( buffer, len, "fdPP",
1818 SMB_ASSERT( newlen == len );
1820 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1821 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1822 sharename, type, lpqcommand, lprmcommand ));
1824 /* here we set a msg pending record for other smbd processes
1825 to throttle the number of duplicate print_queue_update msgs
1828 pdb = get_print_db_byname(sharename);
1834 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1836 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1837 /* log a message but continue on */
1839 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1843 release_print_db( pdb );
1845 /* finally send the message */
1847 messaging_send_buf(msg_ctx, pid_to_procid(background_lpq_updater_pid),
1848 MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1850 SAFE_FREE( buffer );
1855 /****************************************************************************
1856 Create/Update an entry in the print tdb that will allow us to send notify
1857 updates only to interested smbd's.
1858 ****************************************************************************/
1860 bool print_notify_register_pid(int snum)
1863 struct tdb_print_db *pdb = NULL;
1864 TDB_CONTEXT *tdb = NULL;
1865 const char *printername;
1866 uint32 mypid = (uint32)sys_getpid();
1870 /* if (snum == -1), then the change notify request was
1871 on a print server handle and we need to register on
1876 int num_services = lp_numservices();
1879 for ( idx=0; idx<num_services; idx++ ) {
1880 if (lp_snum_ok(idx) && lp_print_ok(idx) )
1881 print_notify_register_pid(idx);
1886 else /* register for a specific printer */
1888 printername = lp_const_servicename(snum);
1889 pdb = get_print_db_byname(printername);
1895 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1896 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1899 release_print_db(pdb);
1903 data = get_printer_notify_pid_list( tdb, printername, True );
1905 /* Add ourselves and increase the refcount. */
1907 for (i = 0; i < data.dsize; i += 8) {
1908 if (IVAL(data.dptr,i) == mypid) {
1909 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1910 SIVAL(data.dptr, i+4, new_refcount);
1915 if (i == data.dsize) {
1916 /* We weren't in the list. Realloc. */
1917 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1919 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1924 SIVAL(data.dptr,data.dsize - 8,mypid);
1925 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1928 /* Store back the record. */
1929 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1930 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1931 list for printer %s\n", printername));
1939 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1941 release_print_db(pdb);
1942 SAFE_FREE(data.dptr);
1946 /****************************************************************************
1947 Update an entry in the print tdb that will allow us to send notify
1948 updates only to interested smbd's.
1949 ****************************************************************************/
1951 bool print_notify_deregister_pid(int snum)
1954 struct tdb_print_db *pdb = NULL;
1955 TDB_CONTEXT *tdb = NULL;
1956 const char *printername;
1957 uint32 mypid = (uint32)sys_getpid();
1961 /* if ( snum == -1 ), we are deregister a print server handle
1962 which means to deregister on all print queues */
1966 int num_services = lp_numservices();
1969 for ( idx=0; idx<num_services; idx++ ) {
1970 if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1971 print_notify_deregister_pid(idx);
1976 else /* deregister a specific printer */
1978 printername = lp_const_servicename(snum);
1979 pdb = get_print_db_byname(printername);
1985 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1986 DEBUG(0,("print_notify_register_pid: Failed to lock \
1987 printer %s database\n", printername));
1989 release_print_db(pdb);
1993 data = get_printer_notify_pid_list( tdb, printername, True );
1995 /* Reduce refcount. Remove ourselves if zero. */
1997 for (i = 0; i < data.dsize; ) {
1998 if (IVAL(data.dptr,i) == mypid) {
1999 uint32 refcount = IVAL(data.dptr, i+4);
2003 if (refcount == 0) {
2004 if (data.dsize - i > 8)
2005 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
2009 SIVAL(data.dptr, i+4, refcount);
2015 if (data.dsize == 0)
2016 SAFE_FREE(data.dptr);
2018 /* Store back the record. */
2019 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
2020 DEBUG(0,("print_notify_register_pid: Failed to update pid \
2021 list for printer %s\n", printername));
2029 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
2031 release_print_db(pdb);
2032 SAFE_FREE(data.dptr);
2036 /****************************************************************************
2037 Check if a jobid is valid. It is valid if it exists in the database.
2038 ****************************************************************************/
2040 bool print_job_exists(const char* sharename, uint32 jobid)
2042 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2048 ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
2049 release_print_db(pdb);
2053 /****************************************************************************
2054 Give the filename used for a jobid.
2055 Only valid for the process doing the spooling and when the job
2056 has not been spooled.
2057 ****************************************************************************/
2059 char *print_job_fname(const char* sharename, uint32 jobid)
2061 struct printjob *pjob = print_job_find(sharename, jobid);
2062 if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
2064 return pjob->filename;
2068 /****************************************************************************
2069 Give the filename used for a jobid.
2070 Only valid for the process doing the spooling and when the job
2071 has not been spooled.
2072 ****************************************************************************/
2074 struct spoolss_DeviceMode *print_job_devmode(const char* sharename, uint32 jobid)
2076 struct printjob *pjob = print_job_find(sharename, jobid);
2081 return pjob->devmode;
2084 /****************************************************************************
2085 Set the name of a job. Only possible for owner.
2086 ****************************************************************************/
2088 bool print_job_set_name(struct tevent_context *ev,
2089 struct messaging_context *msg_ctx,
2090 const char *sharename, uint32 jobid, const char *name)
2092 struct printjob *pjob;
2094 pjob = print_job_find(sharename, jobid);
2095 if (!pjob || pjob->pid != sys_getpid())
2098 fstrcpy(pjob->jobname, name);
2099 return pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2102 /****************************************************************************
2103 Get the name of a job. Only possible for owner.
2104 ****************************************************************************/
2106 bool print_job_get_name(TALLOC_CTX *mem_ctx, const char *sharename, uint32_t jobid, char **name)
2108 struct printjob *pjob;
2110 pjob = print_job_find(sharename, jobid);
2111 if (!pjob || pjob->pid != sys_getpid()) {
2115 *name = talloc_strdup(mem_ctx, pjob->jobname);
2124 /***************************************************************************
2125 Remove a jobid from the 'jobs added' list.
2126 ***************************************************************************/
2128 static bool remove_from_jobs_added(const char* sharename, uint32 jobid)
2130 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2132 size_t job_count, i;
2134 bool gotlock = False;
2142 key = string_tdb_data("INFO/jobs_added");
2144 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
2149 data = tdb_fetch(pdb->tdb, key);
2151 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
2154 job_count = data.dsize / 4;
2155 for (i = 0; i < job_count; i++) {
2158 ch_jobid = IVAL(data.dptr, i*4);
2159 if (ch_jobid == jobid) {
2160 if (i < job_count -1 )
2161 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
2163 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
2173 tdb_chainunlock(pdb->tdb, key);
2174 SAFE_FREE(data.dptr);
2175 release_print_db(pdb);
2177 DEBUG(10,("remove_from_jobs_added: removed jobid %u\n", (unsigned int)jobid ));
2179 DEBUG(10,("remove_from_jobs_added: Failed to remove jobid %u\n", (unsigned int)jobid ));
2183 /****************************************************************************
2184 Delete a print job - don't update queue.
2185 ****************************************************************************/
2187 static bool print_job_delete1(struct tevent_context *ev,
2188 struct messaging_context *msg_ctx,
2189 int snum, uint32 jobid)
2191 const char* sharename = lp_const_servicename(snum);
2192 struct printjob *pjob = print_job_find(sharename, jobid);
2194 struct printif *current_printif = get_printer_fns( snum );
2200 * If already deleting just return.
2203 if (pjob->status == LPQ_DELETING)
2206 /* Hrm - we need to be able to cope with deleting a job before it
2207 has reached the spooler. Just mark it as LPQ_DELETING and
2208 let the print_queue_update() code rmeove the record */
2211 if (pjob->sysjob == -1) {
2212 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
2215 /* Set the tdb entry to be deleting. */
2217 pjob->status = LPQ_DELETING;
2218 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2220 if (pjob->spooled && pjob->sysjob != -1)
2222 result = (*(current_printif->job_delete))(
2223 lp_printername(snum),
2224 lp_lprmcommand(snum),
2227 /* Delete the tdb entry if the delete succeeded or the job hasn't
2231 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2236 pjob_delete(ev, msg_ctx, sharename, jobid);
2237 /* Ensure we keep a rough count of the number of total jobs... */
2238 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
2239 release_print_db(pdb);
2243 remove_from_jobs_added( sharename, jobid );
2245 return (result == 0);
2248 /****************************************************************************
2249 Return true if the current user owns the print job.
2250 ****************************************************************************/
2252 static bool is_owner(const struct auth_serversupplied_info *server_info,
2253 const char *servicename,
2256 struct printjob *pjob = print_job_find(servicename, jobid);
2258 if (!pjob || !server_info)
2261 return strequal(pjob->user, server_info->sanitized_username);
2264 /****************************************************************************
2266 ****************************************************************************/
2268 WERROR print_job_delete(const struct auth_serversupplied_info *server_info,
2269 struct messaging_context *msg_ctx,
2270 int snum, uint32_t jobid)
2272 const char* sharename = lp_const_servicename(snum);
2273 struct printjob *pjob;
2277 owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2279 /* Check access against security descriptor or whether the user
2283 !print_access_check(server_info, msg_ctx, snum,
2284 JOB_ACCESS_ADMINISTER)) {
2285 DEBUG(3, ("delete denied by security descriptor\n"));
2287 /* BEGIN_ADMIN_LOG */
2288 sys_adminlog( LOG_ERR,
2289 "Permission denied-- user not allowed to delete, \
2290 pause, or resume print job. User name: %s. Printer name: %s.",
2291 uidtoname(server_info->utok.uid),
2292 lp_printername(snum) );
2295 return WERR_ACCESS_DENIED;
2299 * get the spooled filename of the print job
2300 * if this works, then the file has not been spooled
2301 * to the underlying print system. Just delete the
2302 * spool file & return.
2305 fname = print_job_fname(sharename, jobid);
2306 if (fname != NULL) {
2307 /* remove the spool file */
2308 DEBUG(10, ("print_job_delete: "
2309 "Removing spool file [%s]\n", fname));
2310 if (unlink(fname) == -1) {
2311 return map_werror_from_unix(errno);
2315 if (!print_job_delete1(server_event_context(), msg_ctx, snum, jobid)) {
2316 return WERR_ACCESS_DENIED;
2319 /* force update the database and say the delete failed if the
2322 print_queue_update(msg_ctx, snum, True);
2324 pjob = print_job_find(sharename, jobid);
2325 if (pjob && (pjob->status != LPQ_DELETING)) {
2326 return WERR_ACCESS_DENIED;
2329 return WERR_PRINTER_HAS_JOBS_QUEUED;
2332 /****************************************************************************
2334 ****************************************************************************/
2336 WERROR print_job_pause(const struct auth_serversupplied_info *server_info,
2337 struct messaging_context *msg_ctx,
2338 int snum, uint32 jobid)
2340 const char* sharename = lp_const_servicename(snum);
2341 struct printjob *pjob;
2343 struct printif *current_printif = get_printer_fns( snum );
2346 pjob = print_job_find(sharename, jobid);
2348 if (!pjob || !server_info) {
2349 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2350 (unsigned int)jobid ));
2351 werr = WERR_INVALID_PARAM;
2355 if (!pjob->spooled || pjob->sysjob == -1) {
2356 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2357 (int)pjob->sysjob, (unsigned int)jobid ));
2358 werr = WERR_INVALID_PARAM;
2362 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2363 !print_access_check(server_info, msg_ctx, snum,
2364 JOB_ACCESS_ADMINISTER)) {
2365 DEBUG(3, ("pause denied by security descriptor\n"));
2367 /* BEGIN_ADMIN_LOG */
2368 sys_adminlog( LOG_ERR,
2369 "Permission denied-- user not allowed to delete, \
2370 pause, or resume print job. User name: %s. Printer name: %s.",
2371 uidtoname(server_info->utok.uid),
2372 lp_printername(snum) );
2375 werr = WERR_ACCESS_DENIED;
2379 /* need to pause the spooled entry */
2380 ret = (*(current_printif->job_pause))(snum, pjob);
2383 werr = WERR_INVALID_PARAM;
2387 /* force update the database */
2388 print_cache_flush(lp_const_servicename(snum));
2390 /* Send a printer notify message */
2392 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2395 /* how do we tell if this succeeded? */
2401 /****************************************************************************
2403 ****************************************************************************/
2405 WERROR print_job_resume(const struct auth_serversupplied_info *server_info,
2406 struct messaging_context *msg_ctx,
2407 int snum, uint32 jobid)
2409 const char *sharename = lp_const_servicename(snum);
2410 struct printjob *pjob;
2412 struct printif *current_printif = get_printer_fns( snum );
2415 pjob = print_job_find(sharename, jobid);
2417 if (!pjob || !server_info) {
2418 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2419 (unsigned int)jobid ));
2420 werr = WERR_INVALID_PARAM;
2424 if (!pjob->spooled || pjob->sysjob == -1) {
2425 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2426 (int)pjob->sysjob, (unsigned int)jobid ));
2427 werr = WERR_INVALID_PARAM;
2431 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2432 !print_access_check(server_info, msg_ctx, snum,
2433 JOB_ACCESS_ADMINISTER)) {
2434 DEBUG(3, ("resume denied by security descriptor\n"));
2436 /* BEGIN_ADMIN_LOG */
2437 sys_adminlog( LOG_ERR,
2438 "Permission denied-- user not allowed to delete, \
2439 pause, or resume print job. User name: %s. Printer name: %s.",
2440 uidtoname(server_info->utok.uid),
2441 lp_printername(snum) );
2443 werr = WERR_ACCESS_DENIED;
2447 ret = (*(current_printif->job_resume))(snum, pjob);
2450 werr = WERR_INVALID_PARAM;
2454 /* force update the database */
2455 print_cache_flush(lp_const_servicename(snum));
2457 /* Send a printer notify message */
2459 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2467 /****************************************************************************
2468 Write to a print file.
2469 ****************************************************************************/
2471 ssize_t print_job_write(struct tevent_context *ev,
2472 struct messaging_context *msg_ctx,
2473 int snum, uint32 jobid, const char *buf, size_t size)
2475 const char* sharename = lp_const_servicename(snum);
2476 ssize_t return_code;
2477 struct printjob *pjob;
2479 pjob = print_job_find(sharename, jobid);
2483 /* don't allow another process to get this info - it is meaningless */
2484 if (pjob->pid != sys_getpid())
2487 /* if SMBD is spooling this can't be allowed */
2488 if (pjob->status == PJOB_SMBD_SPOOLING) {
2492 return_code = write_data(pjob->fd, buf, size);
2494 if (return_code>0) {
2496 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2501 /****************************************************************************
2502 Get the queue status - do not update if db is out of date.
2503 ****************************************************************************/
2505 static int get_queue_status(const char* sharename, print_status_struct *status)
2509 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2513 ZERO_STRUCTP(status);
2520 fstr_sprintf(keystr, "STATUS/%s", sharename);
2521 data = tdb_fetch(pdb->tdb, string_tdb_data(keystr));
2523 if (data.dsize == sizeof(print_status_struct))
2524 /* this memcpy is ok since the status struct was
2525 not packed before storing it in the tdb */
2526 memcpy(status, data.dptr, sizeof(print_status_struct));
2527 SAFE_FREE(data.dptr);
2530 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2531 release_print_db(pdb);
2532 return (len == -1 ? 0 : len);
2535 /****************************************************************************
2536 Determine the number of jobs in a queue.
2537 ****************************************************************************/
2539 int print_queue_length(struct messaging_context *msg_ctx, int snum,
2540 print_status_struct *pstatus)
2542 const char* sharename = lp_const_servicename( snum );
2543 print_status_struct status;
2546 ZERO_STRUCT( status );
2548 /* make sure the database is up to date */
2549 if (print_cache_expired(lp_const_servicename(snum), True))
2550 print_queue_update(msg_ctx, snum, False);
2552 /* also fetch the queue status */
2553 memset(&status, 0, sizeof(status));
2554 len = get_queue_status(sharename, &status);
2562 /***************************************************************************
2563 Allocate a jobid. Hold the lock for as short a time as possible.
2564 ***************************************************************************/
2566 static WERROR allocate_print_jobid(struct tdb_print_db *pdb, int snum,
2567 const char *sharename, uint32 *pjobid)
2571 enum TDB_ERROR terr;
2574 *pjobid = (uint32)-1;
2576 for (i = 0; i < 3; i++) {
2577 /* Lock the database - only wait 20 seconds. */
2578 ret = tdb_lock_bystring_with_timeout(pdb->tdb,
2579 "INFO/nextjob", 20);
2581 DEBUG(0, ("allocate_print_jobid: "
2582 "Failed to lock printing database %s\n",
2584 terr = tdb_error(pdb->tdb);
2585 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2588 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2589 terr = tdb_error(pdb->tdb);
2590 if (terr != TDB_ERR_NOEXIST) {
2591 DEBUG(0, ("allocate_print_jobid: "
2592 "Failed to fetch INFO/nextjob "
2593 "for print queue %s\n", sharename));
2594 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2595 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2597 DEBUG(10, ("allocate_print_jobid: "
2598 "No existing jobid in %s\n", sharename));
2602 DEBUG(10, ("allocate_print_jobid: "
2603 "Read jobid %u from %s\n", jobid, sharename));
2605 jobid = NEXT_JOBID(jobid);
2607 ret = tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid);
2609 terr = tdb_error(pdb->tdb);
2610 DEBUG(3, ("allocate_print_jobid: "
2611 "Failed to store INFO/nextjob.\n"));
2612 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2613 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2616 /* We've finished with the INFO/nextjob lock. */
2617 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2619 if (!print_job_exists(sharename, jobid)) {
2622 DEBUG(10, ("allocate_print_jobid: "
2623 "Found jobid %u in %s\n", jobid, sharename));
2627 DEBUG(0, ("allocate_print_jobid: "
2628 "Failed to allocate a print job for queue %s\n",
2630 /* Probably full... */
2631 return WERR_NO_SPOOL_SPACE;
2634 /* Store a dummy placeholder. */
2640 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2641 TDB_INSERT) == -1) {
2642 DEBUG(3, ("allocate_print_jobid: "
2643 "jobid (%d) failed to store placeholder.\n",
2645 terr = tdb_error(pdb->tdb);
2646 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2654 /***************************************************************************
2655 Append a jobid to the 'jobs added' list.
2656 ***************************************************************************/
2658 static bool add_to_jobs_added(struct tdb_print_db *pdb, uint32 jobid)
2663 SIVAL(&store_jobid, 0, jobid);
2664 data.dptr = (uint8 *)&store_jobid;
2667 DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
2669 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_added"),
2674 /***************************************************************************
2675 Do all checks needed to determine if we can start a job.
2676 ***************************************************************************/
2678 static WERROR print_job_checks(const struct auth_serversupplied_info *server_info,
2679 struct messaging_context *msg_ctx,
2680 int snum, int *njobs)
2682 const char *sharename = lp_const_servicename(snum);
2683 uint64_t dspace, dsize;
2687 if (!print_access_check(server_info, msg_ctx, snum,
2688 PRINTER_ACCESS_USE)) {
2689 DEBUG(3, ("print_job_checks: "
2690 "job start denied by security descriptor\n"));
2691 return WERR_ACCESS_DENIED;
2694 if (!print_time_access_check(server_info, msg_ctx, sharename)) {
2695 DEBUG(3, ("print_job_checks: "
2696 "job start denied by time check\n"));
2697 return WERR_ACCESS_DENIED;
2700 /* see if we have sufficient disk space */
2701 if (lp_minprintspace(snum)) {
2702 minspace = lp_minprintspace(snum);
2703 ret = sys_fsusage(lp_pathname(snum), &dspace, &dsize);
2704 if (ret == 0 && dspace < 2*minspace) {
2705 DEBUG(3, ("print_job_checks: "
2706 "disk space check failed.\n"));
2707 return WERR_NO_SPOOL_SPACE;
2711 /* for autoloaded printers, check that the printcap entry still exists */
2712 if (lp_autoloaded(snum) && !pcap_printername_ok(sharename)) {
2713 DEBUG(3, ("print_job_checks: printer name %s check failed.\n",
2715 return WERR_ACCESS_DENIED;
2718 /* Insure the maximum queue size is not violated */
2719 *njobs = print_queue_length(msg_ctx, snum, NULL);
2720 if (*njobs > lp_maxprintjobs(snum)) {
2721 DEBUG(3, ("print_job_checks: Queue %s number of jobs (%d) "
2722 "larger than max printjobs per queue (%d).\n",
2723 sharename, *njobs, lp_maxprintjobs(snum)));
2724 return WERR_NO_SPOOL_SPACE;
2730 /***************************************************************************
2732 ***************************************************************************/
2734 static WERROR print_job_spool_file(int snum, uint32_t jobid,
2735 const char *output_file,
2736 struct printjob *pjob)
2743 /* if this file is within the printer path, it means that smbd
2744 * is spooling it and will pass us control when it is finished.
2745 * Verify that the file name is ok, within path, and it is
2746 * already already there */
2748 path = lp_pathname(snum);
2750 if (strncmp(output_file, path, len) == 0 &&
2751 (output_file[len - 1] == '/' || output_file[len] == '/')) {
2753 /* verify path is not too long */
2754 if (strlen(output_file) >= sizeof(pjob->filename)) {
2755 return WERR_INVALID_NAME;
2758 /* verify that the file exists */
2759 if (sys_stat(output_file, &st, false) != 0) {
2760 return WERR_INVALID_NAME;
2763 fstrcpy(pjob->filename, output_file);
2765 DEBUG(3, ("print_job_spool_file:"
2766 "External spooling activated"));
2768 /* we do not open the file until spooling is done */
2770 pjob->status = PJOB_SMBD_SPOOLING;
2776 slprintf(pjob->filename, sizeof(pjob->filename)-1,
2777 "%s/%s%.8u.XXXXXX", lp_pathname(snum),
2778 PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2779 pjob->fd = mkstemp(pjob->filename);
2781 if (pjob->fd == -1) {
2782 werr = map_werror_from_unix(errno);
2783 if (W_ERROR_EQUAL(werr, WERR_ACCESS_DENIED)) {
2784 /* Common setup error, force a report. */
2785 DEBUG(0, ("print_job_spool_file: "
2786 "insufficient permissions to open spool "
2787 "file %s.\n", pjob->filename));
2789 /* Normal case, report at level 3 and above. */
2790 DEBUG(3, ("print_job_spool_file: "
2791 "can't open spool file %s\n",
2800 /***************************************************************************
2801 Start spooling a job - return the jobid.
2802 ***************************************************************************/
2804 WERROR print_job_start(const struct auth_serversupplied_info *server_info,
2805 struct messaging_context *msg_ctx,
2806 const char *clientmachine,
2807 int snum, const char *docname, const char *filename,
2808 struct spoolss_DeviceMode *devmode, uint32_t *_jobid)
2812 struct printjob pjob;
2813 const char *sharename = lp_const_servicename(snum);
2814 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2819 return WERR_INTERNAL_DB_CORRUPTION;
2822 path = lp_pathname(snum);
2824 werr = print_job_checks(server_info, msg_ctx, snum, &njobs);
2825 if (!W_ERROR_IS_OK(werr)) {
2826 release_print_db(pdb);
2830 DEBUG(10, ("print_job_start: "
2831 "Queue %s number of jobs (%d), max printjobs = %d\n",
2832 sharename, njobs, lp_maxprintjobs(snum)));
2834 werr = allocate_print_jobid(pdb, snum, sharename, &jobid);
2835 if (!W_ERROR_IS_OK(werr)) {
2839 /* create the database entry */
2843 pjob.pid = sys_getpid();
2847 pjob.starttime = time(NULL);
2848 pjob.status = LPQ_SPOOLING;
2850 pjob.spooled = False;
2852 pjob.devmode = devmode;
2854 fstrcpy(pjob.jobname, docname);
2856 fstrcpy(pjob.clientmachine, clientmachine);
2858 fstrcpy(pjob.user, lp_printjob_username(snum));
2859 standard_sub_advanced(sharename, server_info->sanitized_username,
2860 path, server_info->utok.gid,
2861 server_info->sanitized_username,
2862 server_info->info3->base.domain.string,
2863 pjob.user, sizeof(pjob.user)-1);
2864 /* ensure NULL termination */
2865 pjob.user[sizeof(pjob.user)-1] = '\0';
2867 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2869 /* we have a job entry - now create the spool file */
2870 werr = print_job_spool_file(snum, jobid, filename, &pjob);
2871 if (!W_ERROR_IS_OK(werr)) {
2875 pjob_store(server_event_context(), msg_ctx, sharename, jobid, &pjob);
2877 /* Update the 'jobs added' entry used by print_queue_status. */
2878 add_to_jobs_added(pdb, jobid);
2880 /* Ensure we keep a rough count of the number of total jobs... */
2881 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2883 release_print_db(pdb);
2890 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2893 release_print_db(pdb);
2895 DEBUG(3, ("print_job_start: returning fail. "
2896 "Error = %s\n", win_errstr(werr)));
2900 /****************************************************************************
2901 Update the number of pages spooled to jobid
2902 ****************************************************************************/
2904 void print_job_endpage(struct messaging_context *msg_ctx,
2905 int snum, uint32 jobid)
2907 const char* sharename = lp_const_servicename(snum);
2908 struct printjob *pjob;
2910 pjob = print_job_find(sharename, jobid);
2913 /* don't allow another process to get this info - it is meaningless */
2914 if (pjob->pid != sys_getpid())
2918 pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
2921 /****************************************************************************
2922 Print a file - called on closing the file. This spools the job.
2923 If normal close is false then we're tearing down the jobs - treat as an
2925 ****************************************************************************/
2927 NTSTATUS print_job_end(struct messaging_context *msg_ctx, int snum,
2928 uint32 jobid, enum file_close_type close_type)
2930 const char* sharename = lp_const_servicename(snum);
2931 struct printjob *pjob;
2933 SMB_STRUCT_STAT sbuf;
2934 struct printif *current_printif = get_printer_fns( snum );
2935 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2937 pjob = print_job_find(sharename, jobid);
2940 return NT_STATUS_PRINT_CANCELLED;
2943 if (pjob->spooled || pjob->pid != sys_getpid()) {
2944 return NT_STATUS_ACCESS_DENIED;
2947 if (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) {
2948 if (pjob->status == PJOB_SMBD_SPOOLING) {
2949 /* take over the file now, smbd is done */
2950 if (sys_stat(pjob->filename, &sbuf, false) != 0) {
2951 status = map_nt_error_from_unix(errno);
2952 DEBUG(3, ("print_job_end: "
2953 "stat file failed for jobid %d\n",
2958 pjob->status = LPQ_SPOOLING;
2962 if ((sys_fstat(pjob->fd, &sbuf, false) != 0)) {
2963 status = map_nt_error_from_unix(errno);
2965 DEBUG(3, ("print_job_end: "
2966 "stat file failed for jobid %d\n",
2974 pjob->size = sbuf.st_ex_size;
2978 * Not a normal close, something has gone wrong. Cleanup.
2980 if (pjob->fd != -1) {
2986 /* Technically, this is not quite right. If the printer has a separator
2987 * page turned on, the NT spooler prints the separator page even if the
2988 * print job is 0 bytes. 010215 JRR */
2989 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
2990 /* don't bother spooling empty files or something being deleted. */
2991 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
2992 pjob->filename, pjob->size ? "deleted" : "zero length" ));
2993 unlink(pjob->filename);
2994 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2995 return NT_STATUS_OK;
2998 ret = (*(current_printif->job_submit))(snum, pjob);
3001 status = NT_STATUS_PRINT_CANCELLED;
3005 /* The print job has been successfully handed over to the back-end */
3007 pjob->spooled = True;
3008 pjob->status = LPQ_QUEUED;
3009 pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
3011 /* make sure the database is up to date */
3012 if (print_cache_expired(lp_const_servicename(snum), True))
3013 print_queue_update(msg_ctx, snum, False);
3015 return NT_STATUS_OK;
3019 /* The print job was not successfully started. Cleanup */
3020 /* Still need to add proper error return propagation! 010122:JRR */
3022 unlink(pjob->filename);
3023 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
3027 /****************************************************************************
3028 Get a snapshot of jobs in the system without traversing.
3029 ****************************************************************************/
3031 static bool get_stored_queue_info(struct messaging_context *msg_ctx,
3032 struct tdb_print_db *pdb, int snum,
3033 int *pcount, print_queue_struct **ppqueue)
3035 TDB_DATA data, cgdata, jcdata;
3036 print_queue_struct *queue = NULL;
3038 uint32 extra_count = 0;
3039 uint32_t changed_count = 0;
3040 int total_count = 0;
3043 int max_reported_jobs = lp_max_reported_jobs(snum);
3045 const char* sharename = lp_servicename(snum);
3047 /* make sure the database is up to date */
3048 if (print_cache_expired(lp_const_servicename(snum), True))
3049 print_queue_update(msg_ctx, snum, False);
3055 ZERO_STRUCT(cgdata);
3057 /* Get the stored queue data. */
3058 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
3060 if (data.dptr && data.dsize >= sizeof(qcount))
3061 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
3063 /* Get the added jobs list. */
3064 cgdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_added"));
3065 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
3066 extra_count = cgdata.dsize/4;
3068 /* Get the changed jobs list. */
3069 jcdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
3070 if (jcdata.dptr != NULL && (jcdata.dsize % 4 == 0))
3071 changed_count = jcdata.dsize / 4;
3073 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
3075 /* Allocate the queue size. */
3076 if (qcount == 0 && extra_count == 0)
3079 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
3082 /* Retrieve the linearised queue data. */
3084 for( i = 0; i < qcount; i++) {
3085 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
3086 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
3095 queue[i].sysjob = qjob;
3096 queue[i].size = qsize;
3097 queue[i].page_count = qpage_count;
3098 queue[i].status = qstatus;
3099 queue[i].priority = qpriority;
3100 queue[i].time = qtime;
3103 total_count = qcount;
3105 /* Add new jobids to the queue. */
3106 for( i = 0; i < extra_count; i++) {
3108 struct printjob *pjob;
3110 jobid = IVAL(cgdata.dptr, i*4);
3111 DEBUG(5,("get_stored_queue_info: added job = %u\n", (unsigned int)jobid));
3112 pjob = print_job_find(lp_const_servicename(snum), jobid);
3114 DEBUG(5,("get_stored_queue_info: failed to find added job = %u\n", (unsigned int)jobid));
3115 remove_from_jobs_added(sharename, jobid);
3119 queue[total_count].sysjob = jobid;
3120 queue[total_count].size = pjob->size;
3121 queue[total_count].page_count = pjob->page_count;
3122 queue[total_count].status = pjob->status;
3123 queue[total_count].priority = 1;
3124 queue[total_count].time = pjob->starttime;
3125 fstrcpy(queue[total_count].fs_user, pjob->user);
3126 fstrcpy(queue[total_count].fs_file, pjob->jobname);
3130 /* Update the changed jobids. */
3131 for (i = 0; i < changed_count; i++) {
3132 uint32_t jobid = IVAL(jcdata.dptr, i * 4);
3136 for (j = 0; j < total_count; j++) {
3137 if (queue[j].sysjob == jobid) {
3144 struct printjob *pjob;
3146 DEBUG(5,("get_stored_queue_info: changed job: %u\n",
3147 (unsigned int) jobid));
3149 pjob = print_job_find(sharename, jobid);
3151 DEBUG(5,("get_stored_queue_info: failed to find "
3152 "changed job = %u\n",
3153 (unsigned int) jobid));
3154 remove_from_jobs_changed(sharename, jobid);
3158 queue[j].sysjob = jobid;
3159 queue[j].size = pjob->size;
3160 queue[j].page_count = pjob->page_count;
3161 queue[j].status = pjob->status;
3162 queue[j].priority = 1;
3163 queue[j].time = pjob->starttime;
3164 fstrcpy(queue[j].fs_user, pjob->user);
3165 fstrcpy(queue[j].fs_file, pjob->jobname);
3167 DEBUG(5,("get_stored_queue_info: updated queue[%u], jobid: %u, jobname: %s\n",
3168 (unsigned int) j, (unsigned int) jobid, pjob->jobname));
3171 remove_from_jobs_changed(sharename, jobid);
3174 /* Sort the queue by submission time otherwise they are displayed
3177 TYPESAFE_QSORT(queue, total_count, printjob_comp);
3179 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
3181 if (max_reported_jobs && total_count > max_reported_jobs)
3182 total_count = max_reported_jobs;
3185 *pcount = total_count;
3191 SAFE_FREE(data.dptr);
3192 SAFE_FREE(cgdata.dptr);
3196 /****************************************************************************
3197 Get a printer queue listing.
3198 set queue = NULL and status = NULL if you just want to update the cache
3199 ****************************************************************************/
3201 int print_queue_status(struct messaging_context *msg_ctx, int snum,
3202 print_queue_struct **ppqueue,
3203 print_status_struct *status)
3207 const char *sharename;
3208 struct tdb_print_db *pdb;
3211 /* make sure the database is up to date */
3213 if (print_cache_expired(lp_const_servicename(snum), True))
3214 print_queue_update(msg_ctx, snum, False);
3216 /* return if we are done */
3217 if ( !ppqueue || !status )
3221 sharename = lp_const_servicename(snum);
3222 pdb = get_print_db_byname(sharename);
3228 * Fetch the queue status. We must do this first, as there may
3229 * be no jobs in the queue.
3232 ZERO_STRUCTP(status);
3233 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
3234 key = string_tdb_data(keystr);
3236 data = tdb_fetch(pdb->tdb, key);
3238 if (data.dsize == sizeof(*status)) {
3239 /* this memcpy is ok since the status struct was
3240 not packed before storing it in the tdb */
3241 memcpy(status, data.dptr, sizeof(*status));
3243 SAFE_FREE(data.dptr);
3247 * Now, fetch the print queue information. We first count the number
3248 * of entries, and then only retrieve the queue if necessary.
3251 if (!get_stored_queue_info(msg_ctx, pdb, snum, &count, ppqueue)) {
3252 release_print_db(pdb);
3256 release_print_db(pdb);
3260 /****************************************************************************
3262 ****************************************************************************/
3264 WERROR print_queue_pause(const struct auth_serversupplied_info *server_info,
3265 struct messaging_context *msg_ctx, int snum)
3268 struct printif *current_printif = get_printer_fns( snum );
3270 if (!print_access_check(server_info, msg_ctx, snum,
3271 PRINTER_ACCESS_ADMINISTER)) {
3272 return WERR_ACCESS_DENIED;
3278 ret = (*(current_printif->queue_pause))(snum);
3283 return WERR_INVALID_PARAM;
3286 /* force update the database */
3287 print_cache_flush(lp_const_servicename(snum));
3289 /* Send a printer notify message */
3291 notify_printer_status(server_event_context(), msg_ctx, snum,
3292 PRINTER_STATUS_PAUSED);
3297 /****************************************************************************
3299 ****************************************************************************/
3301 WERROR print_queue_resume(const struct auth_serversupplied_info *server_info,
3302 struct messaging_context *msg_ctx, int snum)
3305 struct printif *current_printif = get_printer_fns( snum );
3307 if (!print_access_check(server_info, msg_ctx, snum,
3308 PRINTER_ACCESS_ADMINISTER)) {
3309 return WERR_ACCESS_DENIED;
3314 ret = (*(current_printif->queue_resume))(snum);
3319 return WERR_INVALID_PARAM;
3322 /* make sure the database is up to date */
3323 if (print_cache_expired(lp_const_servicename(snum), True))
3324 print_queue_update(msg_ctx, snum, True);
3326 /* Send a printer notify message */
3328 notify_printer_status(server_event_context(), msg_ctx, snum,
3334 /****************************************************************************
3335 Purge a queue - implemented by deleting all jobs that we can delete.
3336 ****************************************************************************/
3338 WERROR print_queue_purge(const struct auth_serversupplied_info *server_info,
3339 struct messaging_context *msg_ctx, int snum)
3341 print_queue_struct *queue;
3342 print_status_struct status;
3346 /* Force and update so the count is accurate (i.e. not a cached count) */
3347 print_queue_update(msg_ctx, snum, True);
3349 can_job_admin = print_access_check(server_info,
3352 JOB_ACCESS_ADMINISTER);
3353 njobs = print_queue_status(msg_ctx, snum, &queue, &status);
3355 if ( can_job_admin )
3358 for (i=0;i<njobs;i++) {
3359 bool owner = is_owner(server_info, lp_const_servicename(snum),
3362 if (owner || can_job_admin) {
3363 print_job_delete1(server_event_context(), msg_ctx,
3364 snum, queue[i].sysjob);
3368 if ( can_job_admin )
3371 /* update the cache */
3372 print_queue_update(msg_ctx, snum, True);