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 /* FIXME talloc ctx */
377 static int unpack_pjob(uint8 *buf, int buflen, struct printjob *pjob)
381 uint32 pjpid, pjjobid, pjsysjob, pjfd, pjstarttime, pjstatus;
382 uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
388 len += tdb_unpack(buf+len, buflen-len, "ddddddddddfffff",
409 used = unpack_devicemode(NULL, buf+len, buflen-len, &pjob->devmode);
417 pjob->jobid = pjjobid;
418 pjob->sysjob = pjsysjob;
420 pjob->starttime = pjstarttime;
421 pjob->status = pjstatus;
423 pjob->page_count = pjpage_count;
424 pjob->spooled = pjspooled;
425 pjob->smbjob = pjsmbjob;
431 /****************************************************************************
432 Useful function to find a print job in the database.
433 ****************************************************************************/
435 static struct printjob *print_job_find(TALLOC_CTX *mem_ctx,
436 const char *sharename,
439 struct printjob *pjob;
442 struct tdb_print_db *pdb = get_print_db_byname(sharename);
444 DEBUG(10,("print_job_find: looking up job %u for share %s\n",
445 (unsigned int)jobid, sharename ));
451 ret = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
452 release_print_db(pdb);
455 DEBUG(10, ("print_job_find: failed to find jobid %u.\n",
460 pjob = talloc_zero(mem_ctx, struct printjob);
465 if (unpack_pjob(ret.dptr, ret.dsize, pjob) == -1) {
466 DEBUG(10, ("failed to unpack jobid %u.\n", jobid));
472 DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
473 pjob->sysjob, jobid));
474 SMB_ASSERT(pjob->jobid == jobid);
481 /* Convert a unix jobid to a smb jobid */
483 struct unixjob_traverse_state {
485 uint32 sysjob_to_jobid_value;
488 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
489 TDB_DATA data, void *private_data)
491 struct printjob *pjob;
492 struct unixjob_traverse_state *state =
493 (struct unixjob_traverse_state *)private_data;
495 if (!data.dptr || data.dsize == 0)
498 pjob = (struct printjob *)data.dptr;
499 if (key.dsize != sizeof(uint32))
502 if (state->sysjob == pjob->sysjob) {
503 state->sysjob_to_jobid_value = pjob->jobid;
510 static uint32 sysjob_to_jobid_pdb(struct tdb_print_db *pdb, int sysjob)
512 struct unixjob_traverse_state state;
514 state.sysjob = sysjob;
515 state.sysjob_to_jobid_value = (uint32)-1;
517 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
519 return state.sysjob_to_jobid_value;
522 /****************************************************************************
523 This is a *horribly expensive call as we have to iterate through all the
524 current printer tdb's. Don't do this often ! JRA.
525 ****************************************************************************/
527 uint32 sysjob_to_jobid(int unix_jobid)
529 int services = lp_numservices();
531 struct unixjob_traverse_state state;
533 state.sysjob = unix_jobid;
534 state.sysjob_to_jobid_value = (uint32)-1;
536 for (snum = 0; snum < services; snum++) {
537 struct tdb_print_db *pdb;
538 if (!lp_print_ok(snum))
540 pdb = get_print_db_byname(lp_const_servicename(snum));
544 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
545 release_print_db(pdb);
546 if (state.sysjob_to_jobid_value != (uint32)-1)
547 return state.sysjob_to_jobid_value;
552 /****************************************************************************
553 Send notifications based on what has changed after a pjob_store.
554 ****************************************************************************/
556 static const struct {
558 uint32_t spoolss_status;
559 } lpq_to_spoolss_status_map[] = {
560 { LPQ_QUEUED, JOB_STATUS_QUEUED },
561 { LPQ_PAUSED, JOB_STATUS_PAUSED },
562 { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
563 { LPQ_PRINTING, JOB_STATUS_PRINTING },
564 { LPQ_DELETING, JOB_STATUS_DELETING },
565 { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
566 { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
567 { LPQ_PRINTED, JOB_STATUS_PRINTED },
568 { LPQ_DELETED, JOB_STATUS_DELETED },
569 { LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
570 { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
574 /* Convert a lpq status value stored in printing.tdb into the
575 appropriate win32 API constant. */
577 static uint32 map_to_spoolss_status(uint32 lpq_status)
581 while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
582 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
583 return lpq_to_spoolss_status_map[i].spoolss_status;
590 /***************************************************************************
591 Append a jobid to the 'jobs changed' list.
592 ***************************************************************************/
594 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32_t jobid)
597 uint32_t store_jobid;
599 SIVAL(&store_jobid, 0, jobid);
600 data.dptr = (uint8 *) &store_jobid;
603 DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
605 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
609 /***************************************************************************
610 Remove a jobid from the 'jobs changed' list.
611 ***************************************************************************/
613 static bool remove_from_jobs_changed(const char* sharename, uint32_t jobid)
615 struct tdb_print_db *pdb = get_print_db_byname(sharename);
619 bool gotlock = False;
627 key = string_tdb_data("INFO/jobs_changed");
629 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
634 data = tdb_fetch(pdb->tdb, key);
636 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
639 job_count = data.dsize / 4;
640 for (i = 0; i < job_count; i++) {
643 ch_jobid = IVAL(data.dptr, i*4);
644 if (ch_jobid == jobid) {
645 if (i < job_count -1 )
646 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
648 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
658 tdb_chainunlock(pdb->tdb, key);
659 SAFE_FREE(data.dptr);
660 release_print_db(pdb);
662 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
664 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
668 static void pjob_store_notify(struct tevent_context *ev,
669 struct messaging_context *msg_ctx,
670 const char* sharename, uint32 jobid,
671 struct printjob *old_data,
672 struct printjob *new_data,
675 bool new_job = false;
676 bool changed = false;
678 if (old_data == NULL) {
682 /* ACHTUNG! Due to a bug in Samba's spoolss parsing of the
683 NOTIFY_INFO_DATA buffer, we *have* to send the job submission
684 time first or else we'll end up with potential alignment
685 errors. I don't think the systemtime should be spooled as
686 a string, but this gets us around that error.
687 --jerry (i'll feel dirty for this) */
690 notify_job_submitted(ev, msg_ctx,
691 sharename, jobid, new_data->starttime);
692 notify_job_username(ev, msg_ctx,
693 sharename, jobid, new_data->user);
694 notify_job_name(ev, msg_ctx,
695 sharename, jobid, new_data->jobname);
696 notify_job_status(ev, msg_ctx,
697 sharename, jobid, map_to_spoolss_status(new_data->status));
698 notify_job_total_bytes(ev, msg_ctx,
699 sharename, jobid, new_data->size);
700 notify_job_total_pages(ev, msg_ctx,
701 sharename, jobid, new_data->page_count);
703 if (!strequal(old_data->jobname, new_data->jobname)) {
704 notify_job_name(ev, msg_ctx, sharename,
705 jobid, new_data->jobname);
709 if (old_data->status != new_data->status) {
710 notify_job_status(ev, msg_ctx,
712 map_to_spoolss_status(new_data->status));
715 if (old_data->size != new_data->size) {
716 notify_job_total_bytes(ev, msg_ctx,
717 sharename, jobid, new_data->size);
720 if (old_data->page_count != new_data->page_count) {
721 notify_job_total_pages(ev, msg_ctx,
723 new_data->page_count);
730 /****************************************************************************
731 Store a job structure back to the database.
732 ****************************************************************************/
734 static bool pjob_store(struct tevent_context *ev,
735 struct messaging_context *msg_ctx,
736 const char* sharename, uint32 jobid,
737 struct printjob *pjob)
740 TDB_DATA old_data, new_data;
742 struct tdb_print_db *pdb = get_print_db_byname(sharename);
744 int len, newlen, buflen;
752 old_data = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
754 /* Doh! Now we have to pack/unpack data since the NT_DEVICEMODE was added */
761 len += tdb_pack(buf+len, buflen-len, "ddddddddddfffff",
764 (uint32)pjob->sysjob,
766 (uint32)pjob->starttime,
767 (uint32)pjob->status,
769 (uint32)pjob->page_count,
770 (uint32)pjob->spooled,
771 (uint32)pjob->smbjob,
778 len += pack_devicemode(pjob->devmode, buf+len, buflen-len);
781 buf = (uint8 *)SMB_REALLOC(buf, len);
783 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
788 } while ( buflen != len );
794 new_data.dsize = len;
795 ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
798 /* Send notify updates for what has changed */
801 bool changed = false;
802 struct printjob old_pjob;
804 if ( old_data.dsize )
806 if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
808 pjob_store_notify(server_event_context(),
810 sharename, jobid, &old_pjob,
813 talloc_free(old_pjob.devmode);
816 add_to_jobs_changed(pdb, jobid);
823 pjob_store_notify(server_event_context(), msg_ctx,
824 sharename, jobid, NULL, pjob,
830 release_print_db(pdb);
831 SAFE_FREE( old_data.dptr );
837 /****************************************************************************
838 Remove a job structure from the database.
839 ****************************************************************************/
841 static void pjob_delete(struct tevent_context *ev,
842 struct messaging_context *msg_ctx,
843 const char* sharename, uint32 jobid)
846 struct printjob *pjob;
847 uint32 job_status = 0;
848 struct tdb_print_db *pdb;
849 TALLOC_CTX *tmp_ctx = talloc_new(ev);
850 if (tmp_ctx == NULL) {
854 pdb = get_print_db_byname(sharename);
859 pjob = print_job_find(tmp_ctx, sharename, jobid);
861 DEBUG(5, ("we were asked to delete nonexistent job %u\n",
866 /* We must cycle through JOB_STATUS_DELETING and
867 JOB_STATUS_DELETED for the port monitor to delete the job
870 job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
871 notify_job_status(ev, msg_ctx, sharename, jobid, job_status);
873 /* Remove from printing.tdb */
875 tdb_delete(pdb->tdb, print_key(jobid, &tmp));
876 remove_from_jobs_added(sharename, jobid);
877 rap_jobid_delete(sharename, jobid);
879 release_print_db(pdb);
881 talloc_free(tmp_ctx);
884 /****************************************************************************
885 List a unix job in the print database.
886 ****************************************************************************/
888 static void print_unix_job(struct tevent_context *ev,
889 struct messaging_context *msg_ctx,
890 const char *sharename, print_queue_struct *q,
893 struct printjob pj, *old_pj;
894 TALLOC_CTX *tmp_ctx = talloc_new(ev);
895 if (tmp_ctx == NULL) {
899 if (jobid == (uint32)-1) {
900 jobid = q->sysjob + UNIX_JOB_START;
903 /* Preserve the timestamp on an existing unix print job */
905 old_pj = print_job_find(tmp_ctx, sharename, jobid);
911 pj.sysjob = q->sysjob;
913 pj.starttime = old_pj ? old_pj->starttime : q->time;
914 pj.status = q->status;
917 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
918 if (jobid < UNIX_JOB_START) {
920 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
923 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
925 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
926 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
928 pjob_store(ev, msg_ctx, sharename, jobid, &pj);
929 talloc_free(tmp_ctx);
933 struct traverse_struct {
934 print_queue_struct *queue;
935 int qcount, snum, maxcount, total_jobs;
936 const char *sharename;
938 const char *lprm_command;
939 struct printif *print_if;
940 struct tevent_context *ev;
941 struct messaging_context *msg_ctx;
944 /****************************************************************************
945 Utility fn to delete any jobs that are no longer active.
946 ****************************************************************************/
948 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
950 struct traverse_struct *ts = (struct traverse_struct *)state;
951 struct printjob pjob;
955 if ( key.dsize != sizeof(jobid) )
958 if (unpack_pjob(data.dptr, data.dsize, &pjob) == -1)
960 talloc_free(pjob.devmode);
964 /* remove a unix job if it isn't in the system queue any more */
965 for (i=0;i<ts->qcount;i++) {
966 if (ts->queue[i].sysjob == pjob.sysjob) {
970 if (i == ts->qcount) {
971 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
972 (unsigned int)jobid ));
973 pjob_delete(ts->ev, ts->msg_ctx,
974 ts->sharename, jobid);
978 /* need to continue the the bottom of the function to
979 save the correct attributes */
982 /* maybe it hasn't been spooled yet */
984 /* if a job is not spooled and the process doesn't
985 exist then kill it. This cleans up after smbd
987 if (!process_exists_by_pid(pjob.pid)) {
988 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
989 (unsigned int)jobid, (unsigned int)pjob.pid ));
990 pjob_delete(ts->ev, ts->msg_ctx,
991 ts->sharename, jobid);
997 /* this check only makes sense for jobs submitted from Windows clients */
1000 for (i=0;i<ts->qcount;i++) {
1001 if ( pjob.status == LPQ_DELETED )
1004 if (ts->queue[i].sysjob == pjob.sysjob) {
1006 /* try to clean up any jobs that need to be deleted */
1008 if ( pjob.status == LPQ_DELETING ) {
1011 result = (*(ts->print_if->job_delete))(
1012 ts->sharename, ts->lprm_command, &pjob );
1014 if ( result != 0 ) {
1015 /* if we can't delete, then reset the job status */
1016 pjob.status = LPQ_QUEUED;
1017 pjob_store(ts->ev, ts->msg_ctx,
1018 ts->sharename, jobid, &pjob);
1021 /* if we deleted the job, the remove the tdb record */
1024 ts->sharename, jobid);
1025 pjob.status = LPQ_DELETED;
1035 /* The job isn't in the system queue - we have to assume it has
1036 completed, so delete the database entry. */
1038 if (i == ts->qcount) {
1040 /* A race can occur between the time a job is spooled and
1041 when it appears in the lpq output. This happens when
1042 the job is added to printing.tdb when another smbd
1043 running print_queue_update() has completed a lpq and
1044 is currently traversing the printing tdb and deleting jobs.
1045 Don't delete the job if it was submitted after the lpq_time. */
1047 if (pjob.starttime < ts->lpq_time) {
1048 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
1049 (unsigned int)jobid,
1050 (unsigned int)pjob.starttime,
1051 (unsigned int)ts->lpq_time ));
1052 pjob_delete(ts->ev, ts->msg_ctx,
1053 ts->sharename, jobid);
1059 /* Save the pjob attributes we will store. */
1060 ts->queue[i].sysjob = pjob.sysjob;
1061 ts->queue[i].size = pjob.size;
1062 ts->queue[i].page_count = pjob.page_count;
1063 ts->queue[i].status = pjob.status;
1064 ts->queue[i].priority = 1;
1065 ts->queue[i].time = pjob.starttime;
1066 fstrcpy(ts->queue[i].fs_user, pjob.user);
1067 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1074 /****************************************************************************
1075 Check if the print queue has been updated recently enough.
1076 ****************************************************************************/
1078 static void print_cache_flush(const char *sharename)
1081 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1085 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
1086 tdb_store_int32(pdb->tdb, key, -1);
1087 release_print_db(pdb);
1090 /****************************************************************************
1091 Check if someone already thinks they are doing the update.
1092 ****************************************************************************/
1094 static pid_t get_updating_pid(const char *sharename)
1099 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1103 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1104 key = string_tdb_data(keystr);
1106 data = tdb_fetch(pdb->tdb, key);
1107 release_print_db(pdb);
1108 if (!data.dptr || data.dsize != sizeof(pid_t)) {
1109 SAFE_FREE(data.dptr);
1113 updating_pid = IVAL(data.dptr, 0);
1114 SAFE_FREE(data.dptr);
1116 if (process_exists_by_pid(updating_pid))
1117 return updating_pid;
1122 /****************************************************************************
1123 Set the fact that we're doing the update, or have finished doing the update
1125 ****************************************************************************/
1127 static void set_updating_pid(const fstring sharename, bool updating)
1132 pid_t updating_pid = sys_getpid();
1135 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1140 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1141 key = string_tdb_data(keystr);
1143 DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
1144 updating ? "" : "not ",
1148 tdb_delete(pdb->tdb, key);
1149 release_print_db(pdb);
1153 SIVAL( buffer, 0, updating_pid);
1155 data.dsize = 4; /* we always assume this is a 4 byte value */
1157 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1158 release_print_db(pdb);
1161 /****************************************************************************
1162 Sort print jobs by submittal time.
1163 ****************************************************************************/
1165 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1176 /* Sort on job start time */
1178 if (j1->time == j2->time)
1180 return (j1->time > j2->time) ? 1 : -1;
1183 /****************************************************************************
1184 Store the sorted queue representation for later portmon retrieval.
1186 ****************************************************************************/
1188 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
1191 int max_reported_jobs = lp_max_reported_jobs(pts->snum);
1192 print_queue_struct *queue = pts->queue;
1195 unsigned int qcount;
1197 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
1198 pts->qcount = max_reported_jobs;
1201 /* Work out the size. */
1203 data.dsize += tdb_pack(NULL, 0, "d", qcount);
1205 for (i = 0; i < pts->qcount; i++) {
1206 if ( queue[i].status == LPQ_DELETED )
1210 data.dsize += tdb_pack(NULL, 0, "ddddddff",
1211 (uint32)queue[i].sysjob,
1212 (uint32)queue[i].size,
1213 (uint32)queue[i].page_count,
1214 (uint32)queue[i].status,
1215 (uint32)queue[i].priority,
1216 (uint32)queue[i].time,
1221 if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
1225 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
1226 for (i = 0; i < pts->qcount; i++) {
1227 if ( queue[i].status == LPQ_DELETED )
1230 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
1231 (uint32)queue[i].sysjob,
1232 (uint32)queue[i].size,
1233 (uint32)queue[i].page_count,
1234 (uint32)queue[i].status,
1235 (uint32)queue[i].priority,
1236 (uint32)queue[i].time,
1241 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
1243 SAFE_FREE(data.dptr);
1247 static TDB_DATA get_jobs_added_data(struct tdb_print_db *pdb)
1253 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_added"));
1254 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1255 SAFE_FREE(data.dptr);
1262 static void check_job_added(const char *sharename, TDB_DATA data, uint32 jobid)
1265 unsigned int job_count = data.dsize / 4;
1267 for (i = 0; i < job_count; i++) {
1270 ch_jobid = IVAL(data.dptr, i*4);
1271 if (ch_jobid == jobid)
1272 remove_from_jobs_added(sharename, jobid);
1276 /****************************************************************************
1277 Check if the print queue has been updated recently enough.
1278 ****************************************************************************/
1280 static bool print_cache_expired(const char *sharename, bool check_pending)
1283 time_t last_qscan_time, time_now = time(NULL);
1284 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1285 bool result = False;
1290 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1291 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1294 * Invalidate the queue for 3 reasons.
1295 * (1). last queue scan time == -1.
1296 * (2). Current time - last queue scan time > allowed cache time.
1297 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1298 * This last test picks up machines for which the clock has been moved
1299 * forward, an lpq scan done and then the clock moved back. Otherwise
1300 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1303 if (last_qscan_time == ((time_t)-1)
1304 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1305 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1308 time_t msg_pending_time;
1310 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1311 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1312 sharename, (int)last_qscan_time, (int)time_now,
1313 (int)lp_lpqcachetime() ));
1315 /* check if another smbd has already sent a message to update the
1316 queue. Give the pending message one minute to clear and
1317 then send another message anyways. Make sure to check for
1318 clocks that have been run forward and then back again. */
1320 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1323 && tdb_fetch_uint32( pdb->tdb, key, &u )
1324 && (msg_pending_time=u) > 0
1325 && msg_pending_time <= time_now
1326 && (time_now - msg_pending_time) < 60 )
1328 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1337 release_print_db(pdb);
1341 /****************************************************************************
1342 main work for updating the lpq cache for a printer queue
1343 ****************************************************************************/
1345 static void print_queue_update_internal(struct tevent_context *ev,
1346 struct messaging_context *msg_ctx,
1347 const char *sharename,
1348 struct printif *current_printif,
1349 char *lpq_command, char *lprm_command)
1352 print_queue_struct *queue = NULL;
1353 print_status_struct status;
1354 print_status_struct old_status;
1355 struct printjob *pjob;
1356 struct traverse_struct tstruct;
1359 fstring keystr, cachestr;
1360 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1361 TALLOC_CTX *tmp_ctx = talloc_new(ev);
1363 if ((pdb == NULL) || (tmp_ctx == NULL)) {
1367 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1368 sharename, current_printif->type, lpq_command));
1371 * Update the cache time FIRST ! Stops others even
1372 * attempting to get the lock and doing this
1373 * if the lpq takes a long time.
1376 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1377 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1379 /* get the current queue using the appropriate interface */
1380 ZERO_STRUCT(status);
1382 qcount = (*(current_printif->queue_get))(sharename,
1383 current_printif->type,
1384 lpq_command, &queue, &status);
1386 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1387 qcount, (qcount != 1) ? "s" : "", sharename));
1389 /* Sort the queue by submission time otherwise they are displayed
1392 TYPESAFE_QSORT(queue, qcount, printjob_comp);
1395 any job in the internal database that is marked as spooled
1396 and doesn't exist in the system queue is considered finished
1397 and removed from the database
1399 any job in the system database but not in the internal database
1400 is added as a unix job
1402 fill in any system job numbers as we go
1404 jcdata = get_jobs_added_data(pdb);
1406 for (i=0; i<qcount; i++) {
1407 uint32 jobid = sysjob_to_jobid_pdb(pdb, queue[i].sysjob);
1408 if (jobid == (uint32)-1) {
1409 /* assume its a unix print job */
1410 print_unix_job(ev, msg_ctx,
1411 sharename, &queue[i], jobid);
1415 /* we have an active SMB print job - update its status */
1416 pjob = print_job_find(tmp_ctx, sharename, jobid);
1418 /* err, somethings wrong. Probably smbd was restarted
1419 with jobs in the queue. All we can do is treat them
1420 like unix jobs. Pity. */
1421 DEBUG(1, ("queued print job %d not found in jobs list, "
1422 "assuming unix job\n", jobid));
1423 print_unix_job(ev, msg_ctx,
1424 sharename, &queue[i], jobid);
1428 /* don't reset the status on jobs to be deleted */
1430 if ( pjob->status != LPQ_DELETING )
1431 pjob->status = queue[i].status;
1433 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
1435 check_job_added(sharename, jcdata, jobid);
1438 SAFE_FREE(jcdata.dptr);
1439 talloc_free(tmp_ctx);
1441 /* now delete any queued entries that don't appear in the
1443 tstruct.queue = queue;
1444 tstruct.qcount = qcount;
1446 tstruct.total_jobs = 0;
1447 tstruct.lpq_time = time(NULL);
1448 tstruct.sharename = sharename;
1449 tstruct.lprm_command = lprm_command;
1450 tstruct.print_if = current_printif;
1452 tstruct.msg_ctx = msg_ctx;
1454 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1456 /* Store the linearised queue, max jobs only. */
1457 store_queue_struct(pdb, &tstruct);
1459 SAFE_FREE(tstruct.queue);
1461 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1462 sharename, tstruct.total_jobs ));
1464 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1466 get_queue_status(sharename, &old_status);
1467 if (old_status.qcount != qcount)
1468 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1469 old_status.qcount, qcount, sharename));
1471 /* store the new queue status structure */
1472 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1473 key = string_tdb_data(keystr);
1475 status.qcount = qcount;
1476 data.dptr = (uint8 *)&status;
1477 data.dsize = sizeof(status);
1478 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1481 * Update the cache time again. We want to do this call
1482 * as little as possible...
1485 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1486 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1488 /* clear the msg pending record for this queue */
1490 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1492 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1493 /* log a message but continue on */
1495 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1499 release_print_db( pdb );
1504 /****************************************************************************
1505 Update the internal database from the system print queue for a queue.
1506 obtain a lock on the print queue before proceeding (needed when mutiple
1507 smbd processes maytry to update the lpq cache concurrently).
1508 ****************************************************************************/
1510 static void print_queue_update_with_lock( struct tevent_context *ev,
1511 struct messaging_context *msg_ctx,
1512 const char *sharename,
1513 struct printif *current_printif,
1514 char *lpq_command, char *lprm_command )
1517 struct tdb_print_db *pdb;
1519 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1520 pdb = get_print_db_byname(sharename);
1524 if ( !print_cache_expired(sharename, False) ) {
1525 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1526 release_print_db(pdb);
1531 * Check to see if someone else is doing this update.
1532 * This is essentially a mutex on the update.
1535 if (get_updating_pid(sharename) != -1) {
1536 release_print_db(pdb);
1540 /* Lock the queue for the database update */
1542 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1543 /* Only wait 10 seconds for this. */
1544 if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) == -1) {
1545 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1546 release_print_db(pdb);
1551 * Ensure that no one else got in here.
1552 * If the updating pid is still -1 then we are
1556 if (get_updating_pid(sharename) != -1) {
1558 * Someone else is doing the update, exit.
1560 tdb_unlock_bystring(pdb->tdb, keystr);
1561 release_print_db(pdb);
1566 * We're going to do the update ourselves.
1569 /* Tell others we're doing the update. */
1570 set_updating_pid(sharename, True);
1573 * Allow others to enter and notice we're doing
1577 tdb_unlock_bystring(pdb->tdb, keystr);
1579 /* do the main work now */
1581 print_queue_update_internal(ev, msg_ctx,
1582 sharename, current_printif,
1583 lpq_command, lprm_command);
1585 /* Delete our pid from the db. */
1586 set_updating_pid(sharename, False);
1587 release_print_db(pdb);
1590 /****************************************************************************
1591 this is the receive function of the background lpq updater
1592 ****************************************************************************/
1593 void print_queue_receive(struct messaging_context *msg,
1596 struct server_id server_id,
1600 char *lpqcommand = NULL, *lprmcommand = NULL;
1604 len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1611 SAFE_FREE(lpqcommand);
1612 SAFE_FREE(lprmcommand);
1613 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1617 print_queue_update_with_lock(server_event_context(), msg, sharename,
1618 get_printer_fns_from_type((enum printing_types)printing_type),
1619 lpqcommand, lprmcommand );
1621 SAFE_FREE(lpqcommand);
1622 SAFE_FREE(lprmcommand);
1626 static void printing_pause_fd_handler(struct tevent_context *ev,
1627 struct tevent_fd *fde,
1632 * If pause_pipe[1] is closed it means the parent smbd
1633 * and children exited or aborted.
1635 exit_server_cleanly(NULL);
1638 extern struct child_pid *children;
1639 extern int num_children;
1641 static void add_child_pid(pid_t pid)
1643 struct child_pid *child;
1645 child = SMB_MALLOC_P(struct child_pid);
1646 if (child == NULL) {
1647 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
1651 DLIST_ADD(children, child);
1655 static pid_t background_lpq_updater_pid = -1;
1657 /****************************************************************************
1658 main thread of the background lpq updater
1659 ****************************************************************************/
1660 void start_background_queue(struct tevent_context *ev,
1661 struct messaging_context *msg_ctx)
1663 /* Use local variables for this as we don't
1664 * need to save the parent side of this, just
1665 * ensure it closes when the process exits.
1669 DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
1671 if (pipe(pause_pipe) == -1) {
1672 DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
1676 background_lpq_updater_pid = sys_fork();
1678 if (background_lpq_updater_pid == -1) {
1679 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
1683 /* Track the printing pid along with other smbd children */
1684 add_child_pid(background_lpq_updater_pid);
1686 if(background_lpq_updater_pid == 0) {
1687 struct tevent_fd *fde;
1692 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
1694 close(pause_pipe[0]);
1697 status = reinit_after_fork(msg_ctx, ev, procid_self(), true);
1699 if (!NT_STATUS_IS_OK(status)) {
1700 DEBUG(0,("reinit_after_fork() failed\n"));
1701 smb_panic("reinit_after_fork() failed");
1704 smbd_setup_sig_term_handler();
1705 smbd_setup_sig_hup_handler(ev, msg_ctx);
1707 if (!serverid_register(procid_self(),
1708 FLAG_MSG_GENERAL|FLAG_MSG_SMBD
1709 |FLAG_MSG_PRINT_GENERAL)) {
1713 if (!locking_init()) {
1717 messaging_register(msg_ctx, NULL, MSG_PRINTER_UPDATE,
1718 print_queue_receive);
1720 fde = tevent_add_fd(ev, ev, pause_pipe[1], TEVENT_FD_READ,
1721 printing_pause_fd_handler,
1724 DEBUG(0,("tevent_add_fd() failed for pause_pipe\n"));
1725 smb_panic("tevent_add_fd() failed for pause_pipe");
1728 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
1729 ret = tevent_loop_wait(ev);
1730 /* should not be reached */
1731 DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
1732 ret, (ret == 0) ? "out of events" : strerror(errno)));
1736 close(pause_pipe[1]);
1739 /****************************************************************************
1740 update the internal database from the system print queue for a queue
1741 ****************************************************************************/
1743 static void print_queue_update(struct messaging_context *msg_ctx,
1744 int snum, bool force)
1748 char *lpqcommand = NULL;
1749 char *lprmcommand = NULL;
1750 uint8 *buffer = NULL;
1753 struct tdb_print_db *pdb;
1755 struct printif *current_printif;
1756 TALLOC_CTX *ctx = talloc_tos();
1758 fstrcpy( sharename, lp_const_servicename(snum));
1760 /* don't strip out characters like '$' from the printername */
1762 lpqcommand = talloc_string_sub2(ctx,
1763 lp_lpqcommand(snum),
1765 lp_printername(snum),
1766 false, false, false);
1770 lpqcommand = talloc_sub_advanced(ctx,
1771 lp_servicename(snum),
1772 current_user_info.unix_name,
1774 current_user.ut.gid,
1775 get_current_username(),
1776 current_user_info.domain,
1782 lprmcommand = talloc_string_sub2(ctx,
1783 lp_lprmcommand(snum),
1785 lp_printername(snum),
1786 false, false, false);
1790 lprmcommand = talloc_sub_advanced(ctx,
1791 lp_servicename(snum),
1792 current_user_info.unix_name,
1794 current_user.ut.gid,
1795 get_current_username(),
1796 current_user_info.domain,
1803 * Make sure that the background queue process exists.
1804 * Otherwise just do the update ourselves
1807 if ( force || background_lpq_updater_pid == -1 ) {
1808 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1809 current_printif = get_printer_fns( snum );
1810 print_queue_update_with_lock(server_event_context(), msg_ctx,
1811 sharename, current_printif,
1812 lpqcommand, lprmcommand);
1817 type = lp_printing(snum);
1819 /* get the length */
1821 len = tdb_pack( NULL, 0, "fdPP",
1827 buffer = SMB_XMALLOC_ARRAY( uint8, len );
1829 /* now pack the buffer */
1830 newlen = tdb_pack( buffer, len, "fdPP",
1836 SMB_ASSERT( newlen == len );
1838 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1839 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1840 sharename, type, lpqcommand, lprmcommand ));
1842 /* here we set a msg pending record for other smbd processes
1843 to throttle the number of duplicate print_queue_update msgs
1846 pdb = get_print_db_byname(sharename);
1852 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1854 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1855 /* log a message but continue on */
1857 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1861 release_print_db( pdb );
1863 /* finally send the message */
1865 messaging_send_buf(msg_ctx, pid_to_procid(background_lpq_updater_pid),
1866 MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1868 SAFE_FREE( buffer );
1873 /****************************************************************************
1874 Create/Update an entry in the print tdb that will allow us to send notify
1875 updates only to interested smbd's.
1876 ****************************************************************************/
1878 bool print_notify_register_pid(int snum)
1881 struct tdb_print_db *pdb = NULL;
1882 TDB_CONTEXT *tdb = NULL;
1883 const char *printername;
1884 uint32 mypid = (uint32)sys_getpid();
1888 /* if (snum == -1), then the change notify request was
1889 on a print server handle and we need to register on
1894 int num_services = lp_numservices();
1897 for ( idx=0; idx<num_services; idx++ ) {
1898 if (lp_snum_ok(idx) && lp_print_ok(idx) )
1899 print_notify_register_pid(idx);
1904 else /* register for a specific printer */
1906 printername = lp_const_servicename(snum);
1907 pdb = get_print_db_byname(printername);
1913 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1914 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1917 release_print_db(pdb);
1921 data = get_printer_notify_pid_list( tdb, printername, True );
1923 /* Add ourselves and increase the refcount. */
1925 for (i = 0; i < data.dsize; i += 8) {
1926 if (IVAL(data.dptr,i) == mypid) {
1927 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1928 SIVAL(data.dptr, i+4, new_refcount);
1933 if (i == data.dsize) {
1934 /* We weren't in the list. Realloc. */
1935 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1937 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1942 SIVAL(data.dptr,data.dsize - 8,mypid);
1943 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1946 /* Store back the record. */
1947 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1948 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1949 list for printer %s\n", printername));
1957 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1959 release_print_db(pdb);
1960 SAFE_FREE(data.dptr);
1964 /****************************************************************************
1965 Update an entry in the print tdb that will allow us to send notify
1966 updates only to interested smbd's.
1967 ****************************************************************************/
1969 bool print_notify_deregister_pid(int snum)
1972 struct tdb_print_db *pdb = NULL;
1973 TDB_CONTEXT *tdb = NULL;
1974 const char *printername;
1975 uint32 mypid = (uint32)sys_getpid();
1979 /* if ( snum == -1 ), we are deregister a print server handle
1980 which means to deregister on all print queues */
1984 int num_services = lp_numservices();
1987 for ( idx=0; idx<num_services; idx++ ) {
1988 if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1989 print_notify_deregister_pid(idx);
1994 else /* deregister a specific printer */
1996 printername = lp_const_servicename(snum);
1997 pdb = get_print_db_byname(printername);
2003 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
2004 DEBUG(0,("print_notify_register_pid: Failed to lock \
2005 printer %s database\n", printername));
2007 release_print_db(pdb);
2011 data = get_printer_notify_pid_list( tdb, printername, True );
2013 /* Reduce refcount. Remove ourselves if zero. */
2015 for (i = 0; i < data.dsize; ) {
2016 if (IVAL(data.dptr,i) == mypid) {
2017 uint32 refcount = IVAL(data.dptr, i+4);
2021 if (refcount == 0) {
2022 if (data.dsize - i > 8)
2023 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
2027 SIVAL(data.dptr, i+4, refcount);
2033 if (data.dsize == 0)
2034 SAFE_FREE(data.dptr);
2036 /* Store back the record. */
2037 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
2038 DEBUG(0,("print_notify_register_pid: Failed to update pid \
2039 list for printer %s\n", printername));
2047 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
2049 release_print_db(pdb);
2050 SAFE_FREE(data.dptr);
2054 /****************************************************************************
2055 Check if a jobid is valid. It is valid if it exists in the database.
2056 ****************************************************************************/
2058 bool print_job_exists(const char* sharename, uint32 jobid)
2060 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2066 ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
2067 release_print_db(pdb);
2071 /****************************************************************************
2072 Give the filename used for a jobid.
2073 Only valid for the process doing the spooling and when the job
2074 has not been spooled.
2075 ****************************************************************************/
2077 char *print_job_fname(const char* sharename, uint32 jobid)
2079 struct printjob *pjob = print_job_find(NULL, sharename, jobid);
2080 if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
2082 return pjob->filename;
2086 /****************************************************************************
2087 Give the filename used for a jobid.
2088 Only valid for the process doing the spooling and when the job
2089 has not been spooled.
2090 ****************************************************************************/
2092 struct spoolss_DeviceMode *print_job_devmode(TALLOC_CTX *mem_ctx,
2093 const char *sharename,
2096 struct printjob *pjob = print_job_find(mem_ctx, sharename, jobid);
2101 return pjob->devmode;
2104 /****************************************************************************
2105 Set the name of a job. Only possible for owner.
2106 ****************************************************************************/
2108 bool print_job_set_name(struct tevent_context *ev,
2109 struct messaging_context *msg_ctx,
2110 const char *sharename, uint32 jobid, const char *name)
2112 struct printjob *pjob;
2114 TALLOC_CTX *tmp_ctx = talloc_new(ev);
2115 if (tmp_ctx == NULL) {
2119 pjob = print_job_find(tmp_ctx, sharename, jobid);
2120 if (!pjob || pjob->pid != sys_getpid()) {
2125 fstrcpy(pjob->jobname, name);
2126 ret = pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2128 talloc_free(tmp_ctx);
2132 /****************************************************************************
2133 Get the name of a job. Only possible for owner.
2134 ****************************************************************************/
2136 bool print_job_get_name(TALLOC_CTX *mem_ctx, const char *sharename, uint32_t jobid, char **name)
2138 struct printjob *pjob;
2140 pjob = print_job_find(mem_ctx, sharename, jobid);
2141 if (!pjob || pjob->pid != sys_getpid()) {
2145 return pjob->jobname;
2149 /***************************************************************************
2150 Remove a jobid from the 'jobs added' list.
2151 ***************************************************************************/
2153 static bool remove_from_jobs_added(const char* sharename, uint32 jobid)
2155 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2157 size_t job_count, i;
2159 bool gotlock = False;
2167 key = string_tdb_data("INFO/jobs_added");
2169 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
2174 data = tdb_fetch(pdb->tdb, key);
2176 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
2179 job_count = data.dsize / 4;
2180 for (i = 0; i < job_count; i++) {
2183 ch_jobid = IVAL(data.dptr, i*4);
2184 if (ch_jobid == jobid) {
2185 if (i < job_count -1 )
2186 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
2188 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
2198 tdb_chainunlock(pdb->tdb, key);
2199 SAFE_FREE(data.dptr);
2200 release_print_db(pdb);
2202 DEBUG(10,("remove_from_jobs_added: removed jobid %u\n", (unsigned int)jobid ));
2204 DEBUG(10,("remove_from_jobs_added: Failed to remove jobid %u\n", (unsigned int)jobid ));
2208 /****************************************************************************
2209 Delete a print job - don't update queue.
2210 ****************************************************************************/
2212 static bool print_job_delete1(struct tevent_context *ev,
2213 struct messaging_context *msg_ctx,
2214 int snum, uint32 jobid)
2216 const char* sharename = lp_const_servicename(snum);
2217 struct printjob *pjob;
2219 struct printif *current_printif = get_printer_fns( snum );
2221 TALLOC_CTX *tmp_ctx = talloc_new(ev);
2222 if (tmp_ctx == NULL) {
2226 pjob = print_job_find(tmp_ctx, sharename, jobid);
2233 * If already deleting just return.
2236 if (pjob->status == LPQ_DELETING) {
2241 /* Hrm - we need to be able to cope with deleting a job before it
2242 has reached the spooler. Just mark it as LPQ_DELETING and
2243 let the print_queue_update() code rmeove the record */
2246 if (pjob->sysjob == -1) {
2247 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
2250 /* Set the tdb entry to be deleting. */
2252 pjob->status = LPQ_DELETING;
2253 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2255 if (pjob->spooled && pjob->sysjob != -1)
2257 result = (*(current_printif->job_delete))(
2258 lp_printername(snum),
2259 lp_lprmcommand(snum),
2262 /* Delete the tdb entry if the delete succeeded or the job hasn't
2266 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2273 pjob_delete(ev, msg_ctx, sharename, jobid);
2274 /* Ensure we keep a rough count of the number of total jobs... */
2275 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
2276 release_print_db(pdb);
2280 remove_from_jobs_added( sharename, jobid );
2282 ret = (result == 0);
2284 talloc_free(tmp_ctx);
2288 /****************************************************************************
2289 Return true if the current user owns the print job.
2290 ****************************************************************************/
2292 static bool is_owner(const struct auth_serversupplied_info *server_info,
2293 const char *servicename,
2296 struct printjob *pjob;
2298 TALLOC_CTX *tmp_ctx = talloc_new(server_info);
2299 if (tmp_ctx == NULL) {
2303 pjob = print_job_find(tmp_ctx, servicename, jobid);
2304 if (!pjob || !server_info) {
2309 ret = strequal(pjob->user, server_info->sanitized_username);
2311 talloc_free(tmp_ctx);
2315 /****************************************************************************
2317 ****************************************************************************/
2319 WERROR print_job_delete(const struct auth_serversupplied_info *server_info,
2320 struct messaging_context *msg_ctx,
2321 int snum, uint32_t jobid)
2323 const char* sharename = lp_const_servicename(snum);
2324 struct printjob *pjob;
2327 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2328 if (tmp_ctx == NULL) {
2329 return WERR_NOT_ENOUGH_MEMORY;
2332 owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2334 /* Check access against security descriptor or whether the user
2338 !print_access_check(server_info, msg_ctx, snum,
2339 JOB_ACCESS_ADMINISTER)) {
2340 DEBUG(3, ("delete denied by security descriptor\n"));
2342 /* BEGIN_ADMIN_LOG */
2343 sys_adminlog( LOG_ERR,
2344 "Permission denied-- user not allowed to delete, \
2345 pause, or resume print job. User name: %s. Printer name: %s.",
2346 uidtoname(server_info->utok.uid),
2347 lp_printername(snum) );
2350 werr = WERR_ACCESS_DENIED;
2355 * get the spooled filename of the print job
2356 * if this works, then the file has not been spooled
2357 * to the underlying print system. Just delete the
2358 * spool file & return.
2361 pjob = print_job_find(tmp_ctx, sharename, jobid);
2362 if (!pjob || pjob->spooled || pjob->pid != getpid()) {
2363 DEBUG(10, ("Skipping spool file removal for job %u\n", jobid));
2365 DEBUG(10, ("Removing spool file [%s]\n", pjob->filename));
2366 if (unlink(pjob->filename) == -1) {
2367 werr = map_werror_from_unix(errno);
2372 if (!print_job_delete1(server_event_context(), msg_ctx, snum, jobid)) {
2373 werr = WERR_ACCESS_DENIED;
2377 /* force update the database and say the delete failed if the
2380 print_queue_update(msg_ctx, snum, True);
2382 pjob = print_job_find(tmp_ctx, sharename, jobid);
2383 if (pjob && (pjob->status != LPQ_DELETING)) {
2384 werr = WERR_ACCESS_DENIED;
2387 werr = WERR_PRINTER_HAS_JOBS_QUEUED;
2390 talloc_free(tmp_ctx);
2394 /****************************************************************************
2396 ****************************************************************************/
2398 WERROR print_job_pause(const struct auth_serversupplied_info *server_info,
2399 struct messaging_context *msg_ctx,
2400 int snum, uint32 jobid)
2402 const char* sharename = lp_const_servicename(snum);
2403 struct printjob *pjob;
2405 struct printif *current_printif = get_printer_fns( snum );
2407 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2408 if (tmp_ctx == NULL) {
2409 return WERR_NOT_ENOUGH_MEMORY;
2412 pjob = print_job_find(tmp_ctx, sharename, jobid);
2413 if (!pjob || !server_info) {
2414 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2415 (unsigned int)jobid ));
2416 werr = WERR_INVALID_PARAM;
2420 if (!pjob->spooled || pjob->sysjob == -1) {
2421 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2422 (int)pjob->sysjob, (unsigned int)jobid ));
2423 werr = WERR_INVALID_PARAM;
2427 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2428 !print_access_check(server_info, msg_ctx, snum,
2429 JOB_ACCESS_ADMINISTER)) {
2430 DEBUG(3, ("pause denied by security descriptor\n"));
2432 /* BEGIN_ADMIN_LOG */
2433 sys_adminlog( LOG_ERR,
2434 "Permission denied-- user not allowed to delete, \
2435 pause, or resume print job. User name: %s. Printer name: %s.",
2436 uidtoname(server_info->utok.uid),
2437 lp_printername(snum) );
2440 werr = WERR_ACCESS_DENIED;
2444 /* need to pause the spooled entry */
2445 ret = (*(current_printif->job_pause))(snum, pjob);
2448 werr = WERR_INVALID_PARAM;
2452 /* force update the database */
2453 print_cache_flush(lp_const_servicename(snum));
2455 /* Send a printer notify message */
2457 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2460 /* how do we tell if this succeeded? */
2463 talloc_free(tmp_ctx);
2467 /****************************************************************************
2469 ****************************************************************************/
2471 WERROR print_job_resume(const struct auth_serversupplied_info *server_info,
2472 struct messaging_context *msg_ctx,
2473 int snum, uint32 jobid)
2475 const char *sharename = lp_const_servicename(snum);
2476 struct printjob *pjob;
2478 struct printif *current_printif = get_printer_fns( snum );
2480 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2481 if (tmp_ctx == NULL)
2482 return WERR_NOT_ENOUGH_MEMORY;
2484 pjob = print_job_find(tmp_ctx, sharename, jobid);
2485 if (!pjob || !server_info) {
2486 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2487 (unsigned int)jobid ));
2488 werr = WERR_INVALID_PARAM;
2492 if (!pjob->spooled || pjob->sysjob == -1) {
2493 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2494 (int)pjob->sysjob, (unsigned int)jobid ));
2495 werr = WERR_INVALID_PARAM;
2499 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2500 !print_access_check(server_info, msg_ctx, snum,
2501 JOB_ACCESS_ADMINISTER)) {
2502 DEBUG(3, ("resume denied by security descriptor\n"));
2504 /* BEGIN_ADMIN_LOG */
2505 sys_adminlog( LOG_ERR,
2506 "Permission denied-- user not allowed to delete, \
2507 pause, or resume print job. User name: %s. Printer name: %s.",
2508 uidtoname(server_info->utok.uid),
2509 lp_printername(snum) );
2511 werr = WERR_ACCESS_DENIED;
2515 ret = (*(current_printif->job_resume))(snum, pjob);
2518 werr = WERR_INVALID_PARAM;
2522 /* force update the database */
2523 print_cache_flush(lp_const_servicename(snum));
2525 /* Send a printer notify message */
2527 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2532 talloc_free(tmp_ctx);
2536 /****************************************************************************
2537 Write to a print file.
2538 ****************************************************************************/
2540 ssize_t print_job_write(struct tevent_context *ev,
2541 struct messaging_context *msg_ctx,
2542 int snum, uint32 jobid, const char *buf, size_t size)
2544 const char* sharename = lp_const_servicename(snum);
2545 ssize_t return_code;
2546 struct printjob *pjob;
2547 TALLOC_CTX *tmp_ctx = talloc_new(ev);
2548 if (tmp_ctx == NULL) {
2552 pjob = print_job_find(tmp_ctx, sharename, jobid);
2558 /* don't allow another process to get this info - it is meaningless */
2559 if (pjob->pid != sys_getpid()) {
2564 /* if SMBD is spooling this can't be allowed */
2565 if (pjob->status == PJOB_SMBD_SPOOLING) {
2570 return_code = write_data(pjob->fd, buf, size);
2571 if (return_code > 0) {
2573 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2576 talloc_free(tmp_ctx);
2580 /****************************************************************************
2581 Get the queue status - do not update if db is out of date.
2582 ****************************************************************************/
2584 static int get_queue_status(const char* sharename, print_status_struct *status)
2588 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2592 ZERO_STRUCTP(status);
2599 fstr_sprintf(keystr, "STATUS/%s", sharename);
2600 data = tdb_fetch(pdb->tdb, string_tdb_data(keystr));
2602 if (data.dsize == sizeof(print_status_struct))
2603 /* this memcpy is ok since the status struct was
2604 not packed before storing it in the tdb */
2605 memcpy(status, data.dptr, sizeof(print_status_struct));
2606 SAFE_FREE(data.dptr);
2609 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2610 release_print_db(pdb);
2611 return (len == -1 ? 0 : len);
2614 /****************************************************************************
2615 Determine the number of jobs in a queue.
2616 ****************************************************************************/
2618 int print_queue_length(struct messaging_context *msg_ctx, int snum,
2619 print_status_struct *pstatus)
2621 const char* sharename = lp_const_servicename( snum );
2622 print_status_struct status;
2625 ZERO_STRUCT( status );
2627 /* make sure the database is up to date */
2628 if (print_cache_expired(lp_const_servicename(snum), True))
2629 print_queue_update(msg_ctx, snum, False);
2631 /* also fetch the queue status */
2632 memset(&status, 0, sizeof(status));
2633 len = get_queue_status(sharename, &status);
2641 /***************************************************************************
2642 Allocate a jobid. Hold the lock for as short a time as possible.
2643 ***************************************************************************/
2645 static WERROR allocate_print_jobid(struct tdb_print_db *pdb, int snum,
2646 const char *sharename, uint32 *pjobid)
2650 enum TDB_ERROR terr;
2653 *pjobid = (uint32)-1;
2655 for (i = 0; i < 3; i++) {
2656 /* Lock the database - only wait 20 seconds. */
2657 ret = tdb_lock_bystring_with_timeout(pdb->tdb,
2658 "INFO/nextjob", 20);
2660 DEBUG(0, ("allocate_print_jobid: "
2661 "Failed to lock printing database %s\n",
2663 terr = tdb_error(pdb->tdb);
2664 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2667 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2668 terr = tdb_error(pdb->tdb);
2669 if (terr != TDB_ERR_NOEXIST) {
2670 DEBUG(0, ("allocate_print_jobid: "
2671 "Failed to fetch INFO/nextjob "
2672 "for print queue %s\n", sharename));
2673 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2674 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2676 DEBUG(10, ("allocate_print_jobid: "
2677 "No existing jobid in %s\n", sharename));
2681 DEBUG(10, ("allocate_print_jobid: "
2682 "Read jobid %u from %s\n", jobid, sharename));
2684 jobid = NEXT_JOBID(jobid);
2686 ret = tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid);
2688 terr = tdb_error(pdb->tdb);
2689 DEBUG(3, ("allocate_print_jobid: "
2690 "Failed to store INFO/nextjob.\n"));
2691 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2692 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2695 /* We've finished with the INFO/nextjob lock. */
2696 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2698 if (!print_job_exists(sharename, jobid)) {
2701 DEBUG(10, ("allocate_print_jobid: "
2702 "Found jobid %u in %s\n", jobid, sharename));
2706 DEBUG(0, ("allocate_print_jobid: "
2707 "Failed to allocate a print job for queue %s\n",
2709 /* Probably full... */
2710 return WERR_NO_SPOOL_SPACE;
2713 /* Store a dummy placeholder. */
2719 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2720 TDB_INSERT) == -1) {
2721 DEBUG(3, ("allocate_print_jobid: "
2722 "jobid (%d) failed to store placeholder.\n",
2724 terr = tdb_error(pdb->tdb);
2725 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2733 /***************************************************************************
2734 Append a jobid to the 'jobs added' list.
2735 ***************************************************************************/
2737 static bool add_to_jobs_added(struct tdb_print_db *pdb, uint32 jobid)
2742 SIVAL(&store_jobid, 0, jobid);
2743 data.dptr = (uint8 *)&store_jobid;
2746 DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
2748 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_added"),
2753 /***************************************************************************
2754 Do all checks needed to determine if we can start a job.
2755 ***************************************************************************/
2757 static WERROR print_job_checks(const struct auth_serversupplied_info *server_info,
2758 struct messaging_context *msg_ctx,
2759 int snum, int *njobs)
2761 const char *sharename = lp_const_servicename(snum);
2762 uint64_t dspace, dsize;
2766 if (!print_access_check(server_info, msg_ctx, snum,
2767 PRINTER_ACCESS_USE)) {
2768 DEBUG(3, ("print_job_checks: "
2769 "job start denied by security descriptor\n"));
2770 return WERR_ACCESS_DENIED;
2773 if (!print_time_access_check(server_info, msg_ctx, sharename)) {
2774 DEBUG(3, ("print_job_checks: "
2775 "job start denied by time check\n"));
2776 return WERR_ACCESS_DENIED;
2779 /* see if we have sufficient disk space */
2780 if (lp_minprintspace(snum)) {
2781 minspace = lp_minprintspace(snum);
2782 ret = sys_fsusage(lp_pathname(snum), &dspace, &dsize);
2783 if (ret == 0 && dspace < 2*minspace) {
2784 DEBUG(3, ("print_job_checks: "
2785 "disk space check failed.\n"));
2786 return WERR_NO_SPOOL_SPACE;
2790 /* for autoloaded printers, check that the printcap entry still exists */
2791 if (lp_autoloaded(snum) && !pcap_printername_ok(sharename)) {
2792 DEBUG(3, ("print_job_checks: printer name %s check failed.\n",
2794 return WERR_ACCESS_DENIED;
2797 /* Insure the maximum queue size is not violated */
2798 *njobs = print_queue_length(msg_ctx, snum, NULL);
2799 if (*njobs > lp_maxprintjobs(snum)) {
2800 DEBUG(3, ("print_job_checks: Queue %s number of jobs (%d) "
2801 "larger than max printjobs per queue (%d).\n",
2802 sharename, *njobs, lp_maxprintjobs(snum)));
2803 return WERR_NO_SPOOL_SPACE;
2809 /***************************************************************************
2811 ***************************************************************************/
2813 static WERROR print_job_spool_file(int snum, uint32_t jobid,
2814 const char *output_file,
2815 struct printjob *pjob)
2822 /* if this file is within the printer path, it means that smbd
2823 * is spooling it and will pass us control when it is finished.
2824 * Verify that the file name is ok, within path, and it is
2825 * already already there */
2827 path = lp_pathname(snum);
2829 if (strncmp(output_file, path, len) == 0 &&
2830 (output_file[len - 1] == '/' || output_file[len] == '/')) {
2832 /* verify path is not too long */
2833 if (strlen(output_file) >= sizeof(pjob->filename)) {
2834 return WERR_INVALID_NAME;
2837 /* verify that the file exists */
2838 if (sys_stat(output_file, &st, false) != 0) {
2839 return WERR_INVALID_NAME;
2842 fstrcpy(pjob->filename, output_file);
2844 DEBUG(3, ("print_job_spool_file:"
2845 "External spooling activated"));
2847 /* we do not open the file until spooling is done */
2849 pjob->status = PJOB_SMBD_SPOOLING;
2855 slprintf(pjob->filename, sizeof(pjob->filename)-1,
2856 "%s/%s%.8u.XXXXXX", lp_pathname(snum),
2857 PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2858 pjob->fd = mkstemp(pjob->filename);
2860 if (pjob->fd == -1) {
2861 werr = map_werror_from_unix(errno);
2862 if (W_ERROR_EQUAL(werr, WERR_ACCESS_DENIED)) {
2863 /* Common setup error, force a report. */
2864 DEBUG(0, ("print_job_spool_file: "
2865 "insufficient permissions to open spool "
2866 "file %s.\n", pjob->filename));
2868 /* Normal case, report at level 3 and above. */
2869 DEBUG(3, ("print_job_spool_file: "
2870 "can't open spool file %s\n",
2879 /***************************************************************************
2880 Start spooling a job - return the jobid.
2881 ***************************************************************************/
2883 WERROR print_job_start(const struct auth_serversupplied_info *server_info,
2884 struct messaging_context *msg_ctx,
2885 const char *clientmachine,
2886 int snum, const char *docname, const char *filename,
2887 struct spoolss_DeviceMode *devmode, uint32_t *_jobid)
2891 struct printjob pjob;
2892 const char *sharename = lp_const_servicename(snum);
2893 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2898 return WERR_INTERNAL_DB_CORRUPTION;
2901 path = lp_pathname(snum);
2903 werr = print_job_checks(server_info, msg_ctx, snum, &njobs);
2904 if (!W_ERROR_IS_OK(werr)) {
2905 release_print_db(pdb);
2909 DEBUG(10, ("print_job_start: "
2910 "Queue %s number of jobs (%d), max printjobs = %d\n",
2911 sharename, njobs, lp_maxprintjobs(snum)));
2913 werr = allocate_print_jobid(pdb, snum, sharename, &jobid);
2914 if (!W_ERROR_IS_OK(werr)) {
2918 /* create the database entry */
2922 pjob.pid = sys_getpid();
2926 pjob.starttime = time(NULL);
2927 pjob.status = LPQ_SPOOLING;
2929 pjob.spooled = False;
2931 pjob.devmode = devmode;
2933 fstrcpy(pjob.jobname, docname);
2935 fstrcpy(pjob.clientmachine, clientmachine);
2937 fstrcpy(pjob.user, lp_printjob_username(snum));
2938 standard_sub_advanced(sharename, server_info->sanitized_username,
2939 path, server_info->utok.gid,
2940 server_info->sanitized_username,
2941 server_info->info3->base.domain.string,
2942 pjob.user, sizeof(pjob.user)-1);
2943 /* ensure NULL termination */
2944 pjob.user[sizeof(pjob.user)-1] = '\0';
2946 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2948 /* we have a job entry - now create the spool file */
2949 werr = print_job_spool_file(snum, jobid, filename, &pjob);
2950 if (!W_ERROR_IS_OK(werr)) {
2954 pjob_store(server_event_context(), msg_ctx, sharename, jobid, &pjob);
2956 /* Update the 'jobs added' entry used by print_queue_status. */
2957 add_to_jobs_added(pdb, jobid);
2959 /* Ensure we keep a rough count of the number of total jobs... */
2960 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2962 release_print_db(pdb);
2969 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2972 release_print_db(pdb);
2974 DEBUG(3, ("print_job_start: returning fail. "
2975 "Error = %s\n", win_errstr(werr)));
2979 /****************************************************************************
2980 Update the number of pages spooled to jobid
2981 ****************************************************************************/
2983 void print_job_endpage(struct messaging_context *msg_ctx,
2984 int snum, uint32 jobid)
2986 const char* sharename = lp_const_servicename(snum);
2987 struct printjob *pjob;
2988 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2989 if (tmp_ctx == NULL) {
2993 pjob = print_job_find(tmp_ctx, sharename, jobid);
2997 /* don't allow another process to get this info - it is meaningless */
2998 if (pjob->pid != sys_getpid()) {
3003 pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
3005 talloc_free(tmp_ctx);
3008 /****************************************************************************
3009 Print a file - called on closing the file. This spools the job.
3010 If normal close is false then we're tearing down the jobs - treat as an
3012 ****************************************************************************/
3014 NTSTATUS print_job_end(struct messaging_context *msg_ctx, int snum,
3015 uint32 jobid, enum file_close_type close_type)
3017 const char* sharename = lp_const_servicename(snum);
3018 struct printjob *pjob;
3020 SMB_STRUCT_STAT sbuf;
3021 struct printif *current_printif = get_printer_fns(snum);
3022 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
3023 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
3024 if (tmp_ctx == NULL) {
3025 return NT_STATUS_NO_MEMORY;
3028 pjob = print_job_find(tmp_ctx, sharename, jobid);
3030 status = NT_STATUS_PRINT_CANCELLED;
3034 if (pjob->spooled || pjob->pid != sys_getpid()) {
3035 status = NT_STATUS_ACCESS_DENIED;
3039 if (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) {
3040 if (pjob->status == PJOB_SMBD_SPOOLING) {
3041 /* take over the file now, smbd is done */
3042 if (sys_stat(pjob->filename, &sbuf, false) != 0) {
3043 status = map_nt_error_from_unix(errno);
3044 DEBUG(3, ("print_job_end: "
3045 "stat file failed for jobid %d\n",
3050 pjob->status = LPQ_SPOOLING;
3054 if ((sys_fstat(pjob->fd, &sbuf, false) != 0)) {
3055 status = map_nt_error_from_unix(errno);
3057 DEBUG(3, ("print_job_end: "
3058 "stat file failed for jobid %d\n",
3066 pjob->size = sbuf.st_ex_size;
3070 * Not a normal close, something has gone wrong. Cleanup.
3072 if (pjob->fd != -1) {
3078 /* Technically, this is not quite right. If the printer has a separator
3079 * page turned on, the NT spooler prints the separator page even if the
3080 * print job is 0 bytes. 010215 JRR */
3081 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
3082 /* don't bother spooling empty files or something being deleted. */
3083 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
3084 pjob->filename, pjob->size ? "deleted" : "zero length" ));
3085 unlink(pjob->filename);
3086 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
3087 return NT_STATUS_OK;
3090 ret = (*(current_printif->job_submit))(snum, pjob);
3093 status = NT_STATUS_PRINT_CANCELLED;
3097 /* The print job has been successfully handed over to the back-end */
3099 pjob->spooled = True;
3100 pjob->status = LPQ_QUEUED;
3101 pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
3103 /* make sure the database is up to date */
3104 if (print_cache_expired(lp_const_servicename(snum), True))
3105 print_queue_update(msg_ctx, snum, False);
3107 return NT_STATUS_OK;
3111 /* The print job was not successfully started. Cleanup */
3112 /* Still need to add proper error return propagation! 010122:JRR */
3114 unlink(pjob->filename);
3115 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
3117 talloc_free(tmp_ctx);
3121 /****************************************************************************
3122 Get a snapshot of jobs in the system without traversing.
3123 ****************************************************************************/
3125 static bool get_stored_queue_info(struct messaging_context *msg_ctx,
3126 struct tdb_print_db *pdb, int snum,
3127 int *pcount, print_queue_struct **ppqueue)
3129 TDB_DATA data, cgdata, jcdata;
3130 print_queue_struct *queue = NULL;
3132 uint32 extra_count = 0;
3133 uint32_t changed_count = 0;
3134 int total_count = 0;
3137 int max_reported_jobs = lp_max_reported_jobs(snum);
3139 const char* sharename = lp_servicename(snum);
3140 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
3141 if (tmp_ctx == NULL) {
3145 /* make sure the database is up to date */
3146 if (print_cache_expired(lp_const_servicename(snum), True))
3147 print_queue_update(msg_ctx, snum, False);
3153 ZERO_STRUCT(cgdata);
3155 /* Get the stored queue data. */
3156 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
3158 if (data.dptr && data.dsize >= sizeof(qcount))
3159 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
3161 /* Get the added jobs list. */
3162 cgdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_added"));
3163 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
3164 extra_count = cgdata.dsize/4;
3166 /* Get the changed jobs list. */
3167 jcdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
3168 if (jcdata.dptr != NULL && (jcdata.dsize % 4 == 0))
3169 changed_count = jcdata.dsize / 4;
3171 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
3173 /* Allocate the queue size. */
3174 if (qcount == 0 && extra_count == 0)
3177 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
3180 /* Retrieve the linearised queue data. */
3182 for( i = 0; i < qcount; i++) {
3183 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
3184 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
3193 queue[i].sysjob = qjob;
3194 queue[i].size = qsize;
3195 queue[i].page_count = qpage_count;
3196 queue[i].status = qstatus;
3197 queue[i].priority = qpriority;
3198 queue[i].time = qtime;
3201 total_count = qcount;
3203 /* Add new jobids to the queue. */
3204 for( i = 0; i < extra_count; i++) {
3206 struct printjob *pjob;
3208 jobid = IVAL(cgdata.dptr, i*4);
3209 DEBUG(5,("get_stored_queue_info: added job = %u\n", (unsigned int)jobid));
3210 pjob = print_job_find(tmp_ctx, lp_const_servicename(snum), jobid);
3212 DEBUG(5,("get_stored_queue_info: failed to find added job = %u\n", (unsigned int)jobid));
3213 remove_from_jobs_added(sharename, jobid);
3217 queue[total_count].sysjob = jobid;
3218 queue[total_count].size = pjob->size;
3219 queue[total_count].page_count = pjob->page_count;
3220 queue[total_count].status = pjob->status;
3221 queue[total_count].priority = 1;
3222 queue[total_count].time = pjob->starttime;
3223 fstrcpy(queue[total_count].fs_user, pjob->user);
3224 fstrcpy(queue[total_count].fs_file, pjob->jobname);
3229 /* Update the changed jobids. */
3230 for (i = 0; i < changed_count; i++) {
3231 uint32_t jobid = IVAL(jcdata.dptr, i * 4);
3235 for (j = 0; j < total_count; j++) {
3236 if (queue[j].sysjob == jobid) {
3243 struct printjob *pjob;
3245 DEBUG(5,("get_stored_queue_info: changed job: %u\n",
3246 (unsigned int) jobid));
3248 pjob = print_job_find(tmp_ctx, sharename, jobid);
3250 DEBUG(5,("get_stored_queue_info: failed to find "
3251 "changed job = %u\n",
3252 (unsigned int) jobid));
3253 remove_from_jobs_changed(sharename, jobid);
3257 queue[j].sysjob = jobid;
3258 queue[j].size = pjob->size;
3259 queue[j].page_count = pjob->page_count;
3260 queue[j].status = pjob->status;
3261 queue[j].priority = 1;
3262 queue[j].time = pjob->starttime;
3263 fstrcpy(queue[j].fs_user, pjob->user);
3264 fstrcpy(queue[j].fs_file, pjob->jobname);
3267 DEBUG(5,("get_stored_queue_info: updated queue[%u], jobid: %u, jobname: %s\n",
3268 (unsigned int) j, (unsigned int) jobid, pjob->jobname));
3271 remove_from_jobs_changed(sharename, jobid);
3274 /* Sort the queue by submission time otherwise they are displayed
3277 TYPESAFE_QSORT(queue, total_count, printjob_comp);
3279 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
3281 if (max_reported_jobs && total_count > max_reported_jobs)
3282 total_count = max_reported_jobs;
3285 *pcount = total_count;
3291 SAFE_FREE(data.dptr);
3292 SAFE_FREE(cgdata.dptr);
3293 talloc_free(tmp_ctx);
3297 /****************************************************************************
3298 Get a printer queue listing.
3299 set queue = NULL and status = NULL if you just want to update the cache
3300 ****************************************************************************/
3302 int print_queue_status(struct messaging_context *msg_ctx, int snum,
3303 print_queue_struct **ppqueue,
3304 print_status_struct *status)
3308 const char *sharename;
3309 struct tdb_print_db *pdb;
3312 /* make sure the database is up to date */
3314 if (print_cache_expired(lp_const_servicename(snum), True))
3315 print_queue_update(msg_ctx, snum, False);
3317 /* return if we are done */
3318 if ( !ppqueue || !status )
3322 sharename = lp_const_servicename(snum);
3323 pdb = get_print_db_byname(sharename);
3329 * Fetch the queue status. We must do this first, as there may
3330 * be no jobs in the queue.
3333 ZERO_STRUCTP(status);
3334 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
3335 key = string_tdb_data(keystr);
3337 data = tdb_fetch(pdb->tdb, key);
3339 if (data.dsize == sizeof(*status)) {
3340 /* this memcpy is ok since the status struct was
3341 not packed before storing it in the tdb */
3342 memcpy(status, data.dptr, sizeof(*status));
3344 SAFE_FREE(data.dptr);
3348 * Now, fetch the print queue information. We first count the number
3349 * of entries, and then only retrieve the queue if necessary.
3352 if (!get_stored_queue_info(msg_ctx, pdb, snum, &count, ppqueue)) {
3353 release_print_db(pdb);
3357 release_print_db(pdb);
3361 /****************************************************************************
3363 ****************************************************************************/
3365 WERROR print_queue_pause(const struct auth_serversupplied_info *server_info,
3366 struct messaging_context *msg_ctx, int snum)
3369 struct printif *current_printif = get_printer_fns( snum );
3371 if (!print_access_check(server_info, msg_ctx, snum,
3372 PRINTER_ACCESS_ADMINISTER)) {
3373 return WERR_ACCESS_DENIED;
3379 ret = (*(current_printif->queue_pause))(snum);
3384 return WERR_INVALID_PARAM;
3387 /* force update the database */
3388 print_cache_flush(lp_const_servicename(snum));
3390 /* Send a printer notify message */
3392 notify_printer_status(server_event_context(), msg_ctx, snum,
3393 PRINTER_STATUS_PAUSED);
3398 /****************************************************************************
3400 ****************************************************************************/
3402 WERROR print_queue_resume(const struct auth_serversupplied_info *server_info,
3403 struct messaging_context *msg_ctx, int snum)
3406 struct printif *current_printif = get_printer_fns( snum );
3408 if (!print_access_check(server_info, msg_ctx, snum,
3409 PRINTER_ACCESS_ADMINISTER)) {
3410 return WERR_ACCESS_DENIED;
3415 ret = (*(current_printif->queue_resume))(snum);
3420 return WERR_INVALID_PARAM;
3423 /* make sure the database is up to date */
3424 if (print_cache_expired(lp_const_servicename(snum), True))
3425 print_queue_update(msg_ctx, snum, True);
3427 /* Send a printer notify message */
3429 notify_printer_status(server_event_context(), msg_ctx, snum,
3435 /****************************************************************************
3436 Purge a queue - implemented by deleting all jobs that we can delete.
3437 ****************************************************************************/
3439 WERROR print_queue_purge(const struct auth_serversupplied_info *server_info,
3440 struct messaging_context *msg_ctx, int snum)
3442 print_queue_struct *queue;
3443 print_status_struct status;
3447 /* Force and update so the count is accurate (i.e. not a cached count) */
3448 print_queue_update(msg_ctx, snum, True);
3450 can_job_admin = print_access_check(server_info,
3453 JOB_ACCESS_ADMINISTER);
3454 njobs = print_queue_status(msg_ctx, snum, &queue, &status);
3456 if ( can_job_admin )
3459 for (i=0;i<njobs;i++) {
3460 bool owner = is_owner(server_info, lp_const_servicename(snum),
3463 if (owner || can_job_admin) {
3464 print_job_delete1(server_event_context(), msg_ctx,
3465 snum, queue[i].sysjob);
3469 if ( can_job_admin )
3472 /* update the cache */
3473 print_queue_update(msg_ctx, snum, True);