testprogs: Set functional domain level to 2003.
[Samba.git] / source3 / printing / printing.c
blob5d053cc71ea8fce991fe92a868680c3e12499493
1 /*
2 Unix SMB/Netbios implementation.
3 Version 3.0
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/>.
22 #include "includes.h"
23 #include "system/syslog.h"
24 #include "system/filesys.h"
25 #include "printing.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"
33 #include "serverid.h"
34 #include "smbd/smbd.h"
35 #include "auth.h"
36 #include "messages.h"
37 #include "util_tdb.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 {
63 fstring sharename;
64 uint32 jobid;
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)
74 uint16 rap_jobid;
75 TDB_DATA data, key;
76 struct rap_jobid_key jinfo;
77 uint8 buf[2];
79 DEBUG(10,("pjobid_to_rap: called.\n"));
81 if (!rap_tdb) {
82 /* Create the in-memory tdb. */
83 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
84 if (!rap_tdb)
85 return 0;
88 ZERO_STRUCT( jinfo );
89 fstrcpy( jinfo.sharename, sharename );
90 jinfo.jobid = jobid;
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);
97 SAFE_FREE(data.dptr);
98 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
99 (unsigned int)jobid, (unsigned int)rap_jobid));
100 return rap_jobid;
102 SAFE_FREE(data.dptr);
103 /* Not found - create and store mapping. */
104 rap_jobid = ++next_rap_jobid;
105 if (rap_jobid == 0)
106 rap_jobid = ++next_rap_jobid;
107 SSVAL(buf,0,rap_jobid);
108 data.dptr = buf;
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));
115 return rap_jobid;
118 bool rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
120 TDB_DATA data, key;
121 uint8 buf[2];
123 DEBUG(10,("rap_to_pjobid called.\n"));
125 if (!rap_tdb)
126 return False;
128 SSVAL(buf,0,rap_jobid);
129 key.dptr = buf;
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);
142 return True;
145 DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
146 (unsigned int)rap_jobid));
147 SAFE_FREE(data.dptr);
148 return False;
151 void rap_jobid_delete(const char* sharename, uint32 jobid)
153 TDB_DATA key, data;
154 uint16 rap_jobid;
155 struct rap_jobid_key jinfo;
156 uint8 buf[2];
158 DEBUG(10,("rap_jobid_delete: called.\n"));
160 if (!rap_tdb)
161 return;
163 ZERO_STRUCT( jinfo );
164 fstrcpy( jinfo.sharename, sharename );
165 jinfo.jobid = jobid;
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);
174 return;
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);
183 data.dptr = buf;
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();
199 int snum;
200 bool ok;
201 char *print_cache_path;
203 if (!printer_list_parent_init()) {
204 return false;
207 print_cache_path = cache_path("printing");
208 if (print_cache_path == NULL) {
209 return false;
211 ok = directory_create_or_exist(print_cache_path, 0755);
212 TALLOC_FREE(print_cache_path);
213 if (!ok) {
214 return false;
217 print_cache_path = cache_path("printing.tdb");
218 if (print_cache_path == NULL) {
219 return false;
221 unlink(print_cache_path);
222 TALLOC_FREE(print_cache_path);
224 /* handle a Samba upgrade */
226 for (snum = 0; snum < services; snum++) {
227 struct tdb_print_db *pdb;
228 if (!lp_printable(snum))
229 continue;
231 pdb = get_print_db_byname(lp_const_servicename(snum));
232 if (!pdb)
233 continue;
234 if (tdb_lock_bystring(pdb->tdb, sversion) != 0) {
235 DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
236 release_print_db(pdb);
237 return False;
239 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
240 tdb_wipe_all(pdb->tdb);
241 tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
243 tdb_unlock_bystring(pdb->tdb, sversion);
244 release_print_db(pdb);
247 close_all_print_db(); /* Don't leave any open. */
249 /* do NT print initialization... */
250 return nt_printing_init(msg_ctx);
253 /****************************************************************************
254 Shut down printing backend. Called once at shutdown to close the tdb.
255 ****************************************************************************/
257 void printing_end(void)
259 close_all_print_db(); /* Don't leave any open. */
262 /****************************************************************************
263 Retrieve the set of printing functions for a given service. This allows
264 us to set the printer function table based on the value of the 'printing'
265 service parameter.
267 Use the generic interface as the default and only use cups interface only
268 when asked for (and only when supported)
269 ****************************************************************************/
271 static struct printif *get_printer_fns_from_type( enum printing_types type )
273 struct printif *printer_fns = &generic_printif;
275 #ifdef HAVE_CUPS
276 if ( type == PRINT_CUPS ) {
277 printer_fns = &cups_printif;
279 #endif /* HAVE_CUPS */
281 #ifdef HAVE_IPRINT
282 if ( type == PRINT_IPRINT ) {
283 printer_fns = &iprint_printif;
285 #endif /* HAVE_IPRINT */
287 printer_fns->type = type;
289 return printer_fns;
292 static struct printif *get_printer_fns( int snum )
294 return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
298 /****************************************************************************
299 Useful function to generate a tdb key.
300 ****************************************************************************/
302 static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
304 TDB_DATA ret;
306 SIVAL(tmp, 0, jobid);
307 ret.dptr = (uint8 *)tmp;
308 ret.dsize = sizeof(*tmp);
309 return ret;
312 /****************************************************************************
313 Pack the devicemode to store it in a tdb.
314 ****************************************************************************/
315 static int pack_devicemode(struct spoolss_DeviceMode *devmode, uint8 *buf, int buflen)
317 enum ndr_err_code ndr_err;
318 DATA_BLOB blob;
319 int len = 0;
321 if (devmode) {
322 ndr_err = ndr_push_struct_blob(&blob, talloc_tos(),
323 devmode,
324 (ndr_push_flags_fn_t)
325 ndr_push_spoolss_DeviceMode);
326 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
327 DEBUG(10, ("pack_devicemode: "
328 "error encoding spoolss_DeviceMode\n"));
329 goto done;
331 } else {
332 ZERO_STRUCT(blob);
335 len = tdb_pack(buf, buflen, "B", blob.length, blob.data);
337 if (devmode) {
338 DEBUG(8, ("Packed devicemode [%s]\n", devmode->formname));
341 done:
342 return len;
345 /****************************************************************************
346 Unpack the devicemode to store it in a tdb.
347 ****************************************************************************/
348 static int unpack_devicemode(TALLOC_CTX *mem_ctx,
349 const uint8 *buf, int buflen,
350 struct spoolss_DeviceMode **devmode)
352 struct spoolss_DeviceMode *dm;
353 enum ndr_err_code ndr_err;
354 char *data = NULL;
355 int data_len = 0;
356 DATA_BLOB blob;
357 int len = 0;
359 *devmode = NULL;
361 len = tdb_unpack(buf, buflen, "B", &data_len, &data);
362 if (!data) {
363 return len;
366 dm = talloc_zero(mem_ctx, struct spoolss_DeviceMode);
367 if (!dm) {
368 goto done;
371 blob = data_blob_const(data, data_len);
373 ndr_err = ndr_pull_struct_blob(&blob, dm, dm,
374 (ndr_pull_flags_fn_t)ndr_pull_spoolss_DeviceMode);
375 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
376 DEBUG(10, ("unpack_devicemode: "
377 "error parsing spoolss_DeviceMode\n"));
378 goto done;
381 DEBUG(8, ("Unpacked devicemode [%s](%s)\n",
382 dm->devicename, dm->formname));
383 if (dm->driverextra_data.data) {
384 DEBUG(8, ("with a private section of %d bytes\n",
385 dm->__driverextra_length));
388 *devmode = dm;
390 done:
391 SAFE_FREE(data);
392 return len;
395 /***********************************************************************
396 unpack a pjob from a tdb buffer
397 ***********************************************************************/
399 static int unpack_pjob(TALLOC_CTX *mem_ctx, uint8 *buf, int buflen,
400 struct printjob *pjob)
402 int len = 0;
403 int used;
404 uint32 pjpid, pjjobid, pjsysjob, pjfd, pjstarttime, pjstatus;
405 uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
407 if (!buf || !pjob) {
408 return -1;
411 len += tdb_unpack(buf+len, buflen-len, "ddddddddddfffff",
412 &pjpid,
413 &pjjobid,
414 &pjsysjob,
415 &pjfd,
416 &pjstarttime,
417 &pjstatus,
418 &pjsize,
419 &pjpage_count,
420 &pjspooled,
421 &pjsmbjob,
422 pjob->filename,
423 pjob->jobname,
424 pjob->user,
425 pjob->clientmachine,
426 pjob->queuename);
428 if (len == -1) {
429 return -1;
432 used = unpack_devicemode(mem_ctx, buf+len, buflen-len, &pjob->devmode);
433 if (used == -1) {
434 return -1;
437 len += used;
439 pjob->pid = pjpid;
440 pjob->jobid = pjjobid;
441 pjob->sysjob = pjsysjob;
442 pjob->fd = pjfd;
443 pjob->starttime = pjstarttime;
444 pjob->status = pjstatus;
445 pjob->size = pjsize;
446 pjob->page_count = pjpage_count;
447 pjob->spooled = pjspooled;
448 pjob->smbjob = pjsmbjob;
450 return len;
454 /****************************************************************************
455 Useful function to find a print job in the database.
456 ****************************************************************************/
458 static struct printjob *print_job_find(TALLOC_CTX *mem_ctx,
459 const char *sharename,
460 uint32 jobid)
462 struct printjob *pjob;
463 uint32_t tmp;
464 TDB_DATA ret;
465 struct tdb_print_db *pdb = get_print_db_byname(sharename);
467 DEBUG(10,("print_job_find: looking up job %u for share %s\n",
468 (unsigned int)jobid, sharename ));
470 if (!pdb) {
471 return NULL;
474 ret = tdb_fetch_compat(pdb->tdb, print_key(jobid, &tmp));
475 release_print_db(pdb);
477 if (!ret.dptr) {
478 DEBUG(10, ("print_job_find: failed to find jobid %u.\n",
479 jobid));
480 return NULL;
483 pjob = talloc_zero(mem_ctx, struct printjob);
484 if (pjob == NULL) {
485 goto err_out;
488 if (unpack_pjob(mem_ctx, ret.dptr, ret.dsize, pjob) == -1) {
489 DEBUG(10, ("failed to unpack jobid %u.\n", jobid));
490 talloc_free(pjob);
491 pjob = NULL;
492 goto err_out;
495 DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
496 pjob->sysjob, jobid));
497 SMB_ASSERT(pjob->jobid == jobid);
499 err_out:
500 SAFE_FREE(ret.dptr);
501 return pjob;
504 struct job_traverse_state {
505 int sysjob;
506 uint32_t jobid;
509 /* find spoolss jobid based on sysjob */
510 static int sysjob_to_jobid_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
511 TDB_DATA data, void *private_data)
513 struct printjob *pjob;
514 struct job_traverse_state *state =
515 (struct job_traverse_state *)private_data;
517 if (!data.dptr || data.dsize == 0)
518 return 0;
520 pjob = (struct printjob *)data.dptr;
521 if (key.dsize != sizeof(uint32))
522 return 0;
524 if (state->sysjob == pjob->sysjob) {
525 state->jobid = pjob->jobid;
526 return 1;
529 return 0;
532 uint32 sysjob_to_jobid_pdb(struct tdb_print_db *pdb, int sysjob)
534 struct job_traverse_state state;
536 state.sysjob = sysjob;
537 state.jobid = (uint32_t)-1;
539 tdb_traverse(pdb->tdb, sysjob_to_jobid_traverse_fn, &state);
541 return state.jobid;
544 /****************************************************************************
545 This is a *horribly expensive call as we have to iterate through all the
546 current printer tdb's. Don't do this often ! JRA.
547 ****************************************************************************/
549 uint32 sysjob_to_jobid(int unix_jobid)
551 int services = lp_numservices();
552 int snum;
553 struct job_traverse_state state;
555 state.sysjob = unix_jobid;
556 state.jobid = (uint32_t)-1;
558 for (snum = 0; snum < services; snum++) {
559 struct tdb_print_db *pdb;
560 if (!lp_printable(snum))
561 continue;
562 pdb = get_print_db_byname(lp_const_servicename(snum));
563 if (!pdb) {
564 continue;
566 tdb_traverse(pdb->tdb, sysjob_to_jobid_traverse_fn, &state);
567 release_print_db(pdb);
568 if (state.jobid != (uint32_t)-1)
569 return state.jobid;
571 return (uint32)-1;
574 /* find sysjob based on spoolss jobid */
575 static int jobid_to_sysjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
576 TDB_DATA data, void *private_data)
578 struct printjob *pjob;
579 struct job_traverse_state *state =
580 (struct job_traverse_state *)private_data;
582 if (!data.dptr || data.dsize == 0)
583 return 0;
585 pjob = (struct printjob *)data.dptr;
586 if (key.dsize != sizeof(uint32_t))
587 return 0;
589 if (state->jobid == pjob->jobid) {
590 state->sysjob = pjob->sysjob;
591 return 1;
594 return 0;
597 int jobid_to_sysjob_pdb(struct tdb_print_db *pdb, uint32_t jobid)
599 struct job_traverse_state state;
601 state.sysjob = -1;
602 state.jobid = jobid;
604 tdb_traverse(pdb->tdb, jobid_to_sysjob_traverse_fn, &state);
606 return state.sysjob;
609 /****************************************************************************
610 Send notifications based on what has changed after a pjob_store.
611 ****************************************************************************/
613 static const struct {
614 uint32_t lpq_status;
615 uint32_t spoolss_status;
616 } lpq_to_spoolss_status_map[] = {
617 { LPQ_QUEUED, JOB_STATUS_QUEUED },
618 { LPQ_PAUSED, JOB_STATUS_PAUSED },
619 { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
620 { LPQ_PRINTING, JOB_STATUS_PRINTING },
621 { LPQ_DELETING, JOB_STATUS_DELETING },
622 { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
623 { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
624 { LPQ_PRINTED, JOB_STATUS_PRINTED },
625 { LPQ_DELETED, JOB_STATUS_DELETED },
626 { LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
627 { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
628 { (uint32_t)-1, 0 }
631 /* Convert a lpq status value stored in printing.tdb into the
632 appropriate win32 API constant. */
634 static uint32 map_to_spoolss_status(uint32 lpq_status)
636 int i = 0;
638 while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
639 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
640 return lpq_to_spoolss_status_map[i].spoolss_status;
641 i++;
644 return 0;
647 /***************************************************************************
648 Append a jobid to the 'jobs changed' list.
649 ***************************************************************************/
651 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32_t jobid)
653 TDB_DATA data;
654 uint32_t store_jobid;
656 SIVAL(&store_jobid, 0, jobid);
657 data.dptr = (uint8 *) &store_jobid;
658 data.dsize = 4;
660 DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
662 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
663 data) == 0);
666 /***************************************************************************
667 Remove a jobid from the 'jobs changed' list.
668 ***************************************************************************/
670 static bool remove_from_jobs_changed(const char* sharename, uint32_t jobid)
672 struct tdb_print_db *pdb = get_print_db_byname(sharename);
673 TDB_DATA data, key;
674 size_t job_count, i;
675 bool ret = False;
676 bool gotlock = False;
678 if (!pdb) {
679 return False;
682 ZERO_STRUCT(data);
684 key = string_tdb_data("INFO/jobs_changed");
686 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) != 0)
687 goto out;
689 gotlock = True;
691 data = tdb_fetch_compat(pdb->tdb, key);
693 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
694 goto out;
696 job_count = data.dsize / 4;
697 for (i = 0; i < job_count; i++) {
698 uint32 ch_jobid;
700 ch_jobid = IVAL(data.dptr, i*4);
701 if (ch_jobid == jobid) {
702 if (i < job_count -1 )
703 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
704 data.dsize -= 4;
705 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) != 0)
706 goto out;
707 break;
711 ret = True;
712 out:
714 if (gotlock)
715 tdb_chainunlock(pdb->tdb, key);
716 SAFE_FREE(data.dptr);
717 release_print_db(pdb);
718 if (ret)
719 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
720 else
721 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
722 return ret;
725 static void pjob_store_notify(struct tevent_context *ev,
726 struct messaging_context *msg_ctx,
727 const char* sharename, uint32 jobid,
728 struct printjob *old_data,
729 struct printjob *new_data,
730 bool *pchanged)
732 bool new_job = false;
733 bool changed = false;
735 if (old_data == NULL) {
736 new_job = true;
739 /* ACHTUNG! Due to a bug in Samba's spoolss parsing of the
740 NOTIFY_INFO_DATA buffer, we *have* to send the job submission
741 time first or else we'll end up with potential alignment
742 errors. I don't think the systemtime should be spooled as
743 a string, but this gets us around that error.
744 --jerry (i'll feel dirty for this) */
746 if (new_job) {
747 notify_job_submitted(ev, msg_ctx,
748 sharename, jobid, new_data->starttime);
749 notify_job_username(ev, msg_ctx,
750 sharename, jobid, new_data->user);
751 notify_job_name(ev, msg_ctx,
752 sharename, jobid, new_data->jobname);
753 notify_job_status(ev, msg_ctx,
754 sharename, jobid, map_to_spoolss_status(new_data->status));
755 notify_job_total_bytes(ev, msg_ctx,
756 sharename, jobid, new_data->size);
757 notify_job_total_pages(ev, msg_ctx,
758 sharename, jobid, new_data->page_count);
759 } else {
760 if (!strequal(old_data->jobname, new_data->jobname)) {
761 notify_job_name(ev, msg_ctx, sharename,
762 jobid, new_data->jobname);
763 changed = true;
766 if (old_data->status != new_data->status) {
767 notify_job_status(ev, msg_ctx,
768 sharename, jobid,
769 map_to_spoolss_status(new_data->status));
772 if (old_data->size != new_data->size) {
773 notify_job_total_bytes(ev, msg_ctx,
774 sharename, jobid, new_data->size);
777 if (old_data->page_count != new_data->page_count) {
778 notify_job_total_pages(ev, msg_ctx,
779 sharename, jobid,
780 new_data->page_count);
784 *pchanged = changed;
787 /****************************************************************************
788 Store a job structure back to the database.
789 ****************************************************************************/
791 static bool pjob_store(struct tevent_context *ev,
792 struct messaging_context *msg_ctx,
793 const char* sharename, uint32 jobid,
794 struct printjob *pjob)
796 uint32_t tmp;
797 TDB_DATA old_data, new_data;
798 bool ret = False;
799 struct tdb_print_db *pdb = get_print_db_byname(sharename);
800 uint8 *buf = NULL;
801 int len, newlen, buflen;
804 if (!pdb)
805 return False;
807 /* Get old data */
809 old_data = tdb_fetch_compat(pdb->tdb, print_key(jobid, &tmp));
811 /* Doh! Now we have to pack/unpack data since the NT_DEVICEMODE was added */
813 newlen = 0;
815 do {
816 len = 0;
817 buflen = newlen;
818 len += tdb_pack(buf+len, buflen-len, "ddddddddddfffff",
819 (uint32)pjob->pid,
820 (uint32)pjob->jobid,
821 (uint32)pjob->sysjob,
822 (uint32)pjob->fd,
823 (uint32)pjob->starttime,
824 (uint32)pjob->status,
825 (uint32)pjob->size,
826 (uint32)pjob->page_count,
827 (uint32)pjob->spooled,
828 (uint32)pjob->smbjob,
829 pjob->filename,
830 pjob->jobname,
831 pjob->user,
832 pjob->clientmachine,
833 pjob->queuename);
835 len += pack_devicemode(pjob->devmode, buf+len, buflen-len);
837 if (buflen != len) {
838 buf = (uint8 *)SMB_REALLOC(buf, len);
839 if (!buf) {
840 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
841 goto done;
843 newlen = len;
845 } while ( buflen != len );
848 /* Store new data */
850 new_data.dptr = buf;
851 new_data.dsize = len;
852 ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
853 TDB_REPLACE) == 0);
855 /* Send notify updates for what has changed */
857 if (ret) {
858 bool changed = false;
859 struct printjob old_pjob;
861 if (old_data.dsize) {
862 TALLOC_CTX *tmp_ctx = talloc_new(ev);
863 if (tmp_ctx == NULL)
864 goto done;
866 len = unpack_pjob(tmp_ctx, old_data.dptr,
867 old_data.dsize, &old_pjob);
868 if (len != -1 ) {
869 pjob_store_notify(ev,
870 msg_ctx,
871 sharename, jobid, &old_pjob,
872 pjob,
873 &changed);
874 if (changed) {
875 add_to_jobs_changed(pdb, jobid);
878 talloc_free(tmp_ctx);
880 } else {
881 /* new job */
882 pjob_store_notify(ev, msg_ctx,
883 sharename, jobid, NULL, pjob,
884 &changed);
888 done:
889 release_print_db(pdb);
890 SAFE_FREE( old_data.dptr );
891 SAFE_FREE( buf );
893 return ret;
896 /****************************************************************************
897 Remove a job structure from the database.
898 ****************************************************************************/
900 static void pjob_delete(struct tevent_context *ev,
901 struct messaging_context *msg_ctx,
902 const char* sharename, uint32 jobid)
904 uint32_t tmp;
905 struct printjob *pjob;
906 uint32 job_status = 0;
907 struct tdb_print_db *pdb;
908 TALLOC_CTX *tmp_ctx = talloc_new(ev);
909 if (tmp_ctx == NULL) {
910 return;
913 pdb = get_print_db_byname(sharename);
914 if (!pdb) {
915 goto err_out;
918 pjob = print_job_find(tmp_ctx, sharename, jobid);
919 if (!pjob) {
920 DEBUG(5, ("we were asked to delete nonexistent job %u\n",
921 jobid));
922 goto err_release;
925 /* We must cycle through JOB_STATUS_DELETING and
926 JOB_STATUS_DELETED for the port monitor to delete the job
927 properly. */
929 job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
930 notify_job_status(ev, msg_ctx, sharename, jobid, job_status);
932 /* Remove from printing.tdb */
934 tdb_delete(pdb->tdb, print_key(jobid, &tmp));
935 remove_from_jobs_added(sharename, jobid);
936 rap_jobid_delete(sharename, jobid);
937 err_release:
938 release_print_db(pdb);
939 err_out:
940 talloc_free(tmp_ctx);
943 /****************************************************************************
944 List a unix job in the print database.
945 ****************************************************************************/
947 static void print_unix_job(struct tevent_context *ev,
948 struct messaging_context *msg_ctx,
949 const char *sharename, print_queue_struct *q,
950 uint32 jobid)
952 struct printjob pj, *old_pj;
953 TALLOC_CTX *tmp_ctx = talloc_new(ev);
954 if (tmp_ctx == NULL) {
955 return;
958 if (jobid == (uint32)-1) {
959 jobid = q->sysjob + UNIX_JOB_START;
962 /* Preserve the timestamp on an existing unix print job */
964 old_pj = print_job_find(tmp_ctx, sharename, jobid);
966 ZERO_STRUCT(pj);
968 pj.pid = (pid_t)-1;
969 pj.jobid = jobid;
970 pj.sysjob = q->sysjob;
971 pj.fd = -1;
972 pj.starttime = old_pj ? old_pj->starttime : q->time;
973 pj.status = q->status;
974 pj.size = q->size;
975 pj.spooled = True;
976 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
977 if (jobid < UNIX_JOB_START) {
978 pj.smbjob = True;
979 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
980 } else {
981 pj.smbjob = False;
982 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
984 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
985 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
987 pjob_store(ev, msg_ctx, sharename, jobid, &pj);
988 talloc_free(tmp_ctx);
992 struct traverse_struct {
993 print_queue_struct *queue;
994 int qcount, snum, maxcount, total_jobs;
995 const char *sharename;
996 time_t lpq_time;
997 const char *lprm_command;
998 struct printif *print_if;
999 struct tevent_context *ev;
1000 struct messaging_context *msg_ctx;
1001 TALLOC_CTX *mem_ctx;
1004 /****************************************************************************
1005 Utility fn to delete any jobs that are no longer active.
1006 ****************************************************************************/
1008 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1010 struct traverse_struct *ts = (struct traverse_struct *)state;
1011 struct printjob pjob;
1012 uint32 jobid;
1013 int i = 0;
1015 if ( key.dsize != sizeof(jobid) )
1016 return 0;
1018 if (unpack_pjob(ts->mem_ctx, data.dptr, data.dsize, &pjob) == -1)
1019 return 0;
1020 talloc_free(pjob.devmode);
1021 jobid = pjob.jobid;
1023 if (!pjob.smbjob) {
1024 /* remove a unix job if it isn't in the system queue any more */
1025 for (i=0;i<ts->qcount;i++) {
1026 if (ts->queue[i].sysjob == pjob.sysjob) {
1027 break;
1030 if (i == ts->qcount) {
1031 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
1032 (unsigned int)jobid ));
1033 pjob_delete(ts->ev, ts->msg_ctx,
1034 ts->sharename, jobid);
1035 return 0;
1038 /* need to continue the the bottom of the function to
1039 save the correct attributes */
1042 /* maybe it hasn't been spooled yet */
1043 if (!pjob.spooled) {
1044 /* if a job is not spooled and the process doesn't
1045 exist then kill it. This cleans up after smbd
1046 deaths */
1047 if (!process_exists_by_pid(pjob.pid)) {
1048 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
1049 (unsigned int)jobid, (unsigned int)pjob.pid ));
1050 pjob_delete(ts->ev, ts->msg_ctx,
1051 ts->sharename, jobid);
1052 } else
1053 ts->total_jobs++;
1054 return 0;
1057 /* this check only makes sense for jobs submitted from Windows clients */
1059 if (pjob.smbjob) {
1060 for (i=0;i<ts->qcount;i++) {
1061 if ( pjob.status == LPQ_DELETED )
1062 continue;
1064 if (ts->queue[i].sysjob == pjob.sysjob) {
1066 /* try to clean up any jobs that need to be deleted */
1068 if ( pjob.status == LPQ_DELETING ) {
1069 int result;
1071 result = (*(ts->print_if->job_delete))(
1072 ts->sharename, ts->lprm_command, &pjob );
1074 if ( result != 0 ) {
1075 /* if we can't delete, then reset the job status */
1076 pjob.status = LPQ_QUEUED;
1077 pjob_store(ts->ev, ts->msg_ctx,
1078 ts->sharename, jobid, &pjob);
1080 else {
1081 /* if we deleted the job, the remove the tdb record */
1082 pjob_delete(ts->ev,
1083 ts->msg_ctx,
1084 ts->sharename, jobid);
1085 pjob.status = LPQ_DELETED;
1090 break;
1095 /* The job isn't in the system queue - we have to assume it has
1096 completed, so delete the database entry. */
1098 if (i == ts->qcount) {
1100 /* A race can occur between the time a job is spooled and
1101 when it appears in the lpq output. This happens when
1102 the job is added to printing.tdb when another smbd
1103 running print_queue_update() has completed a lpq and
1104 is currently traversing the printing tdb and deleting jobs.
1105 Don't delete the job if it was submitted after the lpq_time. */
1107 if (pjob.starttime < ts->lpq_time) {
1108 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
1109 (unsigned int)jobid,
1110 (unsigned int)pjob.starttime,
1111 (unsigned int)ts->lpq_time ));
1112 pjob_delete(ts->ev, ts->msg_ctx,
1113 ts->sharename, jobid);
1114 } else
1115 ts->total_jobs++;
1116 return 0;
1119 /* Save the pjob attributes we will store. */
1120 ts->queue[i].sysjob = pjob.sysjob;
1121 ts->queue[i].size = pjob.size;
1122 ts->queue[i].page_count = pjob.page_count;
1123 ts->queue[i].status = pjob.status;
1124 ts->queue[i].priority = 1;
1125 ts->queue[i].time = pjob.starttime;
1126 fstrcpy(ts->queue[i].fs_user, pjob.user);
1127 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1129 ts->total_jobs++;
1131 return 0;
1134 /****************************************************************************
1135 Check if the print queue has been updated recently enough.
1136 ****************************************************************************/
1138 static void print_cache_flush(const char *sharename)
1140 fstring key;
1141 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1143 if (!pdb)
1144 return;
1145 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
1146 tdb_store_int32(pdb->tdb, key, -1);
1147 release_print_db(pdb);
1150 /****************************************************************************
1151 Check if someone already thinks they are doing the update.
1152 ****************************************************************************/
1154 static pid_t get_updating_pid(const char *sharename)
1156 fstring keystr;
1157 TDB_DATA data, key;
1158 pid_t updating_pid;
1159 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1161 if (!pdb)
1162 return (pid_t)-1;
1163 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1164 key = string_tdb_data(keystr);
1166 data = tdb_fetch_compat(pdb->tdb, key);
1167 release_print_db(pdb);
1168 if (!data.dptr || data.dsize != sizeof(pid_t)) {
1169 SAFE_FREE(data.dptr);
1170 return (pid_t)-1;
1173 updating_pid = IVAL(data.dptr, 0);
1174 SAFE_FREE(data.dptr);
1176 if (process_exists_by_pid(updating_pid))
1177 return updating_pid;
1179 return (pid_t)-1;
1182 /****************************************************************************
1183 Set the fact that we're doing the update, or have finished doing the update
1184 in the tdb.
1185 ****************************************************************************/
1187 static void set_updating_pid(const fstring sharename, bool updating)
1189 fstring keystr;
1190 TDB_DATA key;
1191 TDB_DATA data;
1192 pid_t updating_pid = getpid();
1193 uint8 buffer[4];
1195 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1197 if (!pdb)
1198 return;
1200 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1201 key = string_tdb_data(keystr);
1203 DEBUG(5, ("set_updating_pid: %supdating lpq cache for print share %s\n",
1204 updating ? "" : "not ",
1205 sharename ));
1207 if ( !updating ) {
1208 tdb_delete(pdb->tdb, key);
1209 release_print_db(pdb);
1210 return;
1213 SIVAL( buffer, 0, updating_pid);
1214 data.dptr = buffer;
1215 data.dsize = 4; /* we always assume this is a 4 byte value */
1217 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1218 release_print_db(pdb);
1221 /****************************************************************************
1222 Sort print jobs by submittal time.
1223 ****************************************************************************/
1225 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1227 /* Silly cases */
1229 if (!j1 && !j2)
1230 return 0;
1231 if (!j1)
1232 return -1;
1233 if (!j2)
1234 return 1;
1236 /* Sort on job start time */
1238 if (j1->time == j2->time)
1239 return 0;
1240 return (j1->time > j2->time) ? 1 : -1;
1243 /****************************************************************************
1244 Store the sorted queue representation for later portmon retrieval.
1245 Skip deleted jobs
1246 ****************************************************************************/
1248 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
1250 TDB_DATA data;
1251 int max_reported_jobs = lp_max_reported_print_jobs(pts->snum);
1252 print_queue_struct *queue = pts->queue;
1253 size_t len;
1254 size_t i;
1255 unsigned int qcount;
1257 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
1258 pts->qcount = max_reported_jobs;
1259 qcount = 0;
1261 /* Work out the size. */
1262 data.dsize = 0;
1263 data.dsize += tdb_pack(NULL, 0, "d", qcount);
1265 for (i = 0; i < pts->qcount; i++) {
1266 if ( queue[i].status == LPQ_DELETED )
1267 continue;
1269 qcount++;
1270 data.dsize += tdb_pack(NULL, 0, "ddddddff",
1271 (uint32)queue[i].sysjob,
1272 (uint32)queue[i].size,
1273 (uint32)queue[i].page_count,
1274 (uint32)queue[i].status,
1275 (uint32)queue[i].priority,
1276 (uint32)queue[i].time,
1277 queue[i].fs_user,
1278 queue[i].fs_file);
1281 if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
1282 return;
1284 len = 0;
1285 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
1286 for (i = 0; i < pts->qcount; i++) {
1287 if ( queue[i].status == LPQ_DELETED )
1288 continue;
1290 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
1291 (uint32)queue[i].sysjob,
1292 (uint32)queue[i].size,
1293 (uint32)queue[i].page_count,
1294 (uint32)queue[i].status,
1295 (uint32)queue[i].priority,
1296 (uint32)queue[i].time,
1297 queue[i].fs_user,
1298 queue[i].fs_file);
1301 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
1302 TDB_REPLACE);
1303 SAFE_FREE(data.dptr);
1304 return;
1307 static TDB_DATA get_jobs_added_data(struct tdb_print_db *pdb)
1309 TDB_DATA data;
1311 ZERO_STRUCT(data);
1313 data = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_added"));
1314 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1315 SAFE_FREE(data.dptr);
1316 ZERO_STRUCT(data);
1319 return data;
1322 static void check_job_added(const char *sharename, TDB_DATA data, uint32 jobid)
1324 unsigned int i;
1325 unsigned int job_count = data.dsize / 4;
1327 for (i = 0; i < job_count; i++) {
1328 uint32 ch_jobid;
1330 ch_jobid = IVAL(data.dptr, i*4);
1331 if (ch_jobid == jobid)
1332 remove_from_jobs_added(sharename, jobid);
1336 /****************************************************************************
1337 Check if the print queue has been updated recently enough.
1338 ****************************************************************************/
1340 static bool print_cache_expired(const char *sharename, bool check_pending)
1342 fstring key;
1343 time_t last_qscan_time, time_now = time(NULL);
1344 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1345 bool result = False;
1347 if (!pdb)
1348 return False;
1350 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1351 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1354 * Invalidate the queue for 3 reasons.
1355 * (1). last queue scan time == -1.
1356 * (2). Current time - last queue scan time > allowed cache time.
1357 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1358 * This last test picks up machines for which the clock has been moved
1359 * forward, an lpq scan done and then the clock moved back. Otherwise
1360 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1363 if (last_qscan_time == ((time_t)-1)
1364 || (time_now - last_qscan_time) >= lp_lpq_cache_time()
1365 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1367 uint32 u;
1368 time_t msg_pending_time;
1370 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1371 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1372 sharename, (int)last_qscan_time, (int)time_now,
1373 (int)lp_lpq_cache_time() ));
1375 /* check if another smbd has already sent a message to update the
1376 queue. Give the pending message one minute to clear and
1377 then send another message anyways. Make sure to check for
1378 clocks that have been run forward and then back again. */
1380 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1382 if ( check_pending
1383 && tdb_fetch_uint32( pdb->tdb, key, &u )
1384 && (msg_pending_time=u) > 0
1385 && msg_pending_time <= time_now
1386 && (time_now - msg_pending_time) < 60 )
1388 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1389 sharename));
1390 goto done;
1393 result = True;
1396 done:
1397 release_print_db(pdb);
1398 return result;
1401 /****************************************************************************
1402 main work for updating the lpq cache for a printer queue
1403 ****************************************************************************/
1405 static void print_queue_update_internal(struct tevent_context *ev,
1406 struct messaging_context *msg_ctx,
1407 const char *sharename,
1408 struct printif *current_printif,
1409 char *lpq_command, char *lprm_command)
1411 int i, qcount;
1412 print_queue_struct *queue = NULL;
1413 print_status_struct status;
1414 print_status_struct old_status;
1415 struct printjob *pjob;
1416 struct traverse_struct tstruct;
1417 TDB_DATA data, key;
1418 TDB_DATA jcdata;
1419 fstring keystr, cachestr;
1420 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1421 TALLOC_CTX *tmp_ctx = talloc_new(ev);
1423 if ((pdb == NULL) || (tmp_ctx == NULL)) {
1424 return;
1427 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1428 sharename, current_printif->type, lpq_command));
1431 * Update the cache time FIRST ! Stops others even
1432 * attempting to get the lock and doing this
1433 * if the lpq takes a long time.
1436 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1437 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1439 /* get the current queue using the appropriate interface */
1440 ZERO_STRUCT(status);
1442 qcount = (*(current_printif->queue_get))(sharename,
1443 current_printif->type,
1444 lpq_command, &queue, &status);
1446 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1447 qcount, (qcount != 1) ? "s" : "", sharename));
1449 /* Sort the queue by submission time otherwise they are displayed
1450 in hash order. */
1452 TYPESAFE_QSORT(queue, qcount, printjob_comp);
1455 any job in the internal database that is marked as spooled
1456 and doesn't exist in the system queue is considered finished
1457 and removed from the database
1459 any job in the system database but not in the internal database
1460 is added as a unix job
1462 fill in any system job numbers as we go
1464 jcdata = get_jobs_added_data(pdb);
1466 for (i=0; i<qcount; i++) {
1467 uint32 jobid = sysjob_to_jobid_pdb(pdb, queue[i].sysjob);
1468 if (jobid == (uint32)-1) {
1469 /* assume its a unix print job */
1470 print_unix_job(ev, msg_ctx,
1471 sharename, &queue[i], jobid);
1472 continue;
1475 /* we have an active SMB print job - update its status */
1476 pjob = print_job_find(tmp_ctx, sharename, jobid);
1477 if (!pjob) {
1478 /* err, somethings wrong. Probably smbd was restarted
1479 with jobs in the queue. All we can do is treat them
1480 like unix jobs. Pity. */
1481 DEBUG(1, ("queued print job %d not found in jobs list, "
1482 "assuming unix job\n", jobid));
1483 print_unix_job(ev, msg_ctx,
1484 sharename, &queue[i], jobid);
1485 continue;
1488 /* don't reset the status on jobs to be deleted */
1490 if ( pjob->status != LPQ_DELETING )
1491 pjob->status = queue[i].status;
1493 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
1495 check_job_added(sharename, jcdata, jobid);
1498 SAFE_FREE(jcdata.dptr);
1500 /* now delete any queued entries that don't appear in the
1501 system queue */
1502 tstruct.queue = queue;
1503 tstruct.qcount = qcount;
1504 tstruct.snum = -1;
1505 tstruct.total_jobs = 0;
1506 tstruct.lpq_time = time(NULL);
1507 tstruct.sharename = sharename;
1508 tstruct.lprm_command = lprm_command;
1509 tstruct.print_if = current_printif;
1510 tstruct.ev = ev;
1511 tstruct.msg_ctx = msg_ctx;
1512 tstruct.mem_ctx = tmp_ctx;
1514 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1516 /* Store the linearised queue, max jobs only. */
1517 store_queue_struct(pdb, &tstruct);
1519 SAFE_FREE(tstruct.queue);
1520 talloc_free(tmp_ctx);
1522 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1523 sharename, tstruct.total_jobs ));
1525 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1527 get_queue_status(sharename, &old_status);
1528 if (old_status.qcount != qcount)
1529 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1530 old_status.qcount, qcount, sharename));
1532 /* store the new queue status structure */
1533 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1534 key = string_tdb_data(keystr);
1536 status.qcount = qcount;
1537 data.dptr = (uint8 *)&status;
1538 data.dsize = sizeof(status);
1539 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1542 * Update the cache time again. We want to do this call
1543 * as little as possible...
1546 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1547 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1549 /* clear the msg pending record for this queue */
1551 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1553 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1554 /* log a message but continue on */
1556 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1557 sharename));
1560 release_print_db( pdb );
1562 return;
1565 /****************************************************************************
1566 Update the internal database from the system print queue for a queue.
1567 obtain a lock on the print queue before proceeding (needed when mutiple
1568 smbd processes maytry to update the lpq cache concurrently).
1569 ****************************************************************************/
1571 static void print_queue_update_with_lock( struct tevent_context *ev,
1572 struct messaging_context *msg_ctx,
1573 const char *sharename,
1574 struct printif *current_printif,
1575 char *lpq_command, char *lprm_command )
1577 fstring keystr;
1578 struct tdb_print_db *pdb;
1580 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1581 pdb = get_print_db_byname(sharename);
1582 if (!pdb)
1583 return;
1585 if ( !print_cache_expired(sharename, False) ) {
1586 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1587 release_print_db(pdb);
1588 return;
1592 * Check to see if someone else is doing this update.
1593 * This is essentially a mutex on the update.
1596 if (get_updating_pid(sharename) != -1) {
1597 release_print_db(pdb);
1598 return;
1601 /* Lock the queue for the database update */
1603 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1604 /* Only wait 10 seconds for this. */
1605 if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) != 0) {
1606 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1607 release_print_db(pdb);
1608 return;
1612 * Ensure that no one else got in here.
1613 * If the updating pid is still -1 then we are
1614 * the winner.
1617 if (get_updating_pid(sharename) != -1) {
1619 * Someone else is doing the update, exit.
1621 tdb_unlock_bystring(pdb->tdb, keystr);
1622 release_print_db(pdb);
1623 return;
1627 * We're going to do the update ourselves.
1630 /* Tell others we're doing the update. */
1631 set_updating_pid(sharename, True);
1634 * Allow others to enter and notice we're doing
1635 * the update.
1638 tdb_unlock_bystring(pdb->tdb, keystr);
1640 /* do the main work now */
1642 print_queue_update_internal(ev, msg_ctx,
1643 sharename, current_printif,
1644 lpq_command, lprm_command);
1646 /* Delete our pid from the db. */
1647 set_updating_pid(sharename, False);
1648 release_print_db(pdb);
1651 /****************************************************************************
1652 this is the receive function of the background lpq updater
1653 ****************************************************************************/
1654 void print_queue_receive(struct messaging_context *msg,
1655 void *private_data,
1656 uint32_t msg_type,
1657 struct server_id server_id,
1658 DATA_BLOB *data)
1660 fstring sharename;
1661 char *lpqcommand = NULL, *lprmcommand = NULL;
1662 int printing_type;
1663 size_t len;
1665 len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1666 sharename,
1667 &printing_type,
1668 &lpqcommand,
1669 &lprmcommand );
1671 if ( len == -1 ) {
1672 SAFE_FREE(lpqcommand);
1673 SAFE_FREE(lprmcommand);
1674 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1675 return;
1678 print_queue_update_with_lock(server_event_context(), msg, sharename,
1679 get_printer_fns_from_type((enum printing_types)printing_type),
1680 lpqcommand, lprmcommand );
1682 SAFE_FREE(lpqcommand);
1683 SAFE_FREE(lprmcommand);
1684 return;
1687 /****************************************************************************
1688 update the internal database from the system print queue for a queue
1689 ****************************************************************************/
1691 extern pid_t background_lpq_updater_pid;
1693 static void print_queue_update(struct messaging_context *msg_ctx,
1694 int snum, bool force)
1696 fstring key;
1697 fstring sharename;
1698 char *lpqcommand = NULL;
1699 char *lprmcommand = NULL;
1700 uint8 *buffer = NULL;
1701 size_t len = 0;
1702 size_t newlen;
1703 struct tdb_print_db *pdb;
1704 int type;
1705 struct printif *current_printif;
1706 TALLOC_CTX *ctx = talloc_tos();
1708 fstrcpy( sharename, lp_const_servicename(snum));
1710 /* don't strip out characters like '$' from the printername */
1712 lpqcommand = talloc_string_sub2(ctx,
1713 lp_lpq_command(talloc_tos(), snum),
1714 "%p",
1715 lp_printername(talloc_tos(), snum),
1716 false, false, false);
1717 if (!lpqcommand) {
1718 return;
1720 lpqcommand = talloc_sub_advanced(ctx,
1721 lp_servicename(talloc_tos(), snum),
1722 current_user_info.unix_name,
1724 current_user.ut.gid,
1725 get_current_username(),
1726 current_user_info.domain,
1727 lpqcommand);
1728 if (!lpqcommand) {
1729 return;
1732 lprmcommand = talloc_string_sub2(ctx,
1733 lp_lprm_command(talloc_tos(), snum),
1734 "%p",
1735 lp_printername(talloc_tos(), snum),
1736 false, false, false);
1737 if (!lprmcommand) {
1738 return;
1740 lprmcommand = talloc_sub_advanced(ctx,
1741 lp_servicename(talloc_tos(), snum),
1742 current_user_info.unix_name,
1744 current_user.ut.gid,
1745 get_current_username(),
1746 current_user_info.domain,
1747 lprmcommand);
1748 if (!lprmcommand) {
1749 return;
1753 * Make sure that the background queue process exists.
1754 * Otherwise just do the update ourselves
1757 if ( force || background_lpq_updater_pid == -1 ) {
1758 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1759 current_printif = get_printer_fns( snum );
1760 print_queue_update_with_lock(server_event_context(), msg_ctx,
1761 sharename, current_printif,
1762 lpqcommand, lprmcommand);
1764 return;
1767 type = lp_printing(snum);
1769 /* get the length */
1771 len = tdb_pack( NULL, 0, "fdPP",
1772 sharename,
1773 type,
1774 lpqcommand,
1775 lprmcommand );
1777 buffer = SMB_XMALLOC_ARRAY( uint8, len );
1779 /* now pack the buffer */
1780 newlen = tdb_pack( buffer, len, "fdPP",
1781 sharename,
1782 type,
1783 lpqcommand,
1784 lprmcommand );
1786 SMB_ASSERT( newlen == len );
1788 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1789 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1790 sharename, type, lpqcommand, lprmcommand ));
1792 /* here we set a msg pending record for other smbd processes
1793 to throttle the number of duplicate print_queue_update msgs
1794 sent. */
1796 pdb = get_print_db_byname(sharename);
1797 if (!pdb) {
1798 SAFE_FREE(buffer);
1799 return;
1802 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1804 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1805 /* log a message but continue on */
1807 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1808 sharename));
1811 release_print_db( pdb );
1813 /* finally send the message */
1815 messaging_send_buf(msg_ctx, pid_to_procid(background_lpq_updater_pid),
1816 MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1818 SAFE_FREE( buffer );
1820 return;
1823 /****************************************************************************
1824 Create/Update an entry in the print tdb that will allow us to send notify
1825 updates only to interested smbd's.
1826 ****************************************************************************/
1828 bool print_notify_register_pid(int snum)
1830 TDB_DATA data;
1831 struct tdb_print_db *pdb = NULL;
1832 TDB_CONTEXT *tdb = NULL;
1833 const char *printername;
1834 uint32_t mypid = (uint32_t)getpid();
1835 bool ret = False;
1836 size_t i;
1838 /* if (snum == -1), then the change notify request was
1839 on a print server handle and we need to register on
1840 all print queus */
1842 if (snum == -1)
1844 int num_services = lp_numservices();
1845 int idx;
1847 for ( idx=0; idx<num_services; idx++ ) {
1848 if (lp_snum_ok(idx) && lp_printable(idx) )
1849 print_notify_register_pid(idx);
1852 return True;
1854 else /* register for a specific printer */
1856 printername = lp_const_servicename(snum);
1857 pdb = get_print_db_byname(printername);
1858 if (!pdb)
1859 return False;
1860 tdb = pdb->tdb;
1863 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) != 0) {
1864 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1865 printername));
1866 if (pdb)
1867 release_print_db(pdb);
1868 return False;
1871 data = get_printer_notify_pid_list( tdb, printername, True );
1873 /* Add ourselves and increase the refcount. */
1875 for (i = 0; i < data.dsize; i += 8) {
1876 if (IVAL(data.dptr,i) == mypid) {
1877 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1878 SIVAL(data.dptr, i+4, new_refcount);
1879 break;
1883 if (i == data.dsize) {
1884 /* We weren't in the list. Realloc. */
1885 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1886 if (!data.dptr) {
1887 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1888 printername));
1889 goto done;
1891 data.dsize += 8;
1892 SIVAL(data.dptr,data.dsize - 8,mypid);
1893 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1896 /* Store back the record. */
1897 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) != 0) {
1898 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1899 list for printer %s\n", printername));
1900 goto done;
1903 ret = True;
1905 done:
1907 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1908 if (pdb)
1909 release_print_db(pdb);
1910 SAFE_FREE(data.dptr);
1911 return ret;
1914 /****************************************************************************
1915 Update an entry in the print tdb that will allow us to send notify
1916 updates only to interested smbd's.
1917 ****************************************************************************/
1919 bool print_notify_deregister_pid(int snum)
1921 TDB_DATA data;
1922 struct tdb_print_db *pdb = NULL;
1923 TDB_CONTEXT *tdb = NULL;
1924 const char *printername;
1925 uint32_t mypid = (uint32_t)getpid();
1926 size_t i;
1927 bool ret = False;
1929 /* if ( snum == -1 ), we are deregister a print server handle
1930 which means to deregister on all print queues */
1932 if (snum == -1)
1934 int num_services = lp_numservices();
1935 int idx;
1937 for ( idx=0; idx<num_services; idx++ ) {
1938 if ( lp_snum_ok(idx) && lp_printable(idx) )
1939 print_notify_deregister_pid(idx);
1942 return True;
1944 else /* deregister a specific printer */
1946 printername = lp_const_servicename(snum);
1947 pdb = get_print_db_byname(printername);
1948 if (!pdb)
1949 return False;
1950 tdb = pdb->tdb;
1953 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) != 0) {
1954 DEBUG(0,("print_notify_register_pid: Failed to lock \
1955 printer %s database\n", printername));
1956 if (pdb)
1957 release_print_db(pdb);
1958 return False;
1961 data = get_printer_notify_pid_list( tdb, printername, True );
1963 /* Reduce refcount. Remove ourselves if zero. */
1965 for (i = 0; i < data.dsize; ) {
1966 if (IVAL(data.dptr,i) == mypid) {
1967 uint32 refcount = IVAL(data.dptr, i+4);
1969 refcount--;
1971 if (refcount == 0) {
1972 if (data.dsize - i > 8)
1973 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1974 data.dsize -= 8;
1975 continue;
1977 SIVAL(data.dptr, i+4, refcount);
1980 i += 8;
1983 if (data.dsize == 0)
1984 SAFE_FREE(data.dptr);
1986 /* Store back the record. */
1987 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) != 0) {
1988 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1989 list for printer %s\n", printername));
1990 goto done;
1993 ret = True;
1995 done:
1997 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1998 if (pdb)
1999 release_print_db(pdb);
2000 SAFE_FREE(data.dptr);
2001 return ret;
2004 /****************************************************************************
2005 Check if a jobid is valid. It is valid if it exists in the database.
2006 ****************************************************************************/
2008 bool print_job_exists(const char* sharename, uint32 jobid)
2010 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2011 bool ret;
2012 uint32_t tmp;
2014 if (!pdb)
2015 return False;
2016 ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
2017 release_print_db(pdb);
2018 return ret;
2021 /****************************************************************************
2022 Return the device mode asigned to a specific print job.
2023 Only valid for the process doing the spooling and when the job
2024 has not been spooled.
2025 ****************************************************************************/
2027 struct spoolss_DeviceMode *print_job_devmode(TALLOC_CTX *mem_ctx,
2028 const char *sharename,
2029 uint32 jobid)
2031 struct printjob *pjob = print_job_find(mem_ctx, sharename, jobid);
2032 if (pjob == NULL) {
2033 return NULL;
2036 return pjob->devmode;
2039 /****************************************************************************
2040 Set the name of a job. Only possible for owner.
2041 ****************************************************************************/
2043 bool print_job_set_name(struct tevent_context *ev,
2044 struct messaging_context *msg_ctx,
2045 const char *sharename, uint32 jobid, const char *name)
2047 struct printjob *pjob;
2048 bool ret;
2049 TALLOC_CTX *tmp_ctx = talloc_new(ev);
2050 if (tmp_ctx == NULL) {
2051 return false;
2054 pjob = print_job_find(tmp_ctx, sharename, jobid);
2055 if (!pjob || pjob->pid != getpid()) {
2056 ret = false;
2057 goto err_out;
2060 fstrcpy(pjob->jobname, name);
2061 ret = pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2062 err_out:
2063 talloc_free(tmp_ctx);
2064 return ret;
2067 /****************************************************************************
2068 Get the name of a job. Only possible for owner.
2069 ****************************************************************************/
2071 bool print_job_get_name(TALLOC_CTX *mem_ctx, const char *sharename, uint32_t jobid, char **name)
2073 struct printjob *pjob;
2075 pjob = print_job_find(mem_ctx, sharename, jobid);
2076 if (!pjob || pjob->pid != getpid()) {
2077 return false;
2080 *name = pjob->jobname;
2081 return true;
2085 /***************************************************************************
2086 Remove a jobid from the 'jobs added' list.
2087 ***************************************************************************/
2089 static bool remove_from_jobs_added(const char* sharename, uint32 jobid)
2091 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2092 TDB_DATA data, key;
2093 size_t job_count, i;
2094 bool ret = False;
2095 bool gotlock = False;
2097 if (!pdb) {
2098 return False;
2101 ZERO_STRUCT(data);
2103 key = string_tdb_data("INFO/jobs_added");
2105 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) != 0)
2106 goto out;
2108 gotlock = True;
2110 data = tdb_fetch_compat(pdb->tdb, key);
2112 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
2113 goto out;
2115 job_count = data.dsize / 4;
2116 for (i = 0; i < job_count; i++) {
2117 uint32 ch_jobid;
2119 ch_jobid = IVAL(data.dptr, i*4);
2120 if (ch_jobid == jobid) {
2121 if (i < job_count -1 )
2122 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
2123 data.dsize -= 4;
2124 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) != 0)
2125 goto out;
2126 break;
2130 ret = True;
2131 out:
2133 if (gotlock)
2134 tdb_chainunlock(pdb->tdb, key);
2135 SAFE_FREE(data.dptr);
2136 release_print_db(pdb);
2137 if (ret)
2138 DEBUG(10,("remove_from_jobs_added: removed jobid %u\n", (unsigned int)jobid ));
2139 else
2140 DEBUG(10,("remove_from_jobs_added: Failed to remove jobid %u\n", (unsigned int)jobid ));
2141 return ret;
2144 /****************************************************************************
2145 Delete a print job - don't update queue.
2146 ****************************************************************************/
2148 static bool print_job_delete1(struct tevent_context *ev,
2149 struct messaging_context *msg_ctx,
2150 int snum, uint32 jobid)
2152 const char* sharename = lp_const_servicename(snum);
2153 struct printjob *pjob;
2154 int result = 0;
2155 struct printif *current_printif = get_printer_fns( snum );
2156 bool ret;
2157 TALLOC_CTX *tmp_ctx = talloc_new(ev);
2158 if (tmp_ctx == NULL) {
2159 return false;
2162 pjob = print_job_find(tmp_ctx, sharename, jobid);
2163 if (!pjob) {
2164 ret = false;
2165 goto err_out;
2169 * If already deleting just return.
2172 if (pjob->status == LPQ_DELETING) {
2173 ret = true;
2174 goto err_out;
2177 /* Hrm - we need to be able to cope with deleting a job before it
2178 has reached the spooler. Just mark it as LPQ_DELETING and
2179 let the print_queue_update() code rmeove the record */
2182 if (pjob->sysjob == -1) {
2183 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
2186 /* Set the tdb entry to be deleting. */
2188 pjob->status = LPQ_DELETING;
2189 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2191 if (pjob->spooled && pjob->sysjob != -1)
2193 result = (*(current_printif->job_delete))(
2194 lp_printername(talloc_tos(), snum),
2195 lp_lprm_command(talloc_tos(), snum),
2196 pjob);
2198 /* Delete the tdb entry if the delete succeeded or the job hasn't
2199 been spooled. */
2201 if (result == 0) {
2202 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2203 int njobs = 1;
2205 if (!pdb) {
2206 ret = false;
2207 goto err_out;
2209 pjob_delete(ev, msg_ctx, sharename, jobid);
2210 /* Ensure we keep a rough count of the number of total jobs... */
2211 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
2212 release_print_db(pdb);
2216 remove_from_jobs_added( sharename, jobid );
2218 ret = (result == 0);
2219 err_out:
2220 talloc_free(tmp_ctx);
2221 return ret;
2224 /****************************************************************************
2225 Return true if the current user owns the print job.
2226 ****************************************************************************/
2228 static bool is_owner(const struct auth_session_info *server_info,
2229 const char *servicename,
2230 uint32 jobid)
2232 struct printjob *pjob;
2233 bool ret;
2234 TALLOC_CTX *tmp_ctx = talloc_new(server_info);
2235 if (tmp_ctx == NULL) {
2236 return false;
2239 pjob = print_job_find(tmp_ctx, servicename, jobid);
2240 if (!pjob || !server_info) {
2241 ret = false;
2242 goto err_out;
2245 ret = strequal(pjob->user, server_info->unix_info->sanitized_username);
2246 err_out:
2247 talloc_free(tmp_ctx);
2248 return ret;
2251 /****************************************************************************
2252 Delete a print job.
2253 ****************************************************************************/
2255 WERROR print_job_delete(const struct auth_session_info *server_info,
2256 struct messaging_context *msg_ctx,
2257 int snum, uint32_t jobid)
2259 const char* sharename = lp_const_servicename(snum);
2260 struct printjob *pjob;
2261 bool owner;
2262 WERROR werr;
2263 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2264 if (tmp_ctx == NULL) {
2265 return WERR_NOT_ENOUGH_MEMORY;
2268 owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2270 /* Check access against security descriptor or whether the user
2271 owns their job. */
2273 if (!owner &&
2274 !W_ERROR_IS_OK(print_access_check(server_info, msg_ctx, snum,
2275 JOB_ACCESS_ADMINISTER))) {
2276 DEBUG(0, ("print job delete denied."
2277 "User name: %s, Printer name: %s.",
2278 uidtoname(server_info->unix_token->uid),
2279 lp_printername(tmp_ctx, snum)));
2281 werr = WERR_ACCESS_DENIED;
2282 goto err_out;
2286 * get the spooled filename of the print job
2287 * if this works, then the file has not been spooled
2288 * to the underlying print system. Just delete the
2289 * spool file & return.
2292 pjob = print_job_find(tmp_ctx, sharename, jobid);
2293 if (!pjob || pjob->spooled || pjob->pid != getpid()) {
2294 DEBUG(10, ("Skipping spool file removal for job %u\n", jobid));
2295 } else {
2296 DEBUG(10, ("Removing spool file [%s]\n", pjob->filename));
2297 if (unlink(pjob->filename) == -1) {
2298 werr = map_werror_from_unix(errno);
2299 goto err_out;
2303 if (!print_job_delete1(server_event_context(), msg_ctx, snum, jobid)) {
2304 werr = WERR_ACCESS_DENIED;
2305 goto err_out;
2308 /* force update the database and say the delete failed if the
2309 job still exists */
2311 print_queue_update(msg_ctx, snum, True);
2313 pjob = print_job_find(tmp_ctx, sharename, jobid);
2314 if (pjob && (pjob->status != LPQ_DELETING)) {
2315 werr = WERR_ACCESS_DENIED;
2316 goto err_out;
2318 werr = WERR_PRINTER_HAS_JOBS_QUEUED;
2320 err_out:
2321 talloc_free(tmp_ctx);
2322 return werr;
2325 /****************************************************************************
2326 Pause a job.
2327 ****************************************************************************/
2329 WERROR print_job_pause(const struct auth_session_info *server_info,
2330 struct messaging_context *msg_ctx,
2331 int snum, uint32 jobid)
2333 const char* sharename = lp_const_servicename(snum);
2334 struct printjob *pjob;
2335 int ret = -1;
2336 struct printif *current_printif = get_printer_fns( snum );
2337 WERROR werr;
2338 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2339 if (tmp_ctx == NULL) {
2340 return WERR_NOT_ENOUGH_MEMORY;
2343 pjob = print_job_find(tmp_ctx, sharename, jobid);
2344 if (!pjob || !server_info) {
2345 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2346 (unsigned int)jobid ));
2347 werr = WERR_INVALID_PARAM;
2348 goto err_out;
2351 if (!pjob->spooled || pjob->sysjob == -1) {
2352 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2353 (int)pjob->sysjob, (unsigned int)jobid ));
2354 werr = WERR_INVALID_PARAM;
2355 goto err_out;
2358 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2359 !W_ERROR_IS_OK(print_access_check(server_info, msg_ctx, snum,
2360 JOB_ACCESS_ADMINISTER))) {
2361 DEBUG(0, ("print job pause denied."
2362 "User name: %s, Printer name: %s.",
2363 uidtoname(server_info->unix_token->uid),
2364 lp_printername(tmp_ctx, snum)));
2366 werr = WERR_ACCESS_DENIED;
2367 goto err_out;
2370 /* need to pause the spooled entry */
2371 ret = (*(current_printif->job_pause))(snum, pjob);
2373 if (ret != 0) {
2374 werr = WERR_INVALID_PARAM;
2375 goto err_out;
2378 /* force update the database */
2379 print_cache_flush(lp_const_servicename(snum));
2381 /* Send a printer notify message */
2383 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2384 JOB_STATUS_PAUSED);
2386 /* how do we tell if this succeeded? */
2387 werr = WERR_OK;
2388 err_out:
2389 talloc_free(tmp_ctx);
2390 return werr;
2393 /****************************************************************************
2394 Resume a job.
2395 ****************************************************************************/
2397 WERROR print_job_resume(const struct auth_session_info *server_info,
2398 struct messaging_context *msg_ctx,
2399 int snum, uint32 jobid)
2401 const char *sharename = lp_const_servicename(snum);
2402 struct printjob *pjob;
2403 int ret;
2404 struct printif *current_printif = get_printer_fns( snum );
2405 WERROR werr;
2406 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2407 if (tmp_ctx == NULL)
2408 return WERR_NOT_ENOUGH_MEMORY;
2410 pjob = print_job_find(tmp_ctx, sharename, jobid);
2411 if (!pjob || !server_info) {
2412 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2413 (unsigned int)jobid ));
2414 werr = WERR_INVALID_PARAM;
2415 goto err_out;
2418 if (!pjob->spooled || pjob->sysjob == -1) {
2419 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2420 (int)pjob->sysjob, (unsigned int)jobid ));
2421 werr = WERR_INVALID_PARAM;
2422 goto err_out;
2425 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2426 !W_ERROR_IS_OK(print_access_check(server_info, msg_ctx, snum,
2427 JOB_ACCESS_ADMINISTER))) {
2428 DEBUG(0, ("print job resume denied."
2429 "User name: %s, Printer name: %s.",
2430 uidtoname(server_info->unix_token->uid),
2431 lp_printername(tmp_ctx, snum)));
2433 werr = WERR_ACCESS_DENIED;
2434 goto err_out;
2437 ret = (*(current_printif->job_resume))(snum, pjob);
2439 if (ret != 0) {
2440 werr = WERR_INVALID_PARAM;
2441 goto err_out;
2444 /* force update the database */
2445 print_cache_flush(lp_const_servicename(snum));
2447 /* Send a printer notify message */
2449 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2450 JOB_STATUS_QUEUED);
2452 werr = WERR_OK;
2453 err_out:
2454 talloc_free(tmp_ctx);
2455 return werr;
2458 /****************************************************************************
2459 Write to a print file.
2460 ****************************************************************************/
2462 ssize_t print_job_write(struct tevent_context *ev,
2463 struct messaging_context *msg_ctx,
2464 int snum, uint32 jobid, const char *buf, size_t size)
2466 const char* sharename = lp_const_servicename(snum);
2467 ssize_t return_code;
2468 struct printjob *pjob;
2469 TALLOC_CTX *tmp_ctx = talloc_new(ev);
2470 if (tmp_ctx == NULL) {
2471 return -1;
2474 pjob = print_job_find(tmp_ctx, sharename, jobid);
2475 if (!pjob) {
2476 return_code = -1;
2477 goto err_out;
2480 /* don't allow another process to get this info - it is meaningless */
2481 if (pjob->pid != getpid()) {
2482 return_code = -1;
2483 goto err_out;
2486 /* if SMBD is spooling this can't be allowed */
2487 if (pjob->status == PJOB_SMBD_SPOOLING) {
2488 return_code = -1;
2489 goto err_out;
2492 return_code = write_data(pjob->fd, buf, size);
2493 if (return_code > 0) {
2494 pjob->size += size;
2495 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2497 err_out:
2498 talloc_free(tmp_ctx);
2499 return return_code;
2502 /****************************************************************************
2503 Get the queue status - do not update if db is out of date.
2504 ****************************************************************************/
2506 static int get_queue_status(const char* sharename, print_status_struct *status)
2508 fstring keystr;
2509 TDB_DATA data;
2510 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2511 int len;
2513 if (status) {
2514 ZERO_STRUCTP(status);
2517 if (!pdb)
2518 return 0;
2520 if (status) {
2521 fstr_sprintf(keystr, "STATUS/%s", sharename);
2522 data = tdb_fetch_compat(pdb->tdb, string_tdb_data(keystr));
2523 if (data.dptr) {
2524 if (data.dsize == sizeof(print_status_struct))
2525 /* this memcpy is ok since the status struct was
2526 not packed before storing it in the tdb */
2527 memcpy(status, data.dptr, sizeof(print_status_struct));
2528 SAFE_FREE(data.dptr);
2531 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2532 release_print_db(pdb);
2533 return (len == -1 ? 0 : len);
2536 /****************************************************************************
2537 Determine the number of jobs in a queue.
2538 ****************************************************************************/
2540 int print_queue_length(struct messaging_context *msg_ctx, int snum,
2541 print_status_struct *pstatus)
2543 const char* sharename = lp_const_servicename( snum );
2544 print_status_struct status;
2545 int len;
2547 ZERO_STRUCT( status );
2549 /* make sure the database is up to date */
2550 if (print_cache_expired(lp_const_servicename(snum), True))
2551 print_queue_update(msg_ctx, snum, False);
2553 /* also fetch the queue status */
2554 memset(&status, 0, sizeof(status));
2555 len = get_queue_status(sharename, &status);
2557 if (pstatus)
2558 *pstatus = status;
2560 return len;
2563 /***************************************************************************
2564 Allocate a jobid. Hold the lock for as short a time as possible.
2565 ***************************************************************************/
2567 static WERROR allocate_print_jobid(struct tdb_print_db *pdb, int snum,
2568 const char *sharename, uint32 *pjobid)
2570 int i;
2571 uint32 jobid;
2572 enum TDB_ERROR terr;
2573 int ret;
2575 *pjobid = (uint32)-1;
2577 for (i = 0; i < 3; i++) {
2578 /* Lock the database - only wait 20 seconds. */
2579 ret = tdb_lock_bystring_with_timeout(pdb->tdb,
2580 "INFO/nextjob", 20);
2581 if (ret != 0) {
2582 DEBUG(0, ("allocate_print_jobid: "
2583 "Failed to lock printing database %s\n",
2584 sharename));
2585 terr = tdb_error(pdb->tdb);
2586 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2589 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2590 terr = tdb_error(pdb->tdb);
2591 if (terr != TDB_ERR_NOEXIST) {
2592 DEBUG(0, ("allocate_print_jobid: "
2593 "Failed to fetch INFO/nextjob "
2594 "for print queue %s\n", sharename));
2595 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2596 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2598 DEBUG(10, ("allocate_print_jobid: "
2599 "No existing jobid in %s\n", sharename));
2600 jobid = 0;
2603 DEBUG(10, ("allocate_print_jobid: "
2604 "Read jobid %u from %s\n", jobid, sharename));
2606 jobid = NEXT_JOBID(jobid);
2608 ret = tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid);
2609 if (ret != 0) {
2610 terr = tdb_error(pdb->tdb);
2611 DEBUG(3, ("allocate_print_jobid: "
2612 "Failed to store INFO/nextjob.\n"));
2613 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2614 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2617 /* We've finished with the INFO/nextjob lock. */
2618 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2620 if (!print_job_exists(sharename, jobid)) {
2621 break;
2623 DEBUG(10, ("allocate_print_jobid: "
2624 "Found jobid %u in %s\n", jobid, sharename));
2627 if (i > 2) {
2628 DEBUG(0, ("allocate_print_jobid: "
2629 "Failed to allocate a print job for queue %s\n",
2630 sharename));
2631 /* Probably full... */
2632 return WERR_NO_SPOOL_SPACE;
2635 /* Store a dummy placeholder. */
2637 uint32_t tmp;
2638 TDB_DATA dum;
2639 dum.dptr = NULL;
2640 dum.dsize = 0;
2641 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2642 TDB_INSERT) != 0) {
2643 DEBUG(3, ("allocate_print_jobid: "
2644 "jobid (%d) failed to store placeholder.\n",
2645 jobid ));
2646 terr = tdb_error(pdb->tdb);
2647 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2651 *pjobid = jobid;
2652 return WERR_OK;
2655 /***************************************************************************
2656 Append a jobid to the 'jobs added' list.
2657 ***************************************************************************/
2659 static bool add_to_jobs_added(struct tdb_print_db *pdb, uint32 jobid)
2661 TDB_DATA data;
2662 uint32 store_jobid;
2664 SIVAL(&store_jobid, 0, jobid);
2665 data.dptr = (uint8 *)&store_jobid;
2666 data.dsize = 4;
2668 DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
2670 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_added"),
2671 data) == 0);
2675 /***************************************************************************
2676 Do all checks needed to determine if we can start a job.
2677 ***************************************************************************/
2679 static WERROR print_job_checks(const struct auth_session_info *server_info,
2680 struct messaging_context *msg_ctx,
2681 int snum, int *njobs)
2683 const char *sharename = lp_const_servicename(snum);
2684 uint64_t dspace, dsize;
2685 uint64_t minspace;
2686 int ret;
2688 if (!W_ERROR_IS_OK(print_access_check(server_info, msg_ctx, snum,
2689 PRINTER_ACCESS_USE))) {
2690 DEBUG(3, ("print_job_checks: "
2691 "job start denied by security descriptor\n"));
2692 return WERR_ACCESS_DENIED;
2695 if (!print_time_access_check(server_info, msg_ctx, sharename)) {
2696 DEBUG(3, ("print_job_checks: "
2697 "job start denied by time check\n"));
2698 return WERR_ACCESS_DENIED;
2701 /* see if we have sufficient disk space */
2702 if (lp_min_print_space(snum)) {
2703 minspace = lp_min_print_space(snum);
2704 ret = sys_fsusage(lp_path(talloc_tos(), snum), &dspace, &dsize);
2705 if (ret == 0 && dspace < 2*minspace) {
2706 DEBUG(3, ("print_job_checks: "
2707 "disk space check failed.\n"));
2708 return WERR_NO_SPOOL_SPACE;
2712 /* for autoloaded printers, check that the printcap entry still exists */
2713 if (lp_autoloaded(snum) && !pcap_printername_ok(sharename)) {
2714 DEBUG(3, ("print_job_checks: printer name %s check failed.\n",
2715 sharename));
2716 return WERR_ACCESS_DENIED;
2719 /* Insure the maximum queue size is not violated */
2720 *njobs = print_queue_length(msg_ctx, snum, NULL);
2721 if (*njobs > lp_maxprintjobs(snum)) {
2722 DEBUG(3, ("print_job_checks: Queue %s number of jobs (%d) "
2723 "larger than max printjobs per queue (%d).\n",
2724 sharename, *njobs, lp_maxprintjobs(snum)));
2725 return WERR_NO_SPOOL_SPACE;
2728 return WERR_OK;
2731 /***************************************************************************
2732 Create a job file.
2733 ***************************************************************************/
2735 static WERROR print_job_spool_file(int snum, uint32_t jobid,
2736 const char *output_file,
2737 struct printjob *pjob)
2739 WERROR werr;
2740 SMB_STRUCT_STAT st;
2741 const char *path;
2742 int len;
2743 mode_t mask;
2745 /* if this file is within the printer path, it means that smbd
2746 * is spooling it and will pass us control when it is finished.
2747 * Verify that the file name is ok, within path, and it is
2748 * already already there */
2749 if (output_file) {
2750 path = lp_path(talloc_tos(), snum);
2751 len = strlen(path);
2752 if (strncmp(output_file, path, len) == 0 &&
2753 (output_file[len - 1] == '/' || output_file[len] == '/')) {
2755 /* verify path is not too long */
2756 if (strlen(output_file) >= sizeof(pjob->filename)) {
2757 return WERR_INVALID_NAME;
2760 /* verify that the file exists */
2761 if (sys_stat(output_file, &st, false) != 0) {
2762 return WERR_INVALID_NAME;
2765 fstrcpy(pjob->filename, output_file);
2767 DEBUG(3, ("print_job_spool_file:"
2768 "External spooling activated\n"));
2770 /* we do not open the file until spooling is done */
2771 pjob->fd = -1;
2772 pjob->status = PJOB_SMBD_SPOOLING;
2774 return WERR_OK;
2778 slprintf(pjob->filename, sizeof(pjob->filename)-1,
2779 "%s/%sXXXXXX", lp_path(talloc_tos(), snum),
2780 PRINT_SPOOL_PREFIX);
2781 mask = umask(S_IRWXO | S_IRWXG);
2782 pjob->fd = mkstemp(pjob->filename);
2783 umask(mask);
2785 if (pjob->fd == -1) {
2786 werr = map_werror_from_unix(errno);
2787 if (W_ERROR_EQUAL(werr, WERR_ACCESS_DENIED)) {
2788 /* Common setup error, force a report. */
2789 DEBUG(0, ("print_job_spool_file: "
2790 "insufficient permissions to open spool "
2791 "file %s.\n", pjob->filename));
2792 } else {
2793 /* Normal case, report at level 3 and above. */
2794 DEBUG(3, ("print_job_spool_file: "
2795 "can't open spool file %s\n",
2796 pjob->filename));
2798 return werr;
2801 return WERR_OK;
2804 /***************************************************************************
2805 Start spooling a job - return the jobid.
2806 ***************************************************************************/
2808 WERROR print_job_start(const struct auth_session_info *server_info,
2809 struct messaging_context *msg_ctx,
2810 const char *clientmachine,
2811 int snum, const char *docname, const char *filename,
2812 struct spoolss_DeviceMode *devmode, uint32_t *_jobid)
2814 uint32_t jobid;
2815 char *path;
2816 struct printjob pjob;
2817 const char *sharename = lp_const_servicename(snum);
2818 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2819 int njobs;
2820 WERROR werr;
2822 if (!pdb) {
2823 return WERR_INTERNAL_DB_CORRUPTION;
2826 path = lp_path(talloc_tos(), snum);
2828 werr = print_job_checks(server_info, msg_ctx, snum, &njobs);
2829 if (!W_ERROR_IS_OK(werr)) {
2830 release_print_db(pdb);
2831 return werr;
2834 DEBUG(10, ("print_job_start: "
2835 "Queue %s number of jobs (%d), max printjobs = %d\n",
2836 sharename, njobs, lp_maxprintjobs(snum)));
2838 werr = allocate_print_jobid(pdb, snum, sharename, &jobid);
2839 if (!W_ERROR_IS_OK(werr)) {
2840 goto fail;
2843 /* create the database entry */
2845 ZERO_STRUCT(pjob);
2847 pjob.pid = getpid();
2848 pjob.jobid = jobid;
2849 pjob.sysjob = -1;
2850 pjob.fd = -1;
2851 pjob.starttime = time(NULL);
2852 pjob.status = LPQ_SPOOLING;
2853 pjob.size = 0;
2854 pjob.spooled = False;
2855 pjob.smbjob = True;
2856 pjob.devmode = devmode;
2858 fstrcpy(pjob.jobname, docname);
2860 fstrcpy(pjob.clientmachine, clientmachine);
2862 fstrcpy(pjob.user, lp_printjob_username(snum));
2863 standard_sub_advanced(sharename, server_info->unix_info->sanitized_username,
2864 path, server_info->unix_token->gid,
2865 server_info->unix_info->sanitized_username,
2866 server_info->info->domain_name,
2867 pjob.user, sizeof(pjob.user));
2869 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2871 /* we have a job entry - now create the spool file */
2872 werr = print_job_spool_file(snum, jobid, filename, &pjob);
2873 if (!W_ERROR_IS_OK(werr)) {
2874 goto fail;
2877 pjob_store(server_event_context(), msg_ctx, sharename, jobid, &pjob);
2879 /* Update the 'jobs added' entry used by print_queue_status. */
2880 add_to_jobs_added(pdb, jobid);
2882 /* Ensure we keep a rough count of the number of total jobs... */
2883 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2885 release_print_db(pdb);
2887 *_jobid = jobid;
2888 return WERR_OK;
2890 fail:
2891 if (jobid != -1) {
2892 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2895 release_print_db(pdb);
2897 DEBUG(3, ("print_job_start: returning fail. "
2898 "Error = %s\n", win_errstr(werr)));
2899 return werr;
2902 /****************************************************************************
2903 Update the number of pages spooled to jobid
2904 ****************************************************************************/
2906 void print_job_endpage(struct messaging_context *msg_ctx,
2907 int snum, uint32 jobid)
2909 const char* sharename = lp_const_servicename(snum);
2910 struct printjob *pjob;
2911 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2912 if (tmp_ctx == NULL) {
2913 return;
2916 pjob = print_job_find(tmp_ctx, sharename, jobid);
2917 if (!pjob) {
2918 goto err_out;
2920 /* don't allow another process to get this info - it is meaningless */
2921 if (pjob->pid != getpid()) {
2922 goto err_out;
2925 pjob->page_count++;
2926 pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
2927 err_out:
2928 talloc_free(tmp_ctx);
2931 /****************************************************************************
2932 Print a file - called on closing the file. This spools the job.
2933 If normal close is false then we're tearing down the jobs - treat as an
2934 error.
2935 ****************************************************************************/
2937 NTSTATUS print_job_end(struct messaging_context *msg_ctx, int snum,
2938 uint32 jobid, enum file_close_type close_type)
2940 const char* sharename = lp_const_servicename(snum);
2941 struct printjob *pjob;
2942 int ret;
2943 SMB_STRUCT_STAT sbuf;
2944 struct printif *current_printif = get_printer_fns(snum);
2945 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2946 char *lpq_cmd;
2947 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2948 if (tmp_ctx == NULL) {
2949 return NT_STATUS_NO_MEMORY;
2952 pjob = print_job_find(tmp_ctx, sharename, jobid);
2953 if (!pjob) {
2954 status = NT_STATUS_PRINT_CANCELLED;
2955 goto err_out;
2958 if (pjob->spooled || pjob->pid != getpid()) {
2959 status = NT_STATUS_ACCESS_DENIED;
2960 goto err_out;
2963 if (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) {
2964 if (pjob->status == PJOB_SMBD_SPOOLING) {
2965 /* take over the file now, smbd is done */
2966 if (sys_stat(pjob->filename, &sbuf, false) != 0) {
2967 status = map_nt_error_from_unix(errno);
2968 DEBUG(3, ("print_job_end: "
2969 "stat file failed for jobid %d\n",
2970 jobid));
2971 goto fail;
2974 pjob->status = LPQ_SPOOLING;
2976 } else {
2978 if ((sys_fstat(pjob->fd, &sbuf, false) != 0)) {
2979 status = map_nt_error_from_unix(errno);
2980 close(pjob->fd);
2981 DEBUG(3, ("print_job_end: "
2982 "stat file failed for jobid %d\n",
2983 jobid));
2984 goto fail;
2987 close(pjob->fd);
2990 pjob->size = sbuf.st_ex_size;
2991 } else {
2994 * Not a normal close, something has gone wrong. Cleanup.
2996 if (pjob->fd != -1) {
2997 close(pjob->fd);
2999 goto fail;
3002 /* Technically, this is not quite right. If the printer has a separator
3003 * page turned on, the NT spooler prints the separator page even if the
3004 * print job is 0 bytes. 010215 JRR */
3005 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
3006 /* don't bother spooling empty files or something being deleted. */
3007 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
3008 pjob->filename, pjob->size ? "deleted" : "zero length" ));
3009 unlink(pjob->filename);
3010 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
3011 return NT_STATUS_OK;
3014 /* don't strip out characters like '$' from the printername */
3015 lpq_cmd = talloc_string_sub2(tmp_ctx,
3016 lp_lpq_command(talloc_tos(), snum),
3017 "%p",
3018 lp_printername(talloc_tos(), snum),
3019 false, false, false);
3020 if (lpq_cmd == NULL) {
3021 status = NT_STATUS_PRINT_CANCELLED;
3022 goto fail;
3024 lpq_cmd = talloc_sub_advanced(tmp_ctx,
3025 lp_servicename(talloc_tos(), snum),
3026 current_user_info.unix_name,
3028 current_user.ut.gid,
3029 get_current_username(),
3030 current_user_info.domain,
3031 lpq_cmd);
3032 if (lpq_cmd == NULL) {
3033 status = NT_STATUS_PRINT_CANCELLED;
3034 goto fail;
3037 ret = (*(current_printif->job_submit))(snum, pjob,
3038 current_printif->type, lpq_cmd);
3039 if (ret) {
3040 status = NT_STATUS_PRINT_CANCELLED;
3041 goto fail;
3044 /* The print job has been successfully handed over to the back-end */
3046 pjob->spooled = True;
3047 pjob->status = LPQ_QUEUED;
3048 pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
3050 /* make sure the database is up to date */
3051 if (print_cache_expired(lp_const_servicename(snum), True))
3052 print_queue_update(msg_ctx, snum, False);
3054 return NT_STATUS_OK;
3056 fail:
3058 /* The print job was not successfully started. Cleanup */
3059 /* Still need to add proper error return propagation! 010122:JRR */
3060 pjob->fd = -1;
3061 unlink(pjob->filename);
3062 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
3063 err_out:
3064 talloc_free(tmp_ctx);
3065 return status;
3068 /****************************************************************************
3069 Get a snapshot of jobs in the system without traversing.
3070 ****************************************************************************/
3072 static bool get_stored_queue_info(struct messaging_context *msg_ctx,
3073 struct tdb_print_db *pdb, int snum,
3074 int *pcount, print_queue_struct **ppqueue)
3076 TDB_DATA data, cgdata, jcdata;
3077 print_queue_struct *queue = NULL;
3078 uint32 qcount = 0;
3079 uint32 extra_count = 0;
3080 uint32_t changed_count = 0;
3081 int total_count = 0;
3082 size_t len = 0;
3083 uint32 i;
3084 int max_reported_jobs = lp_max_reported_print_jobs(snum);
3085 bool ret = false;
3086 const char* sharename = lp_servicename(talloc_tos(), snum);
3087 TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
3088 if (tmp_ctx == NULL) {
3089 return false;
3092 /* make sure the database is up to date */
3093 if (print_cache_expired(lp_const_servicename(snum), True))
3094 print_queue_update(msg_ctx, snum, False);
3096 *pcount = 0;
3097 *ppqueue = NULL;
3099 ZERO_STRUCT(data);
3100 ZERO_STRUCT(cgdata);
3102 /* Get the stored queue data. */
3103 data = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
3105 if (data.dptr && data.dsize >= sizeof(qcount))
3106 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
3108 /* Get the added jobs list. */
3109 cgdata = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_added"));
3110 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
3111 extra_count = cgdata.dsize/4;
3113 /* Get the changed jobs list. */
3114 jcdata = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
3115 if (jcdata.dptr != NULL && (jcdata.dsize % 4 == 0))
3116 changed_count = jcdata.dsize / 4;
3118 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
3120 /* Allocate the queue size. */
3121 if (qcount == 0 && extra_count == 0)
3122 goto out;
3124 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
3125 goto out;
3127 /* Retrieve the linearised queue data. */
3129 for(i = 0; i < qcount; i++) {
3130 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
3131 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
3132 &qjob,
3133 &qsize,
3134 &qpage_count,
3135 &qstatus,
3136 &qpriority,
3137 &qtime,
3138 queue[i].fs_user,
3139 queue[i].fs_file);
3140 queue[i].sysjob = qjob;
3141 queue[i].size = qsize;
3142 queue[i].page_count = qpage_count;
3143 queue[i].status = qstatus;
3144 queue[i].priority = qpriority;
3145 queue[i].time = qtime;
3148 total_count = qcount;
3150 /* Add new jobids to the queue. */
3151 for (i = 0; i < extra_count; i++) {
3152 uint32 jobid;
3153 struct printjob *pjob;
3155 jobid = IVAL(cgdata.dptr, i*4);
3156 DEBUG(5,("get_stored_queue_info: added job = %u\n", (unsigned int)jobid));
3157 pjob = print_job_find(tmp_ctx, lp_const_servicename(snum), jobid);
3158 if (!pjob) {
3159 DEBUG(5,("get_stored_queue_info: failed to find added job = %u\n", (unsigned int)jobid));
3160 remove_from_jobs_added(sharename, jobid);
3161 continue;
3164 queue[total_count].sysjob = pjob->sysjob;
3165 queue[total_count].size = pjob->size;
3166 queue[total_count].page_count = pjob->page_count;
3167 queue[total_count].status = pjob->status;
3168 queue[total_count].priority = 1;
3169 queue[total_count].time = pjob->starttime;
3170 fstrcpy(queue[total_count].fs_user, pjob->user);
3171 fstrcpy(queue[total_count].fs_file, pjob->jobname);
3172 total_count++;
3173 talloc_free(pjob);
3176 /* Update the changed jobids. */
3177 for (i = 0; i < changed_count; i++) {
3178 uint32_t jobid = IVAL(jcdata.dptr, i * 4);
3179 struct printjob *pjob;
3180 uint32_t j;
3181 bool found = false;
3183 pjob = print_job_find(tmp_ctx, sharename, jobid);
3184 if (pjob == NULL) {
3185 DEBUG(5,("get_stored_queue_info: failed to find "
3186 "changed job = %u\n",
3187 (unsigned int)jobid));
3188 remove_from_jobs_changed(sharename, jobid);
3189 continue;
3192 for (j = 0; j < total_count; j++) {
3193 if (queue[j].sysjob == pjob->sysjob) {
3194 found = true;
3195 break;
3199 if (found) {
3200 DEBUG(5,("get_stored_queue_info: changed job: %u\n",
3201 (unsigned int)jobid));
3203 queue[j].sysjob = pjob->sysjob;
3204 queue[j].size = pjob->size;
3205 queue[j].page_count = pjob->page_count;
3206 queue[j].status = pjob->status;
3207 queue[j].priority = 1;
3208 queue[j].time = pjob->starttime;
3209 fstrcpy(queue[j].fs_user, pjob->user);
3210 fstrcpy(queue[j].fs_file, pjob->jobname);
3211 talloc_free(pjob);
3213 DEBUG(5,("updated queue[%u], jobid: %u, sysjob: %u, "
3214 "jobname: %s\n",
3215 (unsigned int)j, (unsigned int)jobid,
3216 (unsigned int)queue[j].sysjob, pjob->jobname));
3219 remove_from_jobs_changed(sharename, jobid);
3222 /* Sort the queue by submission time otherwise they are displayed
3223 in hash order. */
3225 TYPESAFE_QSORT(queue, total_count, printjob_comp);
3227 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
3229 if (max_reported_jobs && total_count > max_reported_jobs)
3230 total_count = max_reported_jobs;
3232 *ppqueue = queue;
3233 *pcount = total_count;
3235 ret = true;
3237 out:
3239 SAFE_FREE(data.dptr);
3240 SAFE_FREE(cgdata.dptr);
3241 talloc_free(tmp_ctx);
3242 return ret;
3245 /****************************************************************************
3246 Get a printer queue listing.
3247 set queue = NULL and status = NULL if you just want to update the cache
3248 ****************************************************************************/
3250 int print_queue_status(struct messaging_context *msg_ctx, int snum,
3251 print_queue_struct **ppqueue,
3252 print_status_struct *status)
3254 fstring keystr;
3255 TDB_DATA data, key;
3256 const char *sharename;
3257 struct tdb_print_db *pdb;
3258 int count = 0;
3260 /* make sure the database is up to date */
3262 if (print_cache_expired(lp_const_servicename(snum), True))
3263 print_queue_update(msg_ctx, snum, False);
3265 /* return if we are done */
3266 if ( !ppqueue || !status )
3267 return 0;
3269 *ppqueue = NULL;
3270 sharename = lp_const_servicename(snum);
3271 pdb = get_print_db_byname(sharename);
3273 if (!pdb)
3274 return 0;
3277 * Fetch the queue status. We must do this first, as there may
3278 * be no jobs in the queue.
3281 ZERO_STRUCTP(status);
3282 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
3283 key = string_tdb_data(keystr);
3285 data = tdb_fetch_compat(pdb->tdb, key);
3286 if (data.dptr) {
3287 if (data.dsize == sizeof(*status)) {
3288 /* this memcpy is ok since the status struct was
3289 not packed before storing it in the tdb */
3290 memcpy(status, data.dptr, sizeof(*status));
3292 SAFE_FREE(data.dptr);
3296 * Now, fetch the print queue information. We first count the number
3297 * of entries, and then only retrieve the queue if necessary.
3300 if (!get_stored_queue_info(msg_ctx, pdb, snum, &count, ppqueue)) {
3301 release_print_db(pdb);
3302 return 0;
3305 release_print_db(pdb);
3306 return count;
3309 /****************************************************************************
3310 Pause a queue.
3311 ****************************************************************************/
3313 WERROR print_queue_pause(const struct auth_session_info *server_info,
3314 struct messaging_context *msg_ctx, int snum)
3316 int ret;
3317 struct printif *current_printif = get_printer_fns( snum );
3319 if (!W_ERROR_IS_OK(print_access_check(server_info, msg_ctx, snum,
3320 PRINTER_ACCESS_ADMINISTER))) {
3321 return WERR_ACCESS_DENIED;
3325 become_root();
3327 ret = (*(current_printif->queue_pause))(snum);
3329 unbecome_root();
3331 if (ret != 0) {
3332 return WERR_INVALID_PARAM;
3335 /* force update the database */
3336 print_cache_flush(lp_const_servicename(snum));
3338 /* Send a printer notify message */
3340 notify_printer_status(server_event_context(), msg_ctx, snum,
3341 PRINTER_STATUS_PAUSED);
3343 return WERR_OK;
3346 /****************************************************************************
3347 Resume a queue.
3348 ****************************************************************************/
3350 WERROR print_queue_resume(const struct auth_session_info *server_info,
3351 struct messaging_context *msg_ctx, int snum)
3353 int ret;
3354 struct printif *current_printif = get_printer_fns( snum );
3356 if (!W_ERROR_IS_OK(print_access_check(server_info, msg_ctx, snum,
3357 PRINTER_ACCESS_ADMINISTER))) {
3358 return WERR_ACCESS_DENIED;
3361 become_root();
3363 ret = (*(current_printif->queue_resume))(snum);
3365 unbecome_root();
3367 if (ret != 0) {
3368 return WERR_INVALID_PARAM;
3371 /* make sure the database is up to date */
3372 if (print_cache_expired(lp_const_servicename(snum), True))
3373 print_queue_update(msg_ctx, snum, True);
3375 /* Send a printer notify message */
3377 notify_printer_status(server_event_context(), msg_ctx, snum,
3378 PRINTER_STATUS_OK);
3380 return WERR_OK;
3383 /****************************************************************************
3384 Purge a queue - implemented by deleting all jobs that we can delete.
3385 ****************************************************************************/
3387 WERROR print_queue_purge(const struct auth_session_info *server_info,
3388 struct messaging_context *msg_ctx, int snum)
3390 print_queue_struct *queue;
3391 print_status_struct status;
3392 int njobs, i;
3393 bool can_job_admin;
3395 /* Force and update so the count is accurate (i.e. not a cached count) */
3396 print_queue_update(msg_ctx, snum, True);
3398 can_job_admin = W_ERROR_IS_OK(print_access_check(server_info,
3399 msg_ctx,
3400 snum,
3401 JOB_ACCESS_ADMINISTER));
3402 njobs = print_queue_status(msg_ctx, snum, &queue, &status);
3404 if ( can_job_admin )
3405 become_root();
3407 for (i = 0; i < njobs; i++) {
3408 struct tdb_print_db *pdb;
3409 int jobid;
3410 bool owner;
3411 pdb = get_print_db_byname(lp_const_servicename(snum));
3412 if (pdb == NULL) {
3413 DEBUG(1, ("failed to find printdb for %s\n",
3414 lp_const_servicename(snum)));
3415 continue;
3417 jobid = sysjob_to_jobid_pdb(pdb, queue[i].sysjob);
3418 if (jobid == (uint32_t)-1) {
3419 DEBUG(2, ("jobid for system job %d not found\n",
3420 queue[i].sysjob));
3421 continue; /* unix job */
3423 owner = is_owner(server_info, lp_const_servicename(snum),
3424 jobid);
3426 if (owner || can_job_admin) {
3427 print_job_delete1(server_event_context(), msg_ctx,
3428 snum, jobid);
3432 if ( can_job_admin )
3433 unbecome_root();
3435 /* update the cache */
3436 print_queue_update(msg_ctx, snum, True);
3438 SAFE_FREE(queue);
3440 return WERR_OK;