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"
31 #include "printing/printer_list.h"
32 #include "printing/queue_process.h"
34 #include "smbd/smbd.h"
38 #include "lib/param/loadparm.h"
40 extern struct current_user current_user;
41 extern userdom_struct current_user_info;
43 /* Current printer interface */
44 static bool remove_from_jobs_added(const char* sharename, uint32 jobid);
47 the printing backend revolves around a tdb database that stores the
48 SMB view of the print queue
50 The key for this database is a jobid - a internally generated number that
51 uniquely identifies a print job
53 reading the print queue involves two steps:
54 - possibly running lpq and updating the internal database from that
55 - reading entries from the database
57 jobids are assigned when a job starts spooling.
60 static TDB_CONTEXT *rap_tdb;
61 static uint16 next_rap_jobid;
62 struct rap_jobid_key {
67 /***************************************************************************
68 Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
69 bit RPC jobids.... JRA.
70 ***************************************************************************/
72 uint16 pjobid_to_rap(const char* sharename, uint32 jobid)
76 struct rap_jobid_key jinfo;
79 DEBUG(10,("pjobid_to_rap: called.\n"));
82 /* Create the in-memory tdb. */
83 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
89 fstrcpy( jinfo.sharename, sharename );
91 key.dptr = (uint8 *)&jinfo;
92 key.dsize = sizeof(jinfo);
94 data = tdb_fetch_compat(rap_tdb, key);
95 if (data.dptr && data.dsize == sizeof(uint16)) {
96 rap_jobid = SVAL(data.dptr, 0);
98 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
99 (unsigned int)jobid, (unsigned int)rap_jobid));
102 SAFE_FREE(data.dptr);
103 /* Not found - create and store mapping. */
104 rap_jobid = ++next_rap_jobid;
106 rap_jobid = ++next_rap_jobid;
107 SSVAL(buf,0,rap_jobid);
109 data.dsize = sizeof(rap_jobid);
110 tdb_store(rap_tdb, key, data, TDB_REPLACE);
111 tdb_store(rap_tdb, data, key, TDB_REPLACE);
113 DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
114 (unsigned int)jobid, (unsigned int)rap_jobid));
118 bool rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
123 DEBUG(10,("rap_to_pjobid called.\n"));
128 SSVAL(buf,0,rap_jobid);
130 key.dsize = sizeof(rap_jobid);
131 data = tdb_fetch_compat(rap_tdb, key);
132 if ( data.dptr && data.dsize == sizeof(struct rap_jobid_key) )
134 struct rap_jobid_key *jinfo = (struct rap_jobid_key*)data.dptr;
135 if (sharename != NULL) {
136 fstrcpy( sharename, jinfo->sharename );
138 *pjobid = jinfo->jobid;
139 DEBUG(10,("rap_to_pjobid: jobid %u maps to RAP jobid %u\n",
140 (unsigned int)*pjobid, (unsigned int)rap_jobid));
141 SAFE_FREE(data.dptr);
145 DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
146 (unsigned int)rap_jobid));
147 SAFE_FREE(data.dptr);
151 void rap_jobid_delete(const char* sharename, uint32 jobid)
155 struct rap_jobid_key jinfo;
158 DEBUG(10,("rap_jobid_delete: called.\n"));
163 ZERO_STRUCT( jinfo );
164 fstrcpy( jinfo.sharename, sharename );
166 key.dptr = (uint8 *)&jinfo;
167 key.dsize = sizeof(jinfo);
169 data = tdb_fetch_compat(rap_tdb, key);
170 if (!data.dptr || (data.dsize != sizeof(uint16))) {
171 DEBUG(10,("rap_jobid_delete: cannot find jobid %u\n",
172 (unsigned int)jobid ));
173 SAFE_FREE(data.dptr);
177 DEBUG(10,("rap_jobid_delete: deleting jobid %u\n",
178 (unsigned int)jobid ));
180 rap_jobid = SVAL(data.dptr, 0);
181 SAFE_FREE(data.dptr);
182 SSVAL(buf,0,rap_jobid);
184 data.dsize = sizeof(rap_jobid);
185 tdb_delete(rap_tdb, key);
186 tdb_delete(rap_tdb, data);
189 static int get_queue_status(const char* sharename, print_status_struct *);
191 /****************************************************************************
192 Initialise the printing backend. Called once at startup before the fork().
193 ****************************************************************************/
195 bool print_backend_init(struct messaging_context *msg_ctx)
197 const char *sversion = "INFO/version";
198 int services = lp_numservices();
201 if (!printer_list_parent_init()) {
205 unlink(cache_path("printing.tdb"));
206 mkdir(cache_path("printing"),0755);
208 /* handle a Samba upgrade */
210 for (snum = 0; snum < services; snum++) {
211 struct tdb_print_db *pdb;
212 if (!lp_print_ok(snum))
215 pdb = get_print_db_byname(lp_const_servicename(snum));
218 if (tdb_lock_bystring(pdb->tdb, sversion) != 0) {
219 DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
220 release_print_db(pdb);
223 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
224 tdb_wipe_all(pdb->tdb);
225 tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
227 tdb_unlock_bystring(pdb->tdb, sversion);
228 release_print_db(pdb);
231 close_all_print_db(); /* Don't leave any open. */
233 /* do NT print initialization... */
234 return nt_printing_init(msg_ctx);
237 /****************************************************************************
238 Shut down printing backend. Called once at shutdown to close the tdb.
239 ****************************************************************************/
241 void printing_end(void)
243 close_all_print_db(); /* Don't leave any open. */
246 /****************************************************************************
247 Retrieve the set of printing functions for a given service. This allows
248 us to set the printer function table based on the value of the 'printing'
251 Use the generic interface as the default and only use cups interface only
252 when asked for (and only when supported)
253 ****************************************************************************/
255 static struct printif *get_printer_fns_from_type( enum printing_types type )
257 struct printif *printer_fns = &generic_printif;
260 if ( type == PRINT_CUPS ) {
261 printer_fns = &cups_printif;
263 #endif /* HAVE_CUPS */
266 if ( type == PRINT_IPRINT ) {
267 printer_fns = &iprint_printif;
269 #endif /* HAVE_IPRINT */
271 printer_fns->type = type;
276 static struct printif *get_printer_fns( int snum )
278 return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
282 /****************************************************************************
283 Useful function to generate a tdb key.
284 ****************************************************************************/
286 static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
290 SIVAL(tmp, 0, jobid);
291 ret.dptr = (uint8 *)tmp;
292 ret.dsize = sizeof(*tmp);
296 /****************************************************************************
297 Pack the devicemode to store it in a tdb.
298 ****************************************************************************/
299 static int pack_devicemode(struct spoolss_DeviceMode *devmode, uint8 *buf, int buflen)
301 enum ndr_err_code ndr_err;
306 ndr_err = ndr_push_struct_blob(&blob, talloc_tos(),
308 (ndr_push_flags_fn_t)
309 ndr_push_spoolss_DeviceMode);
310 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
311 DEBUG(10, ("pack_devicemode: "
312 "error encoding spoolss_DeviceMode\n"));
319 len = tdb_pack(buf, buflen, "B", blob.length, blob.data);
322 DEBUG(8, ("Packed devicemode [%s]\n", devmode->formname));
329 /****************************************************************************
330 Unpack the devicemode to store it in a tdb.
331 ****************************************************************************/
332 static int unpack_devicemode(TALLOC_CTX *mem_ctx,
333 const uint8 *buf, int buflen,
334 struct spoolss_DeviceMode **devmode)
336 struct spoolss_DeviceMode *dm;
337 enum ndr_err_code ndr_err;
345 len = tdb_unpack(buf, buflen, "B", &data_len, &data);
350 dm = talloc_zero(mem_ctx, struct spoolss_DeviceMode);
355 blob = data_blob_const(data, data_len);
357 ndr_err = ndr_pull_struct_blob(&blob, dm, dm,
358 (ndr_pull_flags_fn_t)ndr_pull_spoolss_DeviceMode);
359 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
360 DEBUG(10, ("unpack_devicemode: "
361 "error parsing spoolss_DeviceMode\n"));
365 DEBUG(8, ("Unpacked devicemode [%s](%s)\n",
366 dm->devicename, dm->formname));
367 if (dm->driverextra_data.data) {
368 DEBUG(8, ("with a private section of %d bytes\n",
369 dm->__driverextra_length));
379 /***********************************************************************
380 unpack a pjob from a tdb buffer
381 ***********************************************************************/
383 static int unpack_pjob(TALLOC_CTX *mem_ctx, uint8 *buf, int buflen,
384 struct printjob *pjob)
388 uint32 pjpid, pjjobid, pjsysjob, pjfd, pjstarttime, pjstatus;
389 uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
394 len += tdb_unpack(buf+len, buflen-len, "ddddddddddfffff",
414 used = unpack_devicemode(mem_ctx, buf+len, buflen-len, &pjob->devmode);
422 pjob->jobid = pjjobid;
423 pjob->sysjob = pjsysjob;
425 pjob->starttime = pjstarttime;
426 pjob->status = pjstatus;
428 pjob->page_count = pjpage_count;
429 pjob->spooled = pjspooled;
430 pjob->smbjob = pjsmbjob;
436 /****************************************************************************
437 Useful function to find a print job in the database.
438 ****************************************************************************/
440 static struct printjob *print_job_find(TALLOC_CTX *mem_ctx,
441 const char *sharename,
444 struct printjob *pjob;
447 struct tdb_print_db *pdb = get_print_db_byname(sharename);
449 DEBUG(10,("print_job_find: looking up job %u for share %s\n",
450 (unsigned int)jobid, sharename ));
456 ret = tdb_fetch_compat(pdb->tdb, print_key(jobid, &tmp));
457 release_print_db(pdb);
460 DEBUG(10, ("print_job_find: failed to find jobid %u.\n",
465 pjob = talloc_zero(mem_ctx, struct printjob);
470 if (unpack_pjob(mem_ctx, ret.dptr, ret.dsize, pjob) == -1) {
471 DEBUG(10, ("failed to unpack jobid %u.\n", jobid));
477 DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
478 pjob->sysjob, jobid));
479 SMB_ASSERT(pjob->jobid == jobid);
486 /* Convert a unix jobid to a smb jobid */
488 struct unixjob_traverse_state {
490 uint32 sysjob_to_jobid_value;
493 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
494 TDB_DATA data, void *private_data)
496 struct printjob *pjob;
497 struct unixjob_traverse_state *state =
498 (struct unixjob_traverse_state *)private_data;
500 if (!data.dptr || data.dsize == 0)
503 pjob = (struct printjob *)data.dptr;
504 if (key.dsize != sizeof(uint32))
507 if (state->sysjob == pjob->sysjob) {
508 state->sysjob_to_jobid_value = pjob->jobid;
515 static uint32 sysjob_to_jobid_pdb(struct tdb_print_db *pdb, int sysjob)
517 struct unixjob_traverse_state state;
519 state.sysjob = sysjob;
520 state.sysjob_to_jobid_value = (uint32)-1;
522 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
524 return state.sysjob_to_jobid_value;
527 /****************************************************************************
528 This is a *horribly expensive call as we have to iterate through all the
529 current printer tdb's. Don't do this often ! JRA.
530 ****************************************************************************/
532 uint32 sysjob_to_jobid(int unix_jobid)
534 int services = lp_numservices();
536 struct unixjob_traverse_state state;
538 state.sysjob = unix_jobid;
539 state.sysjob_to_jobid_value = (uint32)-1;
541 for (snum = 0; snum < services; snum++) {
542 struct tdb_print_db *pdb;
543 if (!lp_print_ok(snum))
545 pdb = get_print_db_byname(lp_const_servicename(snum));
549 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
550 release_print_db(pdb);
551 if (state.sysjob_to_jobid_value != (uint32)-1)
552 return state.sysjob_to_jobid_value;
557 /****************************************************************************
558 Send notifications based on what has changed after a pjob_store.
559 ****************************************************************************/
561 static const struct {
563 uint32_t spoolss_status;
564 } lpq_to_spoolss_status_map[] = {
565 { LPQ_QUEUED, JOB_STATUS_QUEUED },
566 { LPQ_PAUSED, JOB_STATUS_PAUSED },
567 { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
568 { LPQ_PRINTING, JOB_STATUS_PRINTING },
569 { LPQ_DELETING, JOB_STATUS_DELETING },
570 { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
571 { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
572 { LPQ_PRINTED, JOB_STATUS_PRINTED },
573 { LPQ_DELETED, JOB_STATUS_DELETED },
574 { LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
575 { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
579 /* Convert a lpq status value stored in printing.tdb into the
580 appropriate win32 API constant. */
582 static uint32 map_to_spoolss_status(uint32 lpq_status)
586 while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
587 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
588 return lpq_to_spoolss_status_map[i].spoolss_status;
595 /***************************************************************************
596 Append a jobid to the 'jobs changed' list.
597 ***************************************************************************/
599 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32_t jobid)
602 uint32_t store_jobid;
604 SIVAL(&store_jobid, 0, jobid);
605 data.dptr = (uint8 *) &store_jobid;
608 DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
610 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
614 /***************************************************************************
615 Remove a jobid from the 'jobs changed' list.
616 ***************************************************************************/
618 static bool remove_from_jobs_changed(const char* sharename, uint32_t jobid)
620 struct tdb_print_db *pdb = get_print_db_byname(sharename);
624 bool gotlock = False;
632 key = string_tdb_data("INFO/jobs_changed");
634 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) != 0)
639 data = tdb_fetch_compat(pdb->tdb, key);
641 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
644 job_count = data.dsize / 4;
645 for (i = 0; i < job_count; i++) {
648 ch_jobid = IVAL(data.dptr, i*4);
649 if (ch_jobid == jobid) {
650 if (i < job_count -1 )
651 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
653 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) != 0)
663 tdb_chainunlock(pdb->tdb, key);
664 SAFE_FREE(data.dptr);
665 release_print_db(pdb);
667 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
669 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
673 static void pjob_store_notify(struct tevent_context *ev,
674 struct messaging_context *msg_ctx,
675 const char* sharename, uint32 jobid,
676 struct printjob *old_data,
677 struct printjob *new_data,
680 bool new_job = false;
681 bool changed = false;
683 if (old_data == NULL) {
687 /* ACHTUNG! Due to a bug in Samba's spoolss parsing of the
688 NOTIFY_INFO_DATA buffer, we *have* to send the job submission
689 time first or else we'll end up with potential alignment
690 errors. I don't think the systemtime should be spooled as
691 a string, but this gets us around that error.
692 --jerry (i'll feel dirty for this) */
695 notify_job_submitted(ev, msg_ctx,
696 sharename, jobid, new_data->starttime);
697 notify_job_username(ev, msg_ctx,
698 sharename, jobid, new_data->user);
699 notify_job_name(ev, msg_ctx,
700 sharename, jobid, new_data->jobname);
701 notify_job_status(ev, msg_ctx,
702 sharename, jobid, map_to_spoolss_status(new_data->status));
703 notify_job_total_bytes(ev, msg_ctx,
704 sharename, jobid, new_data->size);
705 notify_job_total_pages(ev, msg_ctx,
706 sharename, jobid, new_data->page_count);
708 if (!strequal(old_data->jobname, new_data->jobname)) {
709 notify_job_name(ev, msg_ctx, sharename,
710 jobid, new_data->jobname);
714 if (old_data->status != new_data->status) {
715 notify_job_status(ev, msg_ctx,
717 map_to_spoolss_status(new_data->status));
720 if (old_data->size != new_data->size) {
721 notify_job_total_bytes(ev, msg_ctx,
722 sharename, jobid, new_data->size);
725 if (old_data->page_count != new_data->page_count) {
726 notify_job_total_pages(ev, msg_ctx,
728 new_data->page_count);
735 /****************************************************************************
736 Store a job structure back to the database.
737 ****************************************************************************/
739 static bool pjob_store(struct tevent_context *ev,
740 struct messaging_context *msg_ctx,
741 const char* sharename, uint32 jobid,
742 struct printjob *pjob)
745 TDB_DATA old_data, new_data;
747 struct tdb_print_db *pdb = get_print_db_byname(sharename);
749 int len, newlen, buflen;
757 old_data = tdb_fetch_compat(pdb->tdb, print_key(jobid, &tmp));
759 /* Doh! Now we have to pack/unpack data since the NT_DEVICEMODE was added */
766 len += tdb_pack(buf+len, buflen-len, "ddddddddddfffff",
769 (uint32)pjob->sysjob,
771 (uint32)pjob->starttime,
772 (uint32)pjob->status,
774 (uint32)pjob->page_count,
775 (uint32)pjob->spooled,
776 (uint32)pjob->smbjob,
783 len += pack_devicemode(pjob->devmode, buf+len, buflen-len);
786 buf = (uint8 *)SMB_REALLOC(buf, len);
788 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
793 } while ( buflen != len );
799 new_data.dsize = len;
800 ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
803 /* Send notify updates for what has changed */
806 bool changed = false;
807 struct printjob old_pjob;
809 if (old_data.dsize) {
810 TALLOC_CTX *tmp_ctx = talloc_new(ev);
814 len = unpack_pjob(tmp_ctx, old_data.dptr,
815 old_data.dsize, &old_pjob);
817 pjob_store_notify(ev,
819 sharename, jobid, &old_pjob,
823 add_to_jobs_changed(pdb, jobid);
826 talloc_free(tmp_ctx);
830 pjob_store_notify(ev, msg_ctx,
831 sharename, jobid, NULL, pjob,
837 release_print_db(pdb);
838 SAFE_FREE( old_data.dptr );
844 /****************************************************************************
845 Remove a job structure from the database.
846 ****************************************************************************/
848 static void pjob_delete(struct tevent_context *ev,
849 struct messaging_context *msg_ctx,
850 const char* sharename, uint32 jobid)
853 struct printjob *pjob;
854 uint32 job_status = 0;
855 struct tdb_print_db *pdb;
856 TALLOC_CTX *tmp_ctx = talloc_new(ev);
860 pdb = get_print_db_byname(sharename);
864 pjob = print_job_find(tmp_ctx, sharename, jobid);
866 DEBUG(5, ("we were asked to delete nonexistent job %u\n",
871 /* We must cycle through JOB_STATUS_DELETING and
872 JOB_STATUS_DELETED for the port monitor to delete the job
875 job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
876 notify_job_status(ev, msg_ctx, sharename, jobid, job_status);
878 /* Remove from printing.tdb */
880 tdb_delete(pdb->tdb, print_key(jobid, &tmp));
881 remove_from_jobs_added(sharename, jobid);
882 rap_jobid_delete(sharename, jobid);
884 release_print_db(pdb);
886 talloc_free(tmp_ctx);
889 /****************************************************************************
890 List a unix job in the print database.
891 ****************************************************************************/
893 static void print_unix_job(struct tevent_context *ev,
894 struct messaging_context *msg_ctx,
895 const char *sharename, print_queue_struct *q,
898 struct printjob pj, *old_pj;
899 TALLOC_CTX *tmp_ctx = talloc_new(ev);
903 if (jobid == (uint32)-1)
904 jobid = q->sysjob + UNIX_JOB_START;
906 /* Preserve the timestamp on an existing unix print job */
908 old_pj = print_job_find(tmp_ctx, sharename, jobid);
914 pj.sysjob = q->sysjob;
916 pj.starttime = old_pj ? old_pj->starttime : q->time;
917 pj.status = q->status;
920 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
921 if (jobid < UNIX_JOB_START) {
923 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
926 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
928 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
929 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
931 pjob_store(ev, msg_ctx, sharename, jobid, &pj);
932 talloc_free(tmp_ctx);
936 struct traverse_struct {
937 print_queue_struct *queue;
938 int qcount, snum, maxcount, total_jobs;
939 const char *sharename;
941 const char *lprm_command;
942 struct printif *print_if;
943 struct tevent_context *ev;
944 struct messaging_context *msg_ctx;
948 /****************************************************************************
949 Utility fn to delete any jobs that are no longer active.
950 ****************************************************************************/
952 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
954 struct traverse_struct *ts = (struct traverse_struct *)state;
955 struct printjob pjob;
959 if ( key.dsize != sizeof(jobid) )
962 if (unpack_pjob(ts->mem_ctx, data.dptr, data.dsize, &pjob) == -1)
964 talloc_free(pjob.devmode);
968 /* remove a unix job if it isn't in the system queue any more */
969 for (i=0;i<ts->qcount;i++) {
970 if (ts->queue[i].sysjob == pjob.sysjob)
973 if (i == ts->qcount) {
974 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
975 (unsigned int)jobid ));
976 pjob_delete(ts->ev, ts->msg_ctx,
977 ts->sharename, jobid);
981 /* need to continue the the bottom of the function to
982 save the correct attributes */
985 /* maybe it hasn't been spooled yet */
987 /* if a job is not spooled and the process doesn't
988 exist then kill it. This cleans up after smbd
990 if (!process_exists_by_pid(pjob.pid)) {
991 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
992 (unsigned int)jobid, (unsigned int)pjob.pid ));
993 pjob_delete(ts->ev, ts->msg_ctx,
994 ts->sharename, jobid);
1000 /* this check only makes sense for jobs submitted from Windows clients */
1003 for (i=0;i<ts->qcount;i++) {
1004 if ( pjob.status == LPQ_DELETED )
1007 if (ts->queue[i].sysjob == pjob.sysjob) {
1009 /* try to clean up any jobs that need to be deleted */
1011 if ( pjob.status == LPQ_DELETING ) {
1014 result = (*(ts->print_if->job_delete))(
1015 ts->sharename, ts->lprm_command, &pjob );
1017 if ( result != 0 ) {
1018 /* if we can't delete, then reset the job status */
1019 pjob.status = LPQ_QUEUED;
1020 pjob_store(ts->ev, ts->msg_ctx,
1021 ts->sharename, jobid, &pjob);
1024 /* if we deleted the job, the remove the tdb record */
1027 ts->sharename, jobid);
1028 pjob.status = LPQ_DELETED;
1038 /* The job isn't in the system queue - we have to assume it has
1039 completed, so delete the database entry. */
1041 if (i == ts->qcount) {
1043 /* A race can occur between the time a job is spooled and
1044 when it appears in the lpq output. This happens when
1045 the job is added to printing.tdb when another smbd
1046 running print_queue_update() has completed a lpq and
1047 is currently traversing the printing tdb and deleting jobs.
1048 Don't delete the job if it was submitted after the lpq_time. */
1050 if (pjob.starttime < ts->lpq_time) {
1051 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
1052 (unsigned int)jobid,
1053 (unsigned int)pjob.starttime,
1054 (unsigned int)ts->lpq_time ));
1055 pjob_delete(ts->ev, ts->msg_ctx,
1056 ts->sharename, jobid);
1062 /* Save the pjob attributes we will store. */
1063 ts->queue[i].sysjob = pjob.sysjob;
1064 ts->queue[i].size = pjob.size;
1065 ts->queue[i].page_count = pjob.page_count;
1066 ts->queue[i].status = pjob.status;
1067 ts->queue[i].priority = 1;
1068 ts->queue[i].time = pjob.starttime;
1069 fstrcpy(ts->queue[i].fs_user, pjob.user);
1070 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1077 /****************************************************************************
1078 Check if the print queue has been updated recently enough.
1079 ****************************************************************************/
1081 static void print_cache_flush(const char *sharename)
1084 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1088 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
1089 tdb_store_int32(pdb->tdb, key, -1);
1090 release_print_db(pdb);
1093 /****************************************************************************
1094 Check if someone already thinks they are doing the update.
1095 ****************************************************************************/
1097 static pid_t get_updating_pid(const char *sharename)
1102 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1106 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1107 key = string_tdb_data(keystr);
1109 data = tdb_fetch_compat(pdb->tdb, key);
1110 release_print_db(pdb);
1111 if (!data.dptr || data.dsize != sizeof(pid_t)) {
1112 SAFE_FREE(data.dptr);
1116 updating_pid = IVAL(data.dptr, 0);
1117 SAFE_FREE(data.dptr);
1119 if (process_exists_by_pid(updating_pid))
1120 return updating_pid;
1125 /****************************************************************************
1126 Set the fact that we're doing the update, or have finished doing the update
1128 ****************************************************************************/
1130 static void set_updating_pid(const fstring sharename, bool updating)
1135 pid_t updating_pid = getpid();
1138 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1143 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1144 key = string_tdb_data(keystr);
1146 DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
1147 updating ? "" : "not ",
1151 tdb_delete(pdb->tdb, key);
1152 release_print_db(pdb);
1156 SIVAL( buffer, 0, updating_pid);
1158 data.dsize = 4; /* we always assume this is a 4 byte value */
1160 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1161 release_print_db(pdb);
1164 /****************************************************************************
1165 Sort print jobs by submittal time.
1166 ****************************************************************************/
1168 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1179 /* Sort on job start time */
1181 if (j1->time == j2->time)
1183 return (j1->time > j2->time) ? 1 : -1;
1186 /****************************************************************************
1187 Store the sorted queue representation for later portmon retrieval.
1189 ****************************************************************************/
1191 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
1194 int max_reported_jobs = lp_max_reported_jobs(pts->snum);
1195 print_queue_struct *queue = pts->queue;
1198 unsigned int qcount;
1200 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
1201 pts->qcount = max_reported_jobs;
1204 /* Work out the size. */
1206 data.dsize += tdb_pack(NULL, 0, "d", qcount);
1208 for (i = 0; i < pts->qcount; i++) {
1209 if ( queue[i].status == LPQ_DELETED )
1213 data.dsize += tdb_pack(NULL, 0, "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 if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
1228 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
1229 for (i = 0; i < pts->qcount; i++) {
1230 if ( queue[i].status == LPQ_DELETED )
1233 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
1234 (uint32)queue[i].sysjob,
1235 (uint32)queue[i].size,
1236 (uint32)queue[i].page_count,
1237 (uint32)queue[i].status,
1238 (uint32)queue[i].priority,
1239 (uint32)queue[i].time,
1244 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
1246 SAFE_FREE(data.dptr);
1250 static TDB_DATA get_jobs_added_data(struct tdb_print_db *pdb)
1256 data = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_added"));
1257 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1258 SAFE_FREE(data.dptr);
1265 static void check_job_added(const char *sharename, TDB_DATA data, uint32 jobid)
1268 unsigned int job_count = data.dsize / 4;
1270 for (i = 0; i < job_count; i++) {
1273 ch_jobid = IVAL(data.dptr, i*4);
1274 if (ch_jobid == jobid)
1275 remove_from_jobs_added(sharename, jobid);
1279 /****************************************************************************
1280 Check if the print queue has been updated recently enough.
1281 ****************************************************************************/
1283 static bool print_cache_expired(const char *sharename, bool check_pending)
1286 time_t last_qscan_time, time_now = time(NULL);
1287 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1288 bool result = False;
1293 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1294 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1297 * Invalidate the queue for 3 reasons.
1298 * (1). last queue scan time == -1.
1299 * (2). Current time - last queue scan time > allowed cache time.
1300 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1301 * This last test picks up machines for which the clock has been moved
1302 * forward, an lpq scan done and then the clock moved back. Otherwise
1303 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1306 if (last_qscan_time == ((time_t)-1)
1307 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1308 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1311 time_t msg_pending_time;
1313 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1314 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1315 sharename, (int)last_qscan_time, (int)time_now,
1316 (int)lp_lpqcachetime() ));
1318 /* check if another smbd has already sent a message to update the
1319 queue. Give the pending message one minute to clear and
1320 then send another message anyways. Make sure to check for
1321 clocks that have been run forward and then back again. */
1323 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1326 && tdb_fetch_uint32( pdb->tdb, key, &u )
1327 && (msg_pending_time=u) > 0
1328 && msg_pending_time <= time_now
1329 && (time_now - msg_pending_time) < 60 )
1331 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1340 release_print_db(pdb);
1344 /****************************************************************************
1345 main work for updating the lpq cache for a printer queue
1346 ****************************************************************************/
1348 static void print_queue_update_internal(struct tevent_context *ev,
1349 struct messaging_context *msg_ctx,
1350 const char *sharename,
1351 struct printif *current_printif,
1352 char *lpq_command, char *lprm_command)
1355 print_queue_struct *queue = NULL;
1356 print_status_struct status;
1357 print_status_struct old_status;
1358 struct printjob *pjob;
1359 struct traverse_struct tstruct;
1362 fstring keystr, cachestr;
1363 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1364 TALLOC_CTX *tmp_ctx = talloc_new(ev);
1366 if ((pdb == NULL) || (tmp_ctx == NULL)) {
1370 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1371 sharename, current_printif->type, lpq_command));
1374 * Update the cache time FIRST ! Stops others even
1375 * attempting to get the lock and doing this
1376 * if the lpq takes a long time.
1379 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1380 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1382 /* get the current queue using the appropriate interface */
1383 ZERO_STRUCT(status);
1385 qcount = (*(current_printif->queue_get))(sharename,
1386 current_printif->type,
1387 lpq_command, &queue, &status);
1389 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1390 qcount, (qcount != 1) ? "s" : "", sharename));
1392 /* Sort the queue by submission time otherwise they are displayed
1395 TYPESAFE_QSORT(queue, qcount, printjob_comp);
1398 any job in the internal database that is marked as spooled
1399 and doesn't exist in the system queue is considered finished
1400 and removed from the database
1402 any job in the system database but not in the internal database
1403 is added as a unix job
1405 fill in any system job numbers as we go
1407 jcdata = get_jobs_added_data(pdb);
1409 for (i=0; i<qcount; i++) {
1410 uint32 jobid = sysjob_to_jobid_pdb(pdb, queue[i].sysjob);
1411 if (jobid == (uint32)-1) {
1412 /* assume its a unix print job */
1413 print_unix_job(ev, msg_ctx,
1414 sharename, &queue[i], jobid);
1418 /* we have an active SMB print job - update its status */
1419 pjob = print_job_find(tmp_ctx, sharename, jobid);
1421 /* err, somethings wrong. Probably smbd was restarted
1422 with jobs in the queue. All we can do is treat them
1423 like unix jobs. Pity. */
1424 DEBUG(1, ("queued print job %d not found in jobs list, "
1425 "assuming unix job\n", jobid));
1426 print_unix_job(ev, msg_ctx,
1427 sharename, &queue[i], jobid);
1431 /* don't reset the status on jobs to be deleted */
1433 if ( pjob->status != LPQ_DELETING )
1434 pjob->status = queue[i].status;
1436 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
1438 check_job_added(sharename, jcdata, jobid);
1441 SAFE_FREE(jcdata.dptr);
1443 /* now delete any queued entries that don't appear in the
1445 tstruct.queue = queue;
1446 tstruct.qcount = qcount;
1448 tstruct.total_jobs = 0;
1449 tstruct.lpq_time = time(NULL);
1450 tstruct.sharename = sharename;
1451 tstruct.lprm_command = lprm_command;
1452 tstruct.print_if = current_printif;
1454 tstruct.msg_ctx = msg_ctx;
1455 tstruct.mem_ctx = tmp_ctx;
1457 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1459 /* Store the linearised queue, max jobs only. */
1460 store_queue_struct(pdb, &tstruct);
1462 SAFE_FREE(tstruct.queue);
1463 talloc_free(tmp_ctx);
1465 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1466 sharename, tstruct.total_jobs ));
1468 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1470 get_queue_status(sharename, &old_status);
1471 if (old_status.qcount != qcount)
1472 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1473 old_status.qcount, qcount, sharename));
1475 /* store the new queue status structure */
1476 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1477 key = string_tdb_data(keystr);
1479 status.qcount = qcount;
1480 data.dptr = (uint8 *)&status;
1481 data.dsize = sizeof(status);
1482 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1485 * Update the cache time again. We want to do this call
1486 * as little as possible...
1489 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1490 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1492 /* clear the msg pending record for this queue */
1494 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1496 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1497 /* log a message but continue on */
1499 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1503 release_print_db( pdb );
1508 /****************************************************************************
1509 Update the internal database from the system print queue for a queue.
1510 obtain a lock on the print queue before proceeding (needed when mutiple
1511 smbd processes maytry to update the lpq cache concurrently).
1512 ****************************************************************************/
1514 static void print_queue_update_with_lock( struct tevent_context *ev,
1515 struct messaging_context *msg_ctx,
1516 const char *sharename,
1517 struct printif *current_printif,
1518 char *lpq_command, char *lprm_command )
1521 struct tdb_print_db *pdb;
1523 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1524 pdb = get_print_db_byname(sharename);
1528 if ( !print_cache_expired(sharename, False) ) {
1529 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1530 release_print_db(pdb);
1535 * Check to see if someone else is doing this update.
1536 * This is essentially a mutex on the update.
1539 if (get_updating_pid(sharename) != -1) {
1540 release_print_db(pdb);
1544 /* Lock the queue for the database update */
1546 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1547 /* Only wait 10 seconds for this. */
1548 if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) != 0) {
1549 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1550 release_print_db(pdb);
1555 * Ensure that no one else got in here.
1556 * If the updating pid is still -1 then we are
1560 if (get_updating_pid(sharename) != -1) {
1562 * Someone else is doing the update, exit.
1564 tdb_unlock_bystring(pdb->tdb, keystr);
1565 release_print_db(pdb);
1570 * We're going to do the update ourselves.
1573 /* Tell others we're doing the update. */
1574 set_updating_pid(sharename, True);
1577 * Allow others to enter and notice we're doing
1581 tdb_unlock_bystring(pdb->tdb, keystr);
1583 /* do the main work now */
1585 print_queue_update_internal(ev, msg_ctx,
1586 sharename, current_printif,
1587 lpq_command, lprm_command);
1589 /* Delete our pid from the db. */
1590 set_updating_pid(sharename, False);
1591 release_print_db(pdb);
1594 /****************************************************************************
1595 this is the receive function of the background lpq updater
1596 ****************************************************************************/
1597 void print_queue_receive(struct messaging_context *msg,
1600 struct server_id server_id,
1604 char *lpqcommand = NULL, *lprmcommand = NULL;
1608 len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1615 SAFE_FREE(lpqcommand);
1616 SAFE_FREE(lprmcommand);
1617 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1621 print_queue_update_with_lock(server_event_context(), msg, sharename,
1622 get_printer_fns_from_type((enum printing_types)printing_type),
1623 lpqcommand, lprmcommand );
1625 SAFE_FREE(lpqcommand);
1626 SAFE_FREE(lprmcommand);
1630 /****************************************************************************
1631 update the internal database from the system print queue for a queue
1632 ****************************************************************************/
1634 extern pid_t background_lpq_updater_pid;
1636 static void print_queue_update(struct messaging_context *msg_ctx,
1637 int snum, bool force)
1641 char *lpqcommand = NULL;
1642 char *lprmcommand = NULL;
1643 uint8 *buffer = NULL;
1646 struct tdb_print_db *pdb;
1648 struct printif *current_printif;
1649 TALLOC_CTX *ctx = talloc_tos();
1651 fstrcpy( sharename, lp_const_servicename(snum));
1653 /* don't strip out characters like '$' from the printername */
1655 lpqcommand = talloc_string_sub2(ctx,
1656 lp_lpqcommand(snum),
1658 lp_printername(snum),
1659 false, false, false);
1663 lpqcommand = talloc_sub_advanced(ctx,
1664 lp_servicename(snum),
1665 current_user_info.unix_name,
1667 current_user.ut.gid,
1668 get_current_username(),
1669 current_user_info.domain,
1675 lprmcommand = talloc_string_sub2(ctx,
1676 lp_lprmcommand(snum),
1678 lp_printername(snum),
1679 false, false, false);
1683 lprmcommand = talloc_sub_advanced(ctx,
1684 lp_servicename(snum),
1685 current_user_info.unix_name,
1687 current_user.ut.gid,
1688 get_current_username(),
1689 current_user_info.domain,
1696 * Make sure that the background queue process exists.
1697 * Otherwise just do the update ourselves
1700 if ( force || background_lpq_updater_pid == -1 ) {
1701 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1702 current_printif = get_printer_fns( snum );
1703 print_queue_update_with_lock(server_event_context(), msg_ctx,
1704 sharename, current_printif,
1705 lpqcommand, lprmcommand);
1710 type = lp_printing(snum);
1712 /* get the length */
1714 len = tdb_pack( NULL, 0, "fdPP",
1720 buffer = SMB_XMALLOC_ARRAY( uint8, len );
1722 /* now pack the buffer */
1723 newlen = tdb_pack( buffer, len, "fdPP",
1729 SMB_ASSERT( newlen == len );
1731 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1732 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1733 sharename, type, lpqcommand, lprmcommand ));
1735 /* here we set a msg pending record for other smbd processes
1736 to throttle the number of duplicate print_queue_update msgs
1739 pdb = get_print_db_byname(sharename);
1745 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1747 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1748 /* log a message but continue on */
1750 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1754 release_print_db( pdb );
1756 /* finally send the message */
1758 messaging_send_buf(msg_ctx, pid_to_procid(background_lpq_updater_pid),
1759 MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1761 SAFE_FREE( buffer );
1766 /****************************************************************************
1767 Create/Update an entry in the print tdb that will allow us to send notify
1768 updates only to interested smbd's.
1769 ****************************************************************************/
1771 bool print_notify_register_pid(int snum)
1774 struct tdb_print_db *pdb = NULL;
1775 TDB_CONTEXT *tdb = NULL;
1776 const char *printername;
1777 uint32_t mypid = (uint32_t)getpid();
1781 /* if (snum == -1), then the change notify request was
1782 on a print server handle and we need to register on
1787 int num_services = lp_numservices();
1790 for ( idx=0; idx<num_services; idx++ ) {
1791 if (lp_snum_ok(idx) && lp_print_ok(idx) )
1792 print_notify_register_pid(idx);
1797 else /* register for a specific printer */
1799 printername = lp_const_servicename(snum);
1800 pdb = get_print_db_byname(printername);
1806 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) != 0) {
1807 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1810 release_print_db(pdb);
1814 data = get_printer_notify_pid_list( tdb, printername, True );
1816 /* Add ourselves and increase the refcount. */
1818 for (i = 0; i < data.dsize; i += 8) {
1819 if (IVAL(data.dptr,i) == mypid) {
1820 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1821 SIVAL(data.dptr, i+4, new_refcount);
1826 if (i == data.dsize) {
1827 /* We weren't in the list. Realloc. */
1828 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1830 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1835 SIVAL(data.dptr,data.dsize - 8,mypid);
1836 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1839 /* Store back the record. */
1840 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) != 0) {
1841 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1842 list for printer %s\n", printername));
1850 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1852 release_print_db(pdb);
1853 SAFE_FREE(data.dptr);
1857 /****************************************************************************
1858 Update an entry in the print tdb that will allow us to send notify
1859 updates only to interested smbd's.
1860 ****************************************************************************/
1862 bool print_notify_deregister_pid(int snum)
1865 struct tdb_print_db *pdb = NULL;
1866 TDB_CONTEXT *tdb = NULL;
1867 const char *printername;
1868 uint32_t mypid = (uint32_t)getpid();
1872 /* if ( snum == -1 ), we are deregister a print server handle
1873 which means to deregister on all print queues */
1877 int num_services = lp_numservices();
1880 for ( idx=0; idx<num_services; idx++ ) {
1881 if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1882 print_notify_deregister_pid(idx);
1887 else /* deregister a specific printer */
1889 printername = lp_const_servicename(snum);
1890 pdb = get_print_db_byname(printername);
1896 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) != 0) {
1897 DEBUG(0,("print_notify_register_pid: Failed to lock \
1898 printer %s database\n", printername));
1900 release_print_db(pdb);
1904 data = get_printer_notify_pid_list( tdb, printername, True );
1906 /* Reduce refcount. Remove ourselves if zero. */
1908 for (i = 0; i < data.dsize; ) {
1909 if (IVAL(data.dptr,i) == mypid) {
1910 uint32 refcount = IVAL(data.dptr, i+4);
1914 if (refcount == 0) {
1915 if (data.dsize - i > 8)
1916 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1920 SIVAL(data.dptr, i+4, refcount);
1926 if (data.dsize == 0)
1927 SAFE_FREE(data.dptr);
1929 /* Store back the record. */
1930 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) != 0) {
1931 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1932 list for printer %s\n", printername));
1940 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1942 release_print_db(pdb);
1943 SAFE_FREE(data.dptr);
1947 /****************************************************************************
1948 Check if a jobid is valid. It is valid if it exists in the database.
1949 ****************************************************************************/
1951 bool print_job_exists(const char* sharename, uint32 jobid)
1953 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1959 ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
1960 release_print_db(pdb);
1964 /****************************************************************************
1965 Give the filename used for a jobid.
1966 Only valid for the process doing the spooling and when the job
1967 has not been spooled.
1968 ****************************************************************************/
1970 char *print_job_fname(const char* sharename, uint32 jobid)
1972 struct printjob *pjob = print_job_find(NULL, sharename, jobid);
1973 if (!pjob || pjob->spooled || pjob->pid != getpid())
1975 return pjob->filename;
1979 /****************************************************************************
1980 Give the filename used for a jobid.
1981 Only valid for the process doing the spooling and when the job
1982 has not been spooled.
1983 ****************************************************************************/
1985 struct spoolss_DeviceMode *print_job_devmode(TALLOC_CTX *mem_ctx,
1986 const char *sharename,
1989 struct printjob *pjob = print_job_find(mem_ctx, sharename, jobid);
1993 return pjob->devmode;
1996 /****************************************************************************
1997 Set the name of a job. Only possible for owner.
1998 ****************************************************************************/
2000 bool print_job_set_name(struct tevent_context *ev,
2001 struct messaging_context *msg_ctx,
2002 const char *sharename, uint32 jobid, const char *name)
2004 struct printjob *pjob;
2006 TALLOC_CTX *tmp_ctx = talloc_new(ev);
2007 if (tmp_ctx == NULL)
2010 pjob = print_job_find(tmp_ctx, sharename, jobid);
2011 if (!pjob || pjob->pid != getpid()) {
2016 fstrcpy(pjob->jobname, name);
2017 ret = pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2019 talloc_free(tmp_ctx);
2023 /****************************************************************************
2024 Get the name of a job. Only possible for owner.
2025 ****************************************************************************/
2027 bool print_job_get_name(TALLOC_CTX *mem_ctx, const char *sharename, uint32_t jobid, char **name)
2029 struct printjob *pjob;
2031 pjob = print_job_find(mem_ctx, sharename, jobid);
2032 if (!pjob || pjob->pid != getpid()) {
2036 return pjob->jobname;
2040 /***************************************************************************
2041 Remove a jobid from the 'jobs added' list.
2042 ***************************************************************************/
2044 static bool remove_from_jobs_added(const char* sharename, uint32 jobid)
2046 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2048 size_t job_count, i;
2050 bool gotlock = False;
2058 key = string_tdb_data("INFO/jobs_added");
2060 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) != 0)
2065 data = tdb_fetch_compat(pdb->tdb, key);
2067 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
2070 job_count = data.dsize / 4;
2071 for (i = 0; i < job_count; i++) {
2074 ch_jobid = IVAL(data.dptr, i*4);
2075 if (ch_jobid == jobid) {
2076 if (i < job_count -1 )
2077 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
2079 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) != 0)
2089 tdb_chainunlock(pdb->tdb, key);
2090 SAFE_FREE(data.dptr);
2091 release_print_db(pdb);
2093 DEBUG(10,("remove_from_jobs_added: removed jobid %u\n", (unsigned int)jobid ));
2095 DEBUG(10,("remove_from_jobs_added: Failed to remove jobid %u\n", (unsigned int)jobid ));
2099 /****************************************************************************
2100 Delete a print job - don't update queue.
2101 ****************************************************************************/
2103 static bool print_job_delete1(struct tevent_context *ev,
2104 struct messaging_context *msg_ctx,
2105 int snum, uint32 jobid)
2107 const char* sharename = lp_const_servicename(snum);
2108 struct printjob *pjob;
2110 struct printif *current_printif = get_printer_fns( snum );
2112 TALLOC_CTX *tmp_ctx = talloc_new(ev);
2113 if (tmp_ctx == NULL)
2116 pjob = print_job_find(tmp_ctx, sharename, jobid);
2123 * If already deleting just return.
2126 if (pjob->status == LPQ_DELETING) {
2131 /* Hrm - we need to be able to cope with deleting a job before it
2132 has reached the spooler. Just mark it as LPQ_DELETING and
2133 let the print_queue_update() code rmeove the record */
2136 if (pjob->sysjob == -1) {
2137 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
2140 /* Set the tdb entry to be deleting. */
2142 pjob->status = LPQ_DELETING;
2143 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2145 if (pjob->spooled && pjob->sysjob != -1)
2147 result = (*(current_printif->job_delete))(
2148 lp_printername(snum),
2149 lp_lprmcommand(snum),
2152 /* Delete the tdb entry if the delete succeeded or the job hasn't
2156 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2163 pjob_delete(ev, msg_ctx, sharename, jobid);
2164 /* Ensure we keep a rough count of the number of total jobs... */
2165 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
2166 release_print_db(pdb);
2170 remove_from_jobs_added( sharename, jobid );
2172 ret = (result == 0);
2174 talloc_free(tmp_ctx);
2178 /****************************************************************************
2179 Return true if the current user owns the print job.
2180 ****************************************************************************/
2182 static bool is_owner(const struct auth_session_info *server_info,
2183 const char *servicename,
2186 struct printjob *pjob;
2188 TALLOC_CTX *tmp_ctx = talloc_new(server_info);
2189 if (tmp_ctx == NULL)
2192 pjob = print_job_find(tmp_ctx, servicename, jobid);
2193 if (!pjob || !server_info) {
2198 ret = strequal(pjob->user, server_info->unix_info->sanitized_username);
2200 talloc_free(tmp_ctx);
2204 /****************************************************************************
2206 ****************************************************************************/
2208 WERROR print_job_delete(const struct auth_session_info *server_info,
2209 struct messaging_context *msg_ctx,
2210 int snum, uint32_t jobid)
2212 const char* sharename = lp_const_servicename(snum);
2213 struct printjob *pjob;
2216 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2217 if (tmp_ctx == NULL) {
2218 return WERR_NOT_ENOUGH_MEMORY;
2221 owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2223 /* Check access against security descriptor or whether the user
2227 !print_access_check(server_info, msg_ctx, snum,
2228 JOB_ACCESS_ADMINISTER)) {
2229 DEBUG(3, ("delete denied by security descriptor\n"));
2231 /* BEGIN_ADMIN_LOG */
2232 sys_adminlog( LOG_ERR,
2233 "Permission denied-- user not allowed to delete, \
2234 pause, or resume print job. User name: %s. Printer name: %s.",
2235 uidtoname(server_info->unix_token->uid),
2236 lp_printername(snum) );
2239 werr = WERR_ACCESS_DENIED;
2244 * get the spooled filename of the print job
2245 * if this works, then the file has not been spooled
2246 * to the underlying print system. Just delete the
2247 * spool file & return.
2250 pjob = print_job_find(tmp_ctx, sharename, jobid);
2251 if (!pjob || pjob->spooled || pjob->pid != getpid()) {
2252 DEBUG(10, ("Skipping spool file removal for job %u\n", jobid));
2254 DEBUG(10, ("Removing spool file [%s]\n", pjob->filename));
2255 if (unlink(pjob->filename) == -1) {
2256 werr = map_werror_from_unix(errno);
2261 if (!print_job_delete1(server_event_context(), msg_ctx, snum, jobid)) {
2262 werr = WERR_ACCESS_DENIED;
2266 /* force update the database and say the delete failed if the
2269 print_queue_update(msg_ctx, snum, True);
2271 pjob = print_job_find(tmp_ctx, sharename, jobid);
2272 if (pjob && (pjob->status != LPQ_DELETING)) {
2273 werr = WERR_ACCESS_DENIED;
2276 werr = WERR_PRINTER_HAS_JOBS_QUEUED;
2279 talloc_free(tmp_ctx);
2283 /****************************************************************************
2285 ****************************************************************************/
2287 WERROR print_job_pause(const struct auth_session_info *server_info,
2288 struct messaging_context *msg_ctx,
2289 int snum, uint32 jobid)
2291 const char* sharename = lp_const_servicename(snum);
2292 struct printjob *pjob;
2294 struct printif *current_printif = get_printer_fns( snum );
2296 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2297 if (tmp_ctx == NULL)
2298 return WERR_NOT_ENOUGH_MEMORY;
2300 pjob = print_job_find(tmp_ctx, sharename, jobid);
2301 if (!pjob || !server_info) {
2302 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2303 (unsigned int)jobid ));
2304 werr = WERR_INVALID_PARAM;
2308 if (!pjob->spooled || pjob->sysjob == -1) {
2309 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2310 (int)pjob->sysjob, (unsigned int)jobid ));
2311 werr = WERR_INVALID_PARAM;
2315 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2316 !print_access_check(server_info, msg_ctx, snum,
2317 JOB_ACCESS_ADMINISTER)) {
2318 DEBUG(3, ("pause denied by security descriptor\n"));
2320 /* BEGIN_ADMIN_LOG */
2321 sys_adminlog( LOG_ERR,
2322 "Permission denied-- user not allowed to delete, \
2323 pause, or resume print job. User name: %s. Printer name: %s.",
2324 uidtoname(server_info->unix_token->uid),
2325 lp_printername(snum) );
2328 werr = WERR_ACCESS_DENIED;
2332 /* need to pause the spooled entry */
2333 ret = (*(current_printif->job_pause))(snum, pjob);
2336 werr = WERR_INVALID_PARAM;
2340 /* force update the database */
2341 print_cache_flush(lp_const_servicename(snum));
2343 /* Send a printer notify message */
2345 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2348 /* how do we tell if this succeeded? */
2351 talloc_free(tmp_ctx);
2355 /****************************************************************************
2357 ****************************************************************************/
2359 WERROR print_job_resume(const struct auth_session_info *server_info,
2360 struct messaging_context *msg_ctx,
2361 int snum, uint32 jobid)
2363 const char *sharename = lp_const_servicename(snum);
2364 struct printjob *pjob;
2366 struct printif *current_printif = get_printer_fns( snum );
2368 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2369 if (tmp_ctx == NULL)
2370 return WERR_NOT_ENOUGH_MEMORY;
2372 pjob = print_job_find(tmp_ctx, sharename, jobid);
2373 if (!pjob || !server_info) {
2374 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2375 (unsigned int)jobid ));
2376 werr = WERR_INVALID_PARAM;
2380 if (!pjob->spooled || pjob->sysjob == -1) {
2381 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2382 (int)pjob->sysjob, (unsigned int)jobid ));
2383 werr = WERR_INVALID_PARAM;
2387 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2388 !print_access_check(server_info, msg_ctx, snum,
2389 JOB_ACCESS_ADMINISTER)) {
2390 DEBUG(3, ("resume denied by security descriptor\n"));
2392 /* BEGIN_ADMIN_LOG */
2393 sys_adminlog( LOG_ERR,
2394 "Permission denied-- user not allowed to delete, \
2395 pause, or resume print job. User name: %s. Printer name: %s.",
2396 uidtoname(server_info->unix_token->uid),
2397 lp_printername(snum) );
2399 werr = WERR_ACCESS_DENIED;
2403 ret = (*(current_printif->job_resume))(snum, pjob);
2406 werr = WERR_INVALID_PARAM;
2410 /* force update the database */
2411 print_cache_flush(lp_const_servicename(snum));
2413 /* Send a printer notify message */
2415 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2420 talloc_free(tmp_ctx);
2424 /****************************************************************************
2425 Write to a print file.
2426 ****************************************************************************/
2428 ssize_t print_job_write(struct tevent_context *ev,
2429 struct messaging_context *msg_ctx,
2430 int snum, uint32 jobid, const char *buf, size_t size)
2432 const char* sharename = lp_const_servicename(snum);
2433 ssize_t return_code;
2434 struct printjob *pjob;
2435 TALLOC_CTX *tmp_ctx = talloc_new(ev);
2436 if (tmp_ctx == NULL)
2439 pjob = print_job_find(tmp_ctx, sharename, jobid);
2445 /* don't allow another process to get this info - it is meaningless */
2446 if (pjob->pid != getpid()) {
2451 /* if SMBD is spooling this can't be allowed */
2452 if (pjob->status == PJOB_SMBD_SPOOLING) {
2457 return_code = write_data(pjob->fd, buf, size);
2458 if (return_code > 0) {
2460 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2463 talloc_free(tmp_ctx);
2467 /****************************************************************************
2468 Get the queue status - do not update if db is out of date.
2469 ****************************************************************************/
2471 static int get_queue_status(const char* sharename, print_status_struct *status)
2475 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2479 ZERO_STRUCTP(status);
2486 fstr_sprintf(keystr, "STATUS/%s", sharename);
2487 data = tdb_fetch_compat(pdb->tdb, string_tdb_data(keystr));
2489 if (data.dsize == sizeof(print_status_struct))
2490 /* this memcpy is ok since the status struct was
2491 not packed before storing it in the tdb */
2492 memcpy(status, data.dptr, sizeof(print_status_struct));
2493 SAFE_FREE(data.dptr);
2496 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2497 release_print_db(pdb);
2498 return (len == -1 ? 0 : len);
2501 /****************************************************************************
2502 Determine the number of jobs in a queue.
2503 ****************************************************************************/
2505 int print_queue_length(struct messaging_context *msg_ctx, int snum,
2506 print_status_struct *pstatus)
2508 const char* sharename = lp_const_servicename( snum );
2509 print_status_struct status;
2512 ZERO_STRUCT( status );
2514 /* make sure the database is up to date */
2515 if (print_cache_expired(lp_const_servicename(snum), True))
2516 print_queue_update(msg_ctx, snum, False);
2518 /* also fetch the queue status */
2519 memset(&status, 0, sizeof(status));
2520 len = get_queue_status(sharename, &status);
2528 /***************************************************************************
2529 Allocate a jobid. Hold the lock for as short a time as possible.
2530 ***************************************************************************/
2532 static WERROR allocate_print_jobid(struct tdb_print_db *pdb, int snum,
2533 const char *sharename, uint32 *pjobid)
2537 enum TDB_ERROR terr;
2540 *pjobid = (uint32)-1;
2542 for (i = 0; i < 3; i++) {
2543 /* Lock the database - only wait 20 seconds. */
2544 ret = tdb_lock_bystring_with_timeout(pdb->tdb,
2545 "INFO/nextjob", 20);
2547 DEBUG(0, ("allocate_print_jobid: "
2548 "Failed to lock printing database %s\n",
2550 terr = tdb_error(pdb->tdb);
2551 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2554 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2555 terr = tdb_error(pdb->tdb);
2556 if (terr != TDB_ERR_NOEXIST) {
2557 DEBUG(0, ("allocate_print_jobid: "
2558 "Failed to fetch INFO/nextjob "
2559 "for print queue %s\n", sharename));
2560 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2561 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2563 DEBUG(10, ("allocate_print_jobid: "
2564 "No existing jobid in %s\n", sharename));
2568 DEBUG(10, ("allocate_print_jobid: "
2569 "Read jobid %u from %s\n", jobid, sharename));
2571 jobid = NEXT_JOBID(jobid);
2573 ret = tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid);
2575 terr = tdb_error(pdb->tdb);
2576 DEBUG(3, ("allocate_print_jobid: "
2577 "Failed to store INFO/nextjob.\n"));
2578 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2579 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2582 /* We've finished with the INFO/nextjob lock. */
2583 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2585 if (!print_job_exists(sharename, jobid)) {
2588 DEBUG(10, ("allocate_print_jobid: "
2589 "Found jobid %u in %s\n", jobid, sharename));
2593 DEBUG(0, ("allocate_print_jobid: "
2594 "Failed to allocate a print job for queue %s\n",
2596 /* Probably full... */
2597 return WERR_NO_SPOOL_SPACE;
2600 /* Store a dummy placeholder. */
2606 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2608 DEBUG(3, ("allocate_print_jobid: "
2609 "jobid (%d) failed to store placeholder.\n",
2611 terr = tdb_error(pdb->tdb);
2612 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2620 /***************************************************************************
2621 Append a jobid to the 'jobs added' list.
2622 ***************************************************************************/
2624 static bool add_to_jobs_added(struct tdb_print_db *pdb, uint32 jobid)
2629 SIVAL(&store_jobid, 0, jobid);
2630 data.dptr = (uint8 *)&store_jobid;
2633 DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
2635 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_added"),
2640 /***************************************************************************
2641 Do all checks needed to determine if we can start a job.
2642 ***************************************************************************/
2644 static WERROR print_job_checks(const struct auth_session_info *server_info,
2645 struct messaging_context *msg_ctx,
2646 int snum, int *njobs)
2648 const char *sharename = lp_const_servicename(snum);
2649 uint64_t dspace, dsize;
2653 if (!print_access_check(server_info, msg_ctx, snum,
2654 PRINTER_ACCESS_USE)) {
2655 DEBUG(3, ("print_job_checks: "
2656 "job start denied by security descriptor\n"));
2657 return WERR_ACCESS_DENIED;
2660 if (!print_time_access_check(server_info, msg_ctx, sharename)) {
2661 DEBUG(3, ("print_job_checks: "
2662 "job start denied by time check\n"));
2663 return WERR_ACCESS_DENIED;
2666 /* see if we have sufficient disk space */
2667 if (lp_minprintspace(snum)) {
2668 minspace = lp_minprintspace(snum);
2669 ret = sys_fsusage(lp_pathname(snum), &dspace, &dsize);
2670 if (ret == 0 && dspace < 2*minspace) {
2671 DEBUG(3, ("print_job_checks: "
2672 "disk space check failed.\n"));
2673 return WERR_NO_SPOOL_SPACE;
2677 /* for autoloaded printers, check that the printcap entry still exists */
2678 if (lp_autoloaded(snum) && !pcap_printername_ok(sharename)) {
2679 DEBUG(3, ("print_job_checks: printer name %s check failed.\n",
2681 return WERR_ACCESS_DENIED;
2684 /* Insure the maximum queue size is not violated */
2685 *njobs = print_queue_length(msg_ctx, snum, NULL);
2686 if (*njobs > lp_maxprintjobs(snum)) {
2687 DEBUG(3, ("print_job_checks: Queue %s number of jobs (%d) "
2688 "larger than max printjobs per queue (%d).\n",
2689 sharename, *njobs, lp_maxprintjobs(snum)));
2690 return WERR_NO_SPOOL_SPACE;
2696 /***************************************************************************
2698 ***************************************************************************/
2700 static WERROR print_job_spool_file(int snum, uint32_t jobid,
2701 const char *output_file,
2702 struct printjob *pjob)
2709 /* if this file is within the printer path, it means that smbd
2710 * is spooling it and will pass us control when it is finished.
2711 * Verify that the file name is ok, within path, and it is
2712 * already already there */
2714 path = lp_pathname(snum);
2716 if (strncmp(output_file, path, len) == 0 &&
2717 (output_file[len - 1] == '/' || output_file[len] == '/')) {
2719 /* verify path is not too long */
2720 if (strlen(output_file) >= sizeof(pjob->filename)) {
2721 return WERR_INVALID_NAME;
2724 /* verify that the file exists */
2725 if (sys_stat(output_file, &st, false) != 0) {
2726 return WERR_INVALID_NAME;
2729 fstrcpy(pjob->filename, output_file);
2731 DEBUG(3, ("print_job_spool_file:"
2732 "External spooling activated"));
2734 /* we do not open the file until spooling is done */
2736 pjob->status = PJOB_SMBD_SPOOLING;
2742 slprintf(pjob->filename, sizeof(pjob->filename)-1,
2743 "%s/%s%.8u.XXXXXX", lp_pathname(snum),
2744 PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2745 pjob->fd = mkstemp(pjob->filename);
2747 if (pjob->fd == -1) {
2748 werr = map_werror_from_unix(errno);
2749 if (W_ERROR_EQUAL(werr, WERR_ACCESS_DENIED)) {
2750 /* Common setup error, force a report. */
2751 DEBUG(0, ("print_job_spool_file: "
2752 "insufficient permissions to open spool "
2753 "file %s.\n", pjob->filename));
2755 /* Normal case, report at level 3 and above. */
2756 DEBUG(3, ("print_job_spool_file: "
2757 "can't open spool file %s\n",
2766 /***************************************************************************
2767 Start spooling a job - return the jobid.
2768 ***************************************************************************/
2770 WERROR print_job_start(const struct auth_session_info *server_info,
2771 struct messaging_context *msg_ctx,
2772 const char *clientmachine,
2773 int snum, const char *docname, const char *filename,
2774 struct spoolss_DeviceMode *devmode, uint32_t *_jobid)
2778 struct printjob pjob;
2779 const char *sharename = lp_const_servicename(snum);
2780 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2785 return WERR_INTERNAL_DB_CORRUPTION;
2788 path = lp_pathname(snum);
2790 werr = print_job_checks(server_info, msg_ctx, snum, &njobs);
2791 if (!W_ERROR_IS_OK(werr)) {
2792 release_print_db(pdb);
2796 DEBUG(10, ("print_job_start: "
2797 "Queue %s number of jobs (%d), max printjobs = %d\n",
2798 sharename, njobs, lp_maxprintjobs(snum)));
2800 werr = allocate_print_jobid(pdb, snum, sharename, &jobid);
2801 if (!W_ERROR_IS_OK(werr)) {
2805 /* create the database entry */
2809 pjob.pid = getpid();
2813 pjob.starttime = time(NULL);
2814 pjob.status = LPQ_SPOOLING;
2816 pjob.spooled = False;
2818 pjob.devmode = devmode;
2820 fstrcpy(pjob.jobname, docname);
2822 fstrcpy(pjob.clientmachine, clientmachine);
2824 fstrcpy(pjob.user, lp_printjob_username(snum));
2825 standard_sub_advanced(sharename, server_info->unix_info->sanitized_username,
2826 path, server_info->unix_token->gid,
2827 server_info->unix_info->sanitized_username,
2828 server_info->info->domain_name,
2829 pjob.user, sizeof(pjob.user));
2831 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2833 /* we have a job entry - now create the spool file */
2834 werr = print_job_spool_file(snum, jobid, filename, &pjob);
2835 if (!W_ERROR_IS_OK(werr)) {
2839 pjob_store(server_event_context(), msg_ctx, sharename, jobid, &pjob);
2841 /* Update the 'jobs added' entry used by print_queue_status. */
2842 add_to_jobs_added(pdb, jobid);
2844 /* Ensure we keep a rough count of the number of total jobs... */
2845 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2847 release_print_db(pdb);
2854 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2857 release_print_db(pdb);
2859 DEBUG(3, ("print_job_start: returning fail. "
2860 "Error = %s\n", win_errstr(werr)));
2864 /****************************************************************************
2865 Update the number of pages spooled to jobid
2866 ****************************************************************************/
2868 void print_job_endpage(struct messaging_context *msg_ctx,
2869 int snum, uint32 jobid)
2871 const char* sharename = lp_const_servicename(snum);
2872 struct printjob *pjob;
2873 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2874 if (tmp_ctx == NULL)
2877 pjob = print_job_find(tmp_ctx, sharename, jobid);
2880 /* don't allow another process to get this info - it is meaningless */
2881 if (pjob->pid != getpid())
2885 pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
2887 talloc_free(tmp_ctx);
2890 /****************************************************************************
2891 Print a file - called on closing the file. This spools the job.
2892 If normal close is false then we're tearing down the jobs - treat as an
2894 ****************************************************************************/
2896 NTSTATUS print_job_end(struct messaging_context *msg_ctx, int snum,
2897 uint32 jobid, enum file_close_type close_type)
2899 const char* sharename = lp_const_servicename(snum);
2900 struct printjob *pjob;
2902 SMB_STRUCT_STAT sbuf;
2903 struct printif *current_printif = get_printer_fns(snum);
2904 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2905 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2906 if (tmp_ctx == NULL)
2907 return NT_STATUS_NO_MEMORY;
2909 pjob = print_job_find(tmp_ctx, sharename, jobid);
2911 status = NT_STATUS_PRINT_CANCELLED;
2915 if (pjob->spooled || pjob->pid != getpid()) {
2916 status = NT_STATUS_ACCESS_DENIED;
2920 if (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) {
2921 if (pjob->status == PJOB_SMBD_SPOOLING) {
2922 /* take over the file now, smbd is done */
2923 if (sys_stat(pjob->filename, &sbuf, false) != 0) {
2924 status = map_nt_error_from_unix(errno);
2925 DEBUG(3, ("print_job_end: "
2926 "stat file failed for jobid %d\n",
2931 pjob->status = LPQ_SPOOLING;
2935 if ((sys_fstat(pjob->fd, &sbuf, false) != 0)) {
2936 status = map_nt_error_from_unix(errno);
2938 DEBUG(3, ("print_job_end: "
2939 "stat file failed for jobid %d\n",
2947 pjob->size = sbuf.st_ex_size;
2951 * Not a normal close, something has gone wrong. Cleanup.
2953 if (pjob->fd != -1) {
2959 /* Technically, this is not quite right. If the printer has a separator
2960 * page turned on, the NT spooler prints the separator page even if the
2961 * print job is 0 bytes. 010215 JRR */
2962 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
2963 /* don't bother spooling empty files or something being deleted. */
2964 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
2965 pjob->filename, pjob->size ? "deleted" : "zero length" ));
2966 unlink(pjob->filename);
2967 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2968 return NT_STATUS_OK;
2971 ret = (*(current_printif->job_submit))(snum, pjob);
2974 status = NT_STATUS_PRINT_CANCELLED;
2978 /* The print job has been successfully handed over to the back-end */
2980 pjob->spooled = True;
2981 pjob->status = LPQ_QUEUED;
2982 pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
2984 /* make sure the database is up to date */
2985 if (print_cache_expired(lp_const_servicename(snum), True))
2986 print_queue_update(msg_ctx, snum, False);
2988 return NT_STATUS_OK;
2992 /* The print job was not successfully started. Cleanup */
2993 /* Still need to add proper error return propagation! 010122:JRR */
2995 unlink(pjob->filename);
2996 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2998 talloc_free(tmp_ctx);
3002 /****************************************************************************
3003 Get a snapshot of jobs in the system without traversing.
3004 ****************************************************************************/
3006 static bool get_stored_queue_info(struct messaging_context *msg_ctx,
3007 struct tdb_print_db *pdb, int snum,
3008 int *pcount, print_queue_struct **ppqueue)
3010 TDB_DATA data, cgdata, jcdata;
3011 print_queue_struct *queue = NULL;
3013 uint32 extra_count = 0;
3014 uint32_t changed_count = 0;
3015 int total_count = 0;
3018 int max_reported_jobs = lp_max_reported_jobs(snum);
3020 const char* sharename = lp_servicename(snum);
3021 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
3022 if (tmp_ctx == NULL)
3025 /* make sure the database is up to date */
3026 if (print_cache_expired(lp_const_servicename(snum), True))
3027 print_queue_update(msg_ctx, snum, False);
3033 ZERO_STRUCT(cgdata);
3035 /* Get the stored queue data. */
3036 data = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
3038 if (data.dptr && data.dsize >= sizeof(qcount))
3039 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
3041 /* Get the added jobs list. */
3042 cgdata = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_added"));
3043 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
3044 extra_count = cgdata.dsize/4;
3046 /* Get the changed jobs list. */
3047 jcdata = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
3048 if (jcdata.dptr != NULL && (jcdata.dsize % 4 == 0))
3049 changed_count = jcdata.dsize / 4;
3051 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
3053 /* Allocate the queue size. */
3054 if (qcount == 0 && extra_count == 0)
3057 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
3060 /* Retrieve the linearised queue data. */
3062 for( i = 0; i < qcount; i++) {
3063 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
3064 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
3073 queue[i].sysjob = qjob;
3074 queue[i].size = qsize;
3075 queue[i].page_count = qpage_count;
3076 queue[i].status = qstatus;
3077 queue[i].priority = qpriority;
3078 queue[i].time = qtime;
3081 total_count = qcount;
3083 /* Add new jobids to the queue. */
3084 for( i = 0; i < extra_count; i++) {
3086 struct printjob *pjob;
3088 jobid = IVAL(cgdata.dptr, i*4);
3089 DEBUG(5,("get_stored_queue_info: added job = %u\n", (unsigned int)jobid));
3090 pjob = print_job_find(tmp_ctx, lp_const_servicename(snum), jobid);
3092 DEBUG(5,("get_stored_queue_info: failed to find added job = %u\n", (unsigned int)jobid));
3093 remove_from_jobs_added(sharename, jobid);
3097 queue[total_count].sysjob = jobid;
3098 queue[total_count].size = pjob->size;
3099 queue[total_count].page_count = pjob->page_count;
3100 queue[total_count].status = pjob->status;
3101 queue[total_count].priority = 1;
3102 queue[total_count].time = pjob->starttime;
3103 fstrcpy(queue[total_count].fs_user, pjob->user);
3104 fstrcpy(queue[total_count].fs_file, pjob->jobname);
3109 /* Update the changed jobids. */
3110 for (i = 0; i < changed_count; i++) {
3111 uint32_t jobid = IVAL(jcdata.dptr, i * 4);
3115 for (j = 0; j < total_count; j++) {
3116 if (queue[j].sysjob == jobid) {
3123 struct printjob *pjob;
3125 DEBUG(5,("get_stored_queue_info: changed job: %u\n",
3126 (unsigned int) jobid));
3128 pjob = print_job_find(tmp_ctx, sharename, jobid);
3130 DEBUG(5,("get_stored_queue_info: failed to find "
3131 "changed job = %u\n",
3132 (unsigned int) jobid));
3133 remove_from_jobs_changed(sharename, jobid);
3137 queue[j].sysjob = jobid;
3138 queue[j].size = pjob->size;
3139 queue[j].page_count = pjob->page_count;
3140 queue[j].status = pjob->status;
3141 queue[j].priority = 1;
3142 queue[j].time = pjob->starttime;
3143 fstrcpy(queue[j].fs_user, pjob->user);
3144 fstrcpy(queue[j].fs_file, pjob->jobname);
3147 DEBUG(5,("get_stored_queue_info: updated queue[%u], jobid: %u, jobname: %s\n",
3148 (unsigned int) j, (unsigned int) jobid, pjob->jobname));
3151 remove_from_jobs_changed(sharename, jobid);
3154 /* Sort the queue by submission time otherwise they are displayed
3157 TYPESAFE_QSORT(queue, total_count, printjob_comp);
3159 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
3161 if (max_reported_jobs && total_count > max_reported_jobs)
3162 total_count = max_reported_jobs;
3165 *pcount = total_count;
3171 SAFE_FREE(data.dptr);
3172 SAFE_FREE(cgdata.dptr);
3173 talloc_free(tmp_ctx);
3177 /****************************************************************************
3178 Get a printer queue listing.
3179 set queue = NULL and status = NULL if you just want to update the cache
3180 ****************************************************************************/
3182 int print_queue_status(struct messaging_context *msg_ctx, int snum,
3183 print_queue_struct **ppqueue,
3184 print_status_struct *status)
3188 const char *sharename;
3189 struct tdb_print_db *pdb;
3192 /* make sure the database is up to date */
3194 if (print_cache_expired(lp_const_servicename(snum), True))
3195 print_queue_update(msg_ctx, snum, False);
3197 /* return if we are done */
3198 if ( !ppqueue || !status )
3202 sharename = lp_const_servicename(snum);
3203 pdb = get_print_db_byname(sharename);
3209 * Fetch the queue status. We must do this first, as there may
3210 * be no jobs in the queue.
3213 ZERO_STRUCTP(status);
3214 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
3215 key = string_tdb_data(keystr);
3217 data = tdb_fetch_compat(pdb->tdb, key);
3219 if (data.dsize == sizeof(*status)) {
3220 /* this memcpy is ok since the status struct was
3221 not packed before storing it in the tdb */
3222 memcpy(status, data.dptr, sizeof(*status));
3224 SAFE_FREE(data.dptr);
3228 * Now, fetch the print queue information. We first count the number
3229 * of entries, and then only retrieve the queue if necessary.
3232 if (!get_stored_queue_info(msg_ctx, pdb, snum, &count, ppqueue)) {
3233 release_print_db(pdb);
3237 release_print_db(pdb);
3241 /****************************************************************************
3243 ****************************************************************************/
3245 WERROR print_queue_pause(const struct auth_session_info *server_info,
3246 struct messaging_context *msg_ctx, int snum)
3249 struct printif *current_printif = get_printer_fns( snum );
3251 if (!print_access_check(server_info, msg_ctx, snum,
3252 PRINTER_ACCESS_ADMINISTER)) {
3253 return WERR_ACCESS_DENIED;
3259 ret = (*(current_printif->queue_pause))(snum);
3264 return WERR_INVALID_PARAM;
3267 /* force update the database */
3268 print_cache_flush(lp_const_servicename(snum));
3270 /* Send a printer notify message */
3272 notify_printer_status(server_event_context(), msg_ctx, snum,
3273 PRINTER_STATUS_PAUSED);
3278 /****************************************************************************
3280 ****************************************************************************/
3282 WERROR print_queue_resume(const struct auth_session_info *server_info,
3283 struct messaging_context *msg_ctx, int snum)
3286 struct printif *current_printif = get_printer_fns( snum );
3288 if (!print_access_check(server_info, msg_ctx, snum,
3289 PRINTER_ACCESS_ADMINISTER)) {
3290 return WERR_ACCESS_DENIED;
3295 ret = (*(current_printif->queue_resume))(snum);
3300 return WERR_INVALID_PARAM;
3303 /* make sure the database is up to date */
3304 if (print_cache_expired(lp_const_servicename(snum), True))
3305 print_queue_update(msg_ctx, snum, True);
3307 /* Send a printer notify message */
3309 notify_printer_status(server_event_context(), msg_ctx, snum,
3315 /****************************************************************************
3316 Purge a queue - implemented by deleting all jobs that we can delete.
3317 ****************************************************************************/
3319 WERROR print_queue_purge(const struct auth_session_info *server_info,
3320 struct messaging_context *msg_ctx, int snum)
3322 print_queue_struct *queue;
3323 print_status_struct status;
3327 /* Force and update so the count is accurate (i.e. not a cached count) */
3328 print_queue_update(msg_ctx, snum, True);
3330 can_job_admin = print_access_check(server_info,
3333 JOB_ACCESS_ADMINISTER);
3334 njobs = print_queue_status(msg_ctx, snum, &queue, &status);
3336 if ( can_job_admin )
3339 for (i=0;i<njobs;i++) {
3340 bool owner = is_owner(server_info, lp_const_servicename(snum),
3343 if (owner || can_job_admin) {
3344 print_job_delete1(server_event_context(), msg_ctx,
3345 snum, queue[i].sysjob);
3349 if ( can_job_admin )
3352 /* update the cache */
3353 print_queue_update(msg_ctx, snum, True);