s3-printing: store print jobid as part of struct printjob
[Samba/id10ts.git] / source3 / printing / printing.c
blob7f742167cc79d0262a0ba084c1b78c833815cf05
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;
201 if (!printer_list_parent_init()) {
202 return false;
205 unlink(cache_path("printing.tdb"));
206 mkdir(cache_path("printing"),0755);
208 /* handle a Samba upgrade */
210 for (snum = 0; snum < services; snum++) {
211 struct tdb_print_db *pdb;
212 if (!lp_print_ok(snum))
213 continue;
215 pdb = get_print_db_byname(lp_const_servicename(snum));
216 if (!pdb)
217 continue;
218 if (tdb_lock_bystring(pdb->tdb, sversion) != 0) {
219 DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
220 release_print_db(pdb);
221 return False;
223 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
224 tdb_wipe_all(pdb->tdb);
225 tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
227 tdb_unlock_bystring(pdb->tdb, sversion);
228 release_print_db(pdb);
231 close_all_print_db(); /* Don't leave any open. */
233 /* do NT print initialization... */
234 return nt_printing_init(msg_ctx);
237 /****************************************************************************
238 Shut down printing backend. Called once at shutdown to close the tdb.
239 ****************************************************************************/
241 void printing_end(void)
243 close_all_print_db(); /* Don't leave any open. */
246 /****************************************************************************
247 Retrieve the set of printing functions for a given service. This allows
248 us to set the printer function table based on the value of the 'printing'
249 service parameter.
251 Use the generic interface as the default and only use cups interface only
252 when asked for (and only when supported)
253 ****************************************************************************/
255 static struct printif *get_printer_fns_from_type( enum printing_types type )
257 struct printif *printer_fns = &generic_printif;
259 #ifdef HAVE_CUPS
260 if ( type == PRINT_CUPS ) {
261 printer_fns = &cups_printif;
263 #endif /* HAVE_CUPS */
265 #ifdef HAVE_IPRINT
266 if ( type == PRINT_IPRINT ) {
267 printer_fns = &iprint_printif;
269 #endif /* HAVE_IPRINT */
271 printer_fns->type = type;
273 return printer_fns;
276 static struct printif *get_printer_fns( int snum )
278 return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
282 /****************************************************************************
283 Useful function to generate a tdb key.
284 ****************************************************************************/
286 static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
288 TDB_DATA ret;
290 SIVAL(tmp, 0, jobid);
291 ret.dptr = (uint8 *)tmp;
292 ret.dsize = sizeof(*tmp);
293 return ret;
296 /****************************************************************************
297 Pack the devicemode to store it in a tdb.
298 ****************************************************************************/
299 static int pack_devicemode(struct spoolss_DeviceMode *devmode, uint8 *buf, int buflen)
301 enum ndr_err_code ndr_err;
302 DATA_BLOB blob;
303 int len = 0;
305 if (devmode) {
306 ndr_err = ndr_push_struct_blob(&blob, talloc_tos(),
307 devmode,
308 (ndr_push_flags_fn_t)
309 ndr_push_spoolss_DeviceMode);
310 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
311 DEBUG(10, ("pack_devicemode: "
312 "error encoding spoolss_DeviceMode\n"));
313 goto done;
315 } else {
316 ZERO_STRUCT(blob);
319 len = tdb_pack(buf, buflen, "B", blob.length, blob.data);
321 if (devmode) {
322 DEBUG(8, ("Packed devicemode [%s]\n", devmode->formname));
325 done:
326 return len;
329 /****************************************************************************
330 Unpack the devicemode to store it in a tdb.
331 ****************************************************************************/
332 static int unpack_devicemode(TALLOC_CTX *mem_ctx,
333 const uint8 *buf, int buflen,
334 struct spoolss_DeviceMode **devmode)
336 struct spoolss_DeviceMode *dm;
337 enum ndr_err_code ndr_err;
338 char *data = NULL;
339 int data_len = 0;
340 DATA_BLOB blob;
341 int len = 0;
343 *devmode = NULL;
345 len = tdb_unpack(buf, buflen, "B", &data_len, &data);
346 if (!data) {
347 return len;
350 dm = talloc_zero(mem_ctx, struct spoolss_DeviceMode);
351 if (!dm) {
352 goto done;
355 blob = data_blob_const(data, data_len);
357 ndr_err = ndr_pull_struct_blob(&blob, dm, dm,
358 (ndr_pull_flags_fn_t)ndr_pull_spoolss_DeviceMode);
359 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
360 DEBUG(10, ("unpack_devicemode: "
361 "error parsing spoolss_DeviceMode\n"));
362 goto done;
365 DEBUG(8, ("Unpacked devicemode [%s](%s)\n",
366 dm->devicename, dm->formname));
367 if (dm->driverextra_data.data) {
368 DEBUG(8, ("with a private section of %d bytes\n",
369 dm->__driverextra_length));
372 *devmode = dm;
374 done:
375 SAFE_FREE(data);
376 return len;
379 /***********************************************************************
380 unpack a pjob from a tdb buffer
381 ***********************************************************************/
383 static int unpack_pjob(uint8 *buf, int buflen, struct printjob *pjob)
385 int len = 0;
386 int used;
387 uint32 pjpid, pjjobid, pjsysjob, pjfd, pjstarttime, pjstatus;
388 uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
390 if (!buf || !pjob) {
391 return -1;
394 len += tdb_unpack(buf+len, buflen-len, "ddddddddddfffff",
395 &pjpid,
396 &pjjobid,
397 &pjsysjob,
398 &pjfd,
399 &pjstarttime,
400 &pjstatus,
401 &pjsize,
402 &pjpage_count,
403 &pjspooled,
404 &pjsmbjob,
405 pjob->filename,
406 pjob->jobname,
407 pjob->user,
408 pjob->clientmachine,
409 pjob->queuename);
411 if (len == -1) {
412 return -1;
415 used = unpack_devicemode(NULL, buf+len, buflen-len, &pjob->devmode);
416 if (used == -1) {
417 return -1;
420 len += used;
422 pjob->pid = pjpid;
423 pjob->jobid = pjjobid;
424 pjob->sysjob = pjsysjob;
425 pjob->fd = pjfd;
426 pjob->starttime = pjstarttime;
427 pjob->status = pjstatus;
428 pjob->size = pjsize;
429 pjob->page_count = pjpage_count;
430 pjob->spooled = pjspooled;
431 pjob->smbjob = pjsmbjob;
433 return len;
437 /****************************************************************************
438 Useful function to find a print job in the database.
439 ****************************************************************************/
441 static struct printjob *print_job_find(const char *sharename, uint32 jobid)
443 static struct printjob pjob;
444 uint32_t tmp;
445 TDB_DATA ret;
446 struct tdb_print_db *pdb = get_print_db_byname(sharename);
448 DEBUG(10,("print_job_find: looking up job %u for share %s\n",
449 (unsigned int)jobid, sharename ));
451 if (!pdb) {
452 return NULL;
455 ret = tdb_fetch_compat(pdb->tdb, print_key(jobid, &tmp));
456 release_print_db(pdb);
458 if (!ret.dptr) {
459 DEBUG(10,("print_job_find: failed to find jobid %u.\n", (unsigned int)jobid ));
460 return NULL;
463 talloc_free(pjob.devmode);
465 ZERO_STRUCT( pjob );
467 if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
468 DEBUG(10,("print_job_find: failed to unpack jobid %u.\n", (unsigned int)jobid ));
469 SAFE_FREE(ret.dptr);
470 return NULL;
473 SAFE_FREE(ret.dptr);
475 DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
476 (int)pjob.sysjob, (unsigned int)jobid ));
477 SMB_ASSERT(pjob.jobid == jobid);
479 return &pjob;
482 /* Convert a unix jobid to a smb jobid */
484 struct unixjob_traverse_state {
485 int sysjob;
486 uint32 sysjob_to_jobid_value;
489 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
490 TDB_DATA data, void *private_data)
492 struct printjob *pjob;
493 struct unixjob_traverse_state *state =
494 (struct unixjob_traverse_state *)private_data;
496 if (!data.dptr || data.dsize == 0)
497 return 0;
499 pjob = (struct printjob *)data.dptr;
500 if (key.dsize != sizeof(uint32))
501 return 0;
503 if (state->sysjob == pjob->sysjob) {
504 state->sysjob_to_jobid_value = pjob->jobid;
505 return 1;
508 return 0;
511 /****************************************************************************
512 This is a *horribly expensive call as we have to iterate through all the
513 current printer tdb's. Don't do this often ! JRA.
514 ****************************************************************************/
516 uint32 sysjob_to_jobid(int unix_jobid)
518 int services = lp_numservices();
519 int snum;
520 struct unixjob_traverse_state state;
522 state.sysjob = unix_jobid;
523 state.sysjob_to_jobid_value = (uint32)-1;
525 for (snum = 0; snum < services; snum++) {
526 struct tdb_print_db *pdb;
527 if (!lp_print_ok(snum))
528 continue;
529 pdb = get_print_db_byname(lp_const_servicename(snum));
530 if (!pdb) {
531 continue;
533 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
534 release_print_db(pdb);
535 if (state.sysjob_to_jobid_value != (uint32)-1)
536 return state.sysjob_to_jobid_value;
538 return (uint32)-1;
541 /****************************************************************************
542 Send notifications based on what has changed after a pjob_store.
543 ****************************************************************************/
545 static const struct {
546 uint32_t lpq_status;
547 uint32_t spoolss_status;
548 } lpq_to_spoolss_status_map[] = {
549 { LPQ_QUEUED, JOB_STATUS_QUEUED },
550 { LPQ_PAUSED, JOB_STATUS_PAUSED },
551 { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
552 { LPQ_PRINTING, JOB_STATUS_PRINTING },
553 { LPQ_DELETING, JOB_STATUS_DELETING },
554 { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
555 { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
556 { LPQ_PRINTED, JOB_STATUS_PRINTED },
557 { LPQ_DELETED, JOB_STATUS_DELETED },
558 { LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
559 { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
560 { (uint32_t)-1, 0 }
563 /* Convert a lpq status value stored in printing.tdb into the
564 appropriate win32 API constant. */
566 static uint32 map_to_spoolss_status(uint32 lpq_status)
568 int i = 0;
570 while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
571 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
572 return lpq_to_spoolss_status_map[i].spoolss_status;
573 i++;
576 return 0;
579 /***************************************************************************
580 Append a jobid to the 'jobs changed' list.
581 ***************************************************************************/
583 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32_t jobid)
585 TDB_DATA data;
586 uint32_t store_jobid;
588 SIVAL(&store_jobid, 0, jobid);
589 data.dptr = (uint8 *) &store_jobid;
590 data.dsize = 4;
592 DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
594 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
595 data) == 0);
598 /***************************************************************************
599 Remove a jobid from the 'jobs changed' list.
600 ***************************************************************************/
602 static bool remove_from_jobs_changed(const char* sharename, uint32_t jobid)
604 struct tdb_print_db *pdb = get_print_db_byname(sharename);
605 TDB_DATA data, key;
606 size_t job_count, i;
607 bool ret = False;
608 bool gotlock = False;
610 if (!pdb) {
611 return False;
614 ZERO_STRUCT(data);
616 key = string_tdb_data("INFO/jobs_changed");
618 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) != 0)
619 goto out;
621 gotlock = True;
623 data = tdb_fetch_compat(pdb->tdb, key);
625 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
626 goto out;
628 job_count = data.dsize / 4;
629 for (i = 0; i < job_count; i++) {
630 uint32 ch_jobid;
632 ch_jobid = IVAL(data.dptr, i*4);
633 if (ch_jobid == jobid) {
634 if (i < job_count -1 )
635 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
636 data.dsize -= 4;
637 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) != 0)
638 goto out;
639 break;
643 ret = True;
644 out:
646 if (gotlock)
647 tdb_chainunlock(pdb->tdb, key);
648 SAFE_FREE(data.dptr);
649 release_print_db(pdb);
650 if (ret)
651 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
652 else
653 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
654 return ret;
657 static void pjob_store_notify(struct tevent_context *ev,
658 struct messaging_context *msg_ctx,
659 const char* sharename, uint32 jobid,
660 struct printjob *old_data,
661 struct printjob *new_data,
662 bool *pchanged)
664 bool new_job = false;
665 bool changed = false;
667 if (old_data == NULL) {
668 new_job = true;
671 /* ACHTUNG! Due to a bug in Samba's spoolss parsing of the
672 NOTIFY_INFO_DATA buffer, we *have* to send the job submission
673 time first or else we'll end up with potential alignment
674 errors. I don't think the systemtime should be spooled as
675 a string, but this gets us around that error.
676 --jerry (i'll feel dirty for this) */
678 if (new_job) {
679 notify_job_submitted(ev, msg_ctx,
680 sharename, jobid, new_data->starttime);
681 notify_job_username(ev, msg_ctx,
682 sharename, jobid, new_data->user);
683 notify_job_name(ev, msg_ctx,
684 sharename, jobid, new_data->jobname);
685 notify_job_status(ev, msg_ctx,
686 sharename, jobid, map_to_spoolss_status(new_data->status));
687 notify_job_total_bytes(ev, msg_ctx,
688 sharename, jobid, new_data->size);
689 notify_job_total_pages(ev, msg_ctx,
690 sharename, jobid, new_data->page_count);
691 } else {
692 if (!strequal(old_data->jobname, new_data->jobname)) {
693 notify_job_name(ev, msg_ctx, sharename,
694 jobid, new_data->jobname);
695 changed = true;
698 if (old_data->status != new_data->status) {
699 notify_job_status(ev, msg_ctx,
700 sharename, jobid,
701 map_to_spoolss_status(new_data->status));
704 if (old_data->size != new_data->size) {
705 notify_job_total_bytes(ev, msg_ctx,
706 sharename, jobid, new_data->size);
709 if (old_data->page_count != new_data->page_count) {
710 notify_job_total_pages(ev, msg_ctx,
711 sharename, jobid,
712 new_data->page_count);
716 *pchanged = changed;
719 /****************************************************************************
720 Store a job structure back to the database.
721 ****************************************************************************/
723 static bool pjob_store(struct tevent_context *ev,
724 struct messaging_context *msg_ctx,
725 const char* sharename, uint32 jobid,
726 struct printjob *pjob)
728 uint32_t tmp;
729 TDB_DATA old_data, new_data;
730 bool ret = False;
731 struct tdb_print_db *pdb = get_print_db_byname(sharename);
732 uint8 *buf = NULL;
733 int len, newlen, buflen;
736 if (!pdb)
737 return False;
739 /* Get old data */
741 old_data = tdb_fetch_compat(pdb->tdb, print_key(jobid, &tmp));
743 /* Doh! Now we have to pack/unpack data since the NT_DEVICEMODE was added */
745 newlen = 0;
747 do {
748 len = 0;
749 buflen = newlen;
750 len += tdb_pack(buf+len, buflen-len, "ddddddddddfffff",
751 (uint32)pjob->pid,
752 (uint32)pjob->jobid,
753 (uint32)pjob->sysjob,
754 (uint32)pjob->fd,
755 (uint32)pjob->starttime,
756 (uint32)pjob->status,
757 (uint32)pjob->size,
758 (uint32)pjob->page_count,
759 (uint32)pjob->spooled,
760 (uint32)pjob->smbjob,
761 pjob->filename,
762 pjob->jobname,
763 pjob->user,
764 pjob->clientmachine,
765 pjob->queuename);
767 len += pack_devicemode(pjob->devmode, buf+len, buflen-len);
769 if (buflen != len) {
770 buf = (uint8 *)SMB_REALLOC(buf, len);
771 if (!buf) {
772 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
773 goto done;
775 newlen = len;
777 } while ( buflen != len );
780 /* Store new data */
782 new_data.dptr = buf;
783 new_data.dsize = len;
784 ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
785 TDB_REPLACE) == 0);
787 /* Send notify updates for what has changed */
789 if ( ret ) {
790 bool changed = false;
791 struct printjob old_pjob;
793 if ( old_data.dsize )
795 if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
797 pjob_store_notify(server_event_context(),
798 msg_ctx,
799 sharename, jobid, &old_pjob,
800 pjob,
801 &changed);
802 talloc_free(old_pjob.devmode);
804 if (changed) {
805 add_to_jobs_changed(pdb, jobid);
810 else {
811 /* new job */
812 pjob_store_notify(server_event_context(), msg_ctx,
813 sharename, jobid, NULL, pjob,
814 &changed);
818 release_print_db(pdb);
819 done:
820 SAFE_FREE( old_data.dptr );
821 SAFE_FREE( buf );
823 return ret;
826 /****************************************************************************
827 Remove a job structure from the database.
828 ****************************************************************************/
830 static void pjob_delete(struct tevent_context *ev,
831 struct messaging_context *msg_ctx,
832 const char* sharename, uint32 jobid)
834 uint32_t tmp;
835 struct printjob *pjob;
836 uint32 job_status = 0;
837 struct tdb_print_db *pdb;
839 pdb = get_print_db_byname( sharename );
841 if (!pdb)
842 return;
844 pjob = print_job_find( sharename, jobid );
846 if (!pjob) {
847 DEBUG(5, ("pjob_delete: we were asked to delete nonexistent job %u\n",
848 (unsigned int)jobid));
849 release_print_db(pdb);
850 return;
853 /* We must cycle through JOB_STATUS_DELETING and
854 JOB_STATUS_DELETED for the port monitor to delete the job
855 properly. */
857 job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
858 notify_job_status(ev, msg_ctx, sharename, jobid, job_status);
860 /* Remove from printing.tdb */
862 tdb_delete(pdb->tdb, print_key(jobid, &tmp));
863 remove_from_jobs_added(sharename, jobid);
864 release_print_db( pdb );
865 rap_jobid_delete(sharename, jobid);
868 /****************************************************************************
869 List a unix job in the print database.
870 ****************************************************************************/
872 static void print_unix_job(struct tevent_context *ev,
873 struct messaging_context *msg_ctx,
874 const char *sharename, print_queue_struct *q,
875 uint32 jobid)
877 struct printjob pj, *old_pj;
879 if (jobid == (uint32)-1)
880 jobid = q->job + UNIX_JOB_START;
882 /* Preserve the timestamp on an existing unix print job */
884 old_pj = print_job_find(sharename, jobid);
886 ZERO_STRUCT(pj);
888 pj.pid = (pid_t)-1;
889 pj.jobid = jobid;
890 pj.sysjob = q->job;
891 pj.fd = -1;
892 pj.starttime = old_pj ? old_pj->starttime : q->time;
893 pj.status = q->status;
894 pj.size = q->size;
895 pj.spooled = True;
896 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
897 if (jobid < UNIX_JOB_START) {
898 pj.smbjob = True;
899 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
900 } else {
901 pj.smbjob = False;
902 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
904 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
905 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
907 pjob_store(ev, msg_ctx, sharename, jobid, &pj);
911 struct traverse_struct {
912 print_queue_struct *queue;
913 int qcount, snum, maxcount, total_jobs;
914 const char *sharename;
915 time_t lpq_time;
916 const char *lprm_command;
917 struct printif *print_if;
918 struct tevent_context *ev;
919 struct messaging_context *msg_ctx;
922 /****************************************************************************
923 Utility fn to delete any jobs that are no longer active.
924 ****************************************************************************/
926 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
928 struct traverse_struct *ts = (struct traverse_struct *)state;
929 struct printjob pjob;
930 uint32 jobid;
931 int i = 0;
933 if ( key.dsize != sizeof(jobid) )
934 return 0;
936 if (unpack_pjob(data.dptr, data.dsize, &pjob) == -1)
937 return 0;
938 talloc_free(pjob.devmode);
939 jobid = pjob.jobid;
941 if (!pjob.smbjob) {
942 /* remove a unix job if it isn't in the system queue any more */
944 for (i=0;i<ts->qcount;i++) {
945 uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
946 if (jobid == u_jobid)
947 break;
949 if (i == ts->qcount) {
950 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
951 (unsigned int)jobid ));
952 pjob_delete(ts->ev, ts->msg_ctx,
953 ts->sharename, jobid);
954 return 0;
957 /* need to continue the the bottom of the function to
958 save the correct attributes */
961 /* maybe it hasn't been spooled yet */
962 if (!pjob.spooled) {
963 /* if a job is not spooled and the process doesn't
964 exist then kill it. This cleans up after smbd
965 deaths */
966 if (!process_exists_by_pid(pjob.pid)) {
967 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
968 (unsigned int)jobid, (unsigned int)pjob.pid ));
969 pjob_delete(ts->ev, ts->msg_ctx,
970 ts->sharename, jobid);
971 } else
972 ts->total_jobs++;
973 return 0;
976 /* this check only makes sense for jobs submitted from Windows clients */
978 if ( pjob.smbjob ) {
979 for (i=0;i<ts->qcount;i++) {
980 uint32 curr_jobid;
982 if ( pjob.status == LPQ_DELETED )
983 continue;
985 curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
987 if (jobid == curr_jobid) {
989 /* try to clean up any jobs that need to be deleted */
991 if ( pjob.status == LPQ_DELETING ) {
992 int result;
994 result = (*(ts->print_if->job_delete))(
995 ts->sharename, ts->lprm_command, &pjob );
997 if ( result != 0 ) {
998 /* if we can't delete, then reset the job status */
999 pjob.status = LPQ_QUEUED;
1000 pjob_store(ts->ev, ts->msg_ctx,
1001 ts->sharename, jobid, &pjob);
1003 else {
1004 /* if we deleted the job, the remove the tdb record */
1005 pjob_delete(ts->ev,
1006 ts->msg_ctx,
1007 ts->sharename, jobid);
1008 pjob.status = LPQ_DELETED;
1013 break;
1018 /* The job isn't in the system queue - we have to assume it has
1019 completed, so delete the database entry. */
1021 if (i == ts->qcount) {
1023 /* A race can occur between the time a job is spooled and
1024 when it appears in the lpq output. This happens when
1025 the job is added to printing.tdb when another smbd
1026 running print_queue_update() has completed a lpq and
1027 is currently traversing the printing tdb and deleting jobs.
1028 Don't delete the job if it was submitted after the lpq_time. */
1030 if (pjob.starttime < ts->lpq_time) {
1031 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
1032 (unsigned int)jobid,
1033 (unsigned int)pjob.starttime,
1034 (unsigned int)ts->lpq_time ));
1035 pjob_delete(ts->ev, ts->msg_ctx,
1036 ts->sharename, jobid);
1037 } else
1038 ts->total_jobs++;
1039 return 0;
1042 /* Save the pjob attributes we will store.
1043 FIXME!!! This is the only place where queue->job
1044 represents the SMB jobid --jerry */
1046 ts->queue[i].job = jobid;
1047 ts->queue[i].size = pjob.size;
1048 ts->queue[i].page_count = pjob.page_count;
1049 ts->queue[i].status = pjob.status;
1050 ts->queue[i].priority = 1;
1051 ts->queue[i].time = pjob.starttime;
1052 fstrcpy(ts->queue[i].fs_user, pjob.user);
1053 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1055 ts->total_jobs++;
1057 return 0;
1060 /****************************************************************************
1061 Check if the print queue has been updated recently enough.
1062 ****************************************************************************/
1064 static void print_cache_flush(const char *sharename)
1066 fstring key;
1067 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1069 if (!pdb)
1070 return;
1071 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
1072 tdb_store_int32(pdb->tdb, key, -1);
1073 release_print_db(pdb);
1076 /****************************************************************************
1077 Check if someone already thinks they are doing the update.
1078 ****************************************************************************/
1080 static pid_t get_updating_pid(const char *sharename)
1082 fstring keystr;
1083 TDB_DATA data, key;
1084 pid_t updating_pid;
1085 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1087 if (!pdb)
1088 return (pid_t)-1;
1089 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1090 key = string_tdb_data(keystr);
1092 data = tdb_fetch_compat(pdb->tdb, key);
1093 release_print_db(pdb);
1094 if (!data.dptr || data.dsize != sizeof(pid_t)) {
1095 SAFE_FREE(data.dptr);
1096 return (pid_t)-1;
1099 updating_pid = IVAL(data.dptr, 0);
1100 SAFE_FREE(data.dptr);
1102 if (process_exists_by_pid(updating_pid))
1103 return updating_pid;
1105 return (pid_t)-1;
1108 /****************************************************************************
1109 Set the fact that we're doing the update, or have finished doing the update
1110 in the tdb.
1111 ****************************************************************************/
1113 static void set_updating_pid(const fstring sharename, bool updating)
1115 fstring keystr;
1116 TDB_DATA key;
1117 TDB_DATA data;
1118 pid_t updating_pid = getpid();
1119 uint8 buffer[4];
1121 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1123 if (!pdb)
1124 return;
1126 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1127 key = string_tdb_data(keystr);
1129 DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
1130 updating ? "" : "not ",
1131 sharename ));
1133 if ( !updating ) {
1134 tdb_delete(pdb->tdb, key);
1135 release_print_db(pdb);
1136 return;
1139 SIVAL( buffer, 0, updating_pid);
1140 data.dptr = buffer;
1141 data.dsize = 4; /* we always assume this is a 4 byte value */
1143 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1144 release_print_db(pdb);
1147 /****************************************************************************
1148 Sort print jobs by submittal time.
1149 ****************************************************************************/
1151 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1153 /* Silly cases */
1155 if (!j1 && !j2)
1156 return 0;
1157 if (!j1)
1158 return -1;
1159 if (!j2)
1160 return 1;
1162 /* Sort on job start time */
1164 if (j1->time == j2->time)
1165 return 0;
1166 return (j1->time > j2->time) ? 1 : -1;
1169 /****************************************************************************
1170 Store the sorted queue representation for later portmon retrieval.
1171 Skip deleted jobs
1172 ****************************************************************************/
1174 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
1176 TDB_DATA data;
1177 int max_reported_jobs = lp_max_reported_jobs(pts->snum);
1178 print_queue_struct *queue = pts->queue;
1179 size_t len;
1180 size_t i;
1181 unsigned int qcount;
1183 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
1184 pts->qcount = max_reported_jobs;
1185 qcount = 0;
1187 /* Work out the size. */
1188 data.dsize = 0;
1189 data.dsize += tdb_pack(NULL, 0, "d", qcount);
1191 for (i = 0; i < pts->qcount; i++) {
1192 if ( queue[i].status == LPQ_DELETED )
1193 continue;
1195 qcount++;
1196 data.dsize += tdb_pack(NULL, 0, "ddddddff",
1197 (uint32)queue[i].job,
1198 (uint32)queue[i].size,
1199 (uint32)queue[i].page_count,
1200 (uint32)queue[i].status,
1201 (uint32)queue[i].priority,
1202 (uint32)queue[i].time,
1203 queue[i].fs_user,
1204 queue[i].fs_file);
1207 if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
1208 return;
1210 len = 0;
1211 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
1212 for (i = 0; i < pts->qcount; i++) {
1213 if ( queue[i].status == LPQ_DELETED )
1214 continue;
1216 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
1217 (uint32)queue[i].job,
1218 (uint32)queue[i].size,
1219 (uint32)queue[i].page_count,
1220 (uint32)queue[i].status,
1221 (uint32)queue[i].priority,
1222 (uint32)queue[i].time,
1223 queue[i].fs_user,
1224 queue[i].fs_file);
1227 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
1228 TDB_REPLACE);
1229 SAFE_FREE(data.dptr);
1230 return;
1233 static TDB_DATA get_jobs_added_data(struct tdb_print_db *pdb)
1235 TDB_DATA data;
1237 ZERO_STRUCT(data);
1239 data = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_added"));
1240 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1241 SAFE_FREE(data.dptr);
1242 ZERO_STRUCT(data);
1245 return data;
1248 static void check_job_added(const char *sharename, TDB_DATA data, uint32 jobid)
1250 unsigned int i;
1251 unsigned int job_count = data.dsize / 4;
1253 for (i = 0; i < job_count; i++) {
1254 uint32 ch_jobid;
1256 ch_jobid = IVAL(data.dptr, i*4);
1257 if (ch_jobid == jobid)
1258 remove_from_jobs_added(sharename, jobid);
1262 /****************************************************************************
1263 Check if the print queue has been updated recently enough.
1264 ****************************************************************************/
1266 static bool print_cache_expired(const char *sharename, bool check_pending)
1268 fstring key;
1269 time_t last_qscan_time, time_now = time(NULL);
1270 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1271 bool result = False;
1273 if (!pdb)
1274 return False;
1276 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1277 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1280 * Invalidate the queue for 3 reasons.
1281 * (1). last queue scan time == -1.
1282 * (2). Current time - last queue scan time > allowed cache time.
1283 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1284 * This last test picks up machines for which the clock has been moved
1285 * forward, an lpq scan done and then the clock moved back. Otherwise
1286 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1289 if (last_qscan_time == ((time_t)-1)
1290 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1291 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1293 uint32 u;
1294 time_t msg_pending_time;
1296 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1297 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1298 sharename, (int)last_qscan_time, (int)time_now,
1299 (int)lp_lpqcachetime() ));
1301 /* check if another smbd has already sent a message to update the
1302 queue. Give the pending message one minute to clear and
1303 then send another message anyways. Make sure to check for
1304 clocks that have been run forward and then back again. */
1306 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1308 if ( check_pending
1309 && tdb_fetch_uint32( pdb->tdb, key, &u )
1310 && (msg_pending_time=u) > 0
1311 && msg_pending_time <= time_now
1312 && (time_now - msg_pending_time) < 60 )
1314 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1315 sharename));
1316 goto done;
1319 result = True;
1322 done:
1323 release_print_db(pdb);
1324 return result;
1327 /****************************************************************************
1328 main work for updating the lpq cache for a printer queue
1329 ****************************************************************************/
1331 static void print_queue_update_internal( struct tevent_context *ev,
1332 struct messaging_context *msg_ctx,
1333 const char *sharename,
1334 struct printif *current_printif,
1335 char *lpq_command, char *lprm_command )
1337 int i, qcount;
1338 print_queue_struct *queue = NULL;
1339 print_status_struct status;
1340 print_status_struct old_status;
1341 struct printjob *pjob;
1342 struct traverse_struct tstruct;
1343 TDB_DATA data, key;
1344 TDB_DATA jcdata;
1345 fstring keystr, cachestr;
1346 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1348 if (!pdb) {
1349 return;
1352 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1353 sharename, current_printif->type, lpq_command));
1356 * Update the cache time FIRST ! Stops others even
1357 * attempting to get the lock and doing this
1358 * if the lpq takes a long time.
1361 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1362 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1364 /* get the current queue using the appropriate interface */
1365 ZERO_STRUCT(status);
1367 qcount = (*(current_printif->queue_get))(sharename,
1368 current_printif->type,
1369 lpq_command, &queue, &status);
1371 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1372 qcount, (qcount != 1) ? "s" : "", sharename));
1374 /* Sort the queue by submission time otherwise they are displayed
1375 in hash order. */
1377 TYPESAFE_QSORT(queue, qcount, printjob_comp);
1380 any job in the internal database that is marked as spooled
1381 and doesn't exist in the system queue is considered finished
1382 and removed from the database
1384 any job in the system database but not in the internal database
1385 is added as a unix job
1387 fill in any system job numbers as we go
1390 jcdata = get_jobs_added_data(pdb);
1392 for (i=0; i<qcount; i++) {
1393 uint32 jobid = print_parse_jobid(queue[i].fs_file);
1395 if (jobid == (uint32)-1) {
1396 /* assume its a unix print job */
1397 print_unix_job(ev, msg_ctx,
1398 sharename, &queue[i], jobid);
1399 continue;
1402 /* we have an active SMB print job - update its status */
1403 pjob = print_job_find(sharename, jobid);
1404 if (!pjob) {
1405 /* err, somethings wrong. Probably smbd was restarted
1406 with jobs in the queue. All we can do is treat them
1407 like unix jobs. Pity. */
1408 print_unix_job(ev, msg_ctx,
1409 sharename, &queue[i], jobid);
1410 continue;
1413 pjob->sysjob = queue[i].job;
1415 /* don't reset the status on jobs to be deleted */
1417 if ( pjob->status != LPQ_DELETING )
1418 pjob->status = queue[i].status;
1420 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
1422 check_job_added(sharename, jcdata, jobid);
1425 SAFE_FREE(jcdata.dptr);
1427 /* now delete any queued entries that don't appear in the
1428 system queue */
1429 tstruct.queue = queue;
1430 tstruct.qcount = qcount;
1431 tstruct.snum = -1;
1432 tstruct.total_jobs = 0;
1433 tstruct.lpq_time = time(NULL);
1434 tstruct.sharename = sharename;
1435 tstruct.lprm_command = lprm_command;
1436 tstruct.print_if = current_printif;
1437 tstruct.ev = ev;
1438 tstruct.msg_ctx = msg_ctx;
1440 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1442 /* Store the linearised queue, max jobs only. */
1443 store_queue_struct(pdb, &tstruct);
1445 SAFE_FREE(tstruct.queue);
1447 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1448 sharename, tstruct.total_jobs ));
1450 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1452 get_queue_status(sharename, &old_status);
1453 if (old_status.qcount != qcount)
1454 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1455 old_status.qcount, qcount, sharename));
1457 /* store the new queue status structure */
1458 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1459 key = string_tdb_data(keystr);
1461 status.qcount = qcount;
1462 data.dptr = (uint8 *)&status;
1463 data.dsize = sizeof(status);
1464 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1467 * Update the cache time again. We want to do this call
1468 * as little as possible...
1471 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1472 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1474 /* clear the msg pending record for this queue */
1476 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1478 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1479 /* log a message but continue on */
1481 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1482 sharename));
1485 release_print_db( pdb );
1487 return;
1490 /****************************************************************************
1491 Update the internal database from the system print queue for a queue.
1492 obtain a lock on the print queue before proceeding (needed when mutiple
1493 smbd processes maytry to update the lpq cache concurrently).
1494 ****************************************************************************/
1496 static void print_queue_update_with_lock( struct tevent_context *ev,
1497 struct messaging_context *msg_ctx,
1498 const char *sharename,
1499 struct printif *current_printif,
1500 char *lpq_command, char *lprm_command )
1502 fstring keystr;
1503 struct tdb_print_db *pdb;
1505 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1506 pdb = get_print_db_byname(sharename);
1507 if (!pdb)
1508 return;
1510 if ( !print_cache_expired(sharename, False) ) {
1511 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1512 release_print_db(pdb);
1513 return;
1517 * Check to see if someone else is doing this update.
1518 * This is essentially a mutex on the update.
1521 if (get_updating_pid(sharename) != -1) {
1522 release_print_db(pdb);
1523 return;
1526 /* Lock the queue for the database update */
1528 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1529 /* Only wait 10 seconds for this. */
1530 if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) != 0) {
1531 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1532 release_print_db(pdb);
1533 return;
1537 * Ensure that no one else got in here.
1538 * If the updating pid is still -1 then we are
1539 * the winner.
1542 if (get_updating_pid(sharename) != -1) {
1544 * Someone else is doing the update, exit.
1546 tdb_unlock_bystring(pdb->tdb, keystr);
1547 release_print_db(pdb);
1548 return;
1552 * We're going to do the update ourselves.
1555 /* Tell others we're doing the update. */
1556 set_updating_pid(sharename, True);
1559 * Allow others to enter and notice we're doing
1560 * the update.
1563 tdb_unlock_bystring(pdb->tdb, keystr);
1565 /* do the main work now */
1567 print_queue_update_internal(ev, msg_ctx,
1568 sharename, current_printif,
1569 lpq_command, lprm_command);
1571 /* Delete our pid from the db. */
1572 set_updating_pid(sharename, False);
1573 release_print_db(pdb);
1576 /****************************************************************************
1577 this is the receive function of the background lpq updater
1578 ****************************************************************************/
1579 void print_queue_receive(struct messaging_context *msg,
1580 void *private_data,
1581 uint32_t msg_type,
1582 struct server_id server_id,
1583 DATA_BLOB *data)
1585 fstring sharename;
1586 char *lpqcommand = NULL, *lprmcommand = NULL;
1587 int printing_type;
1588 size_t len;
1590 len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1591 sharename,
1592 &printing_type,
1593 &lpqcommand,
1594 &lprmcommand );
1596 if ( len == -1 ) {
1597 SAFE_FREE(lpqcommand);
1598 SAFE_FREE(lprmcommand);
1599 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1600 return;
1603 print_queue_update_with_lock(server_event_context(), msg, sharename,
1604 get_printer_fns_from_type((enum printing_types)printing_type),
1605 lpqcommand, lprmcommand );
1607 SAFE_FREE(lpqcommand);
1608 SAFE_FREE(lprmcommand);
1609 return;
1612 /****************************************************************************
1613 update the internal database from the system print queue for a queue
1614 ****************************************************************************/
1616 extern pid_t background_lpq_updater_pid;
1618 static void print_queue_update(struct messaging_context *msg_ctx,
1619 int snum, bool force)
1621 fstring key;
1622 fstring sharename;
1623 char *lpqcommand = NULL;
1624 char *lprmcommand = NULL;
1625 uint8 *buffer = NULL;
1626 size_t len = 0;
1627 size_t newlen;
1628 struct tdb_print_db *pdb;
1629 int type;
1630 struct printif *current_printif;
1631 TALLOC_CTX *ctx = talloc_tos();
1633 fstrcpy( sharename, lp_const_servicename(snum));
1635 /* don't strip out characters like '$' from the printername */
1637 lpqcommand = talloc_string_sub2(ctx,
1638 lp_lpqcommand(snum),
1639 "%p",
1640 lp_printername(snum),
1641 false, false, false);
1642 if (!lpqcommand) {
1643 return;
1645 lpqcommand = talloc_sub_advanced(ctx,
1646 lp_servicename(snum),
1647 current_user_info.unix_name,
1649 current_user.ut.gid,
1650 get_current_username(),
1651 current_user_info.domain,
1652 lpqcommand);
1653 if (!lpqcommand) {
1654 return;
1657 lprmcommand = talloc_string_sub2(ctx,
1658 lp_lprmcommand(snum),
1659 "%p",
1660 lp_printername(snum),
1661 false, false, false);
1662 if (!lprmcommand) {
1663 return;
1665 lprmcommand = talloc_sub_advanced(ctx,
1666 lp_servicename(snum),
1667 current_user_info.unix_name,
1669 current_user.ut.gid,
1670 get_current_username(),
1671 current_user_info.domain,
1672 lprmcommand);
1673 if (!lprmcommand) {
1674 return;
1678 * Make sure that the background queue process exists.
1679 * Otherwise just do the update ourselves
1682 if ( force || background_lpq_updater_pid == -1 ) {
1683 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1684 current_printif = get_printer_fns( snum );
1685 print_queue_update_with_lock(server_event_context(), msg_ctx,
1686 sharename, current_printif,
1687 lpqcommand, lprmcommand);
1689 return;
1692 type = lp_printing(snum);
1694 /* get the length */
1696 len = tdb_pack( NULL, 0, "fdPP",
1697 sharename,
1698 type,
1699 lpqcommand,
1700 lprmcommand );
1702 buffer = SMB_XMALLOC_ARRAY( uint8, len );
1704 /* now pack the buffer */
1705 newlen = tdb_pack( buffer, len, "fdPP",
1706 sharename,
1707 type,
1708 lpqcommand,
1709 lprmcommand );
1711 SMB_ASSERT( newlen == len );
1713 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1714 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1715 sharename, type, lpqcommand, lprmcommand ));
1717 /* here we set a msg pending record for other smbd processes
1718 to throttle the number of duplicate print_queue_update msgs
1719 sent. */
1721 pdb = get_print_db_byname(sharename);
1722 if (!pdb) {
1723 SAFE_FREE(buffer);
1724 return;
1727 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1729 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1730 /* log a message but continue on */
1732 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1733 sharename));
1736 release_print_db( pdb );
1738 /* finally send the message */
1740 messaging_send_buf(msg_ctx, pid_to_procid(background_lpq_updater_pid),
1741 MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1743 SAFE_FREE( buffer );
1745 return;
1748 /****************************************************************************
1749 Create/Update an entry in the print tdb that will allow us to send notify
1750 updates only to interested smbd's.
1751 ****************************************************************************/
1753 bool print_notify_register_pid(int snum)
1755 TDB_DATA data;
1756 struct tdb_print_db *pdb = NULL;
1757 TDB_CONTEXT *tdb = NULL;
1758 const char *printername;
1759 uint32_t mypid = (uint32_t)getpid();
1760 bool ret = False;
1761 size_t i;
1763 /* if (snum == -1), then the change notify request was
1764 on a print server handle and we need to register on
1765 all print queus */
1767 if (snum == -1)
1769 int num_services = lp_numservices();
1770 int idx;
1772 for ( idx=0; idx<num_services; idx++ ) {
1773 if (lp_snum_ok(idx) && lp_print_ok(idx) )
1774 print_notify_register_pid(idx);
1777 return True;
1779 else /* register for a specific printer */
1781 printername = lp_const_servicename(snum);
1782 pdb = get_print_db_byname(printername);
1783 if (!pdb)
1784 return False;
1785 tdb = pdb->tdb;
1788 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) != 0) {
1789 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1790 printername));
1791 if (pdb)
1792 release_print_db(pdb);
1793 return False;
1796 data = get_printer_notify_pid_list( tdb, printername, True );
1798 /* Add ourselves and increase the refcount. */
1800 for (i = 0; i < data.dsize; i += 8) {
1801 if (IVAL(data.dptr,i) == mypid) {
1802 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1803 SIVAL(data.dptr, i+4, new_refcount);
1804 break;
1808 if (i == data.dsize) {
1809 /* We weren't in the list. Realloc. */
1810 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1811 if (!data.dptr) {
1812 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1813 printername));
1814 goto done;
1816 data.dsize += 8;
1817 SIVAL(data.dptr,data.dsize - 8,mypid);
1818 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1821 /* Store back the record. */
1822 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) != 0) {
1823 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1824 list for printer %s\n", printername));
1825 goto done;
1828 ret = True;
1830 done:
1832 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1833 if (pdb)
1834 release_print_db(pdb);
1835 SAFE_FREE(data.dptr);
1836 return ret;
1839 /****************************************************************************
1840 Update an entry in the print tdb that will allow us to send notify
1841 updates only to interested smbd's.
1842 ****************************************************************************/
1844 bool print_notify_deregister_pid(int snum)
1846 TDB_DATA data;
1847 struct tdb_print_db *pdb = NULL;
1848 TDB_CONTEXT *tdb = NULL;
1849 const char *printername;
1850 uint32_t mypid = (uint32_t)getpid();
1851 size_t i;
1852 bool ret = False;
1854 /* if ( snum == -1 ), we are deregister a print server handle
1855 which means to deregister on all print queues */
1857 if (snum == -1)
1859 int num_services = lp_numservices();
1860 int idx;
1862 for ( idx=0; idx<num_services; idx++ ) {
1863 if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1864 print_notify_deregister_pid(idx);
1867 return True;
1869 else /* deregister a specific printer */
1871 printername = lp_const_servicename(snum);
1872 pdb = get_print_db_byname(printername);
1873 if (!pdb)
1874 return False;
1875 tdb = pdb->tdb;
1878 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) != 0) {
1879 DEBUG(0,("print_notify_register_pid: Failed to lock \
1880 printer %s database\n", printername));
1881 if (pdb)
1882 release_print_db(pdb);
1883 return False;
1886 data = get_printer_notify_pid_list( tdb, printername, True );
1888 /* Reduce refcount. Remove ourselves if zero. */
1890 for (i = 0; i < data.dsize; ) {
1891 if (IVAL(data.dptr,i) == mypid) {
1892 uint32 refcount = IVAL(data.dptr, i+4);
1894 refcount--;
1896 if (refcount == 0) {
1897 if (data.dsize - i > 8)
1898 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1899 data.dsize -= 8;
1900 continue;
1902 SIVAL(data.dptr, i+4, refcount);
1905 i += 8;
1908 if (data.dsize == 0)
1909 SAFE_FREE(data.dptr);
1911 /* Store back the record. */
1912 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) != 0) {
1913 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1914 list for printer %s\n", printername));
1915 goto done;
1918 ret = True;
1920 done:
1922 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1923 if (pdb)
1924 release_print_db(pdb);
1925 SAFE_FREE(data.dptr);
1926 return ret;
1929 /****************************************************************************
1930 Check if a jobid is valid. It is valid if it exists in the database.
1931 ****************************************************************************/
1933 bool print_job_exists(const char* sharename, uint32 jobid)
1935 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1936 bool ret;
1937 uint32_t tmp;
1939 if (!pdb)
1940 return False;
1941 ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
1942 release_print_db(pdb);
1943 return ret;
1946 /****************************************************************************
1947 Give the filename used for a jobid.
1948 Only valid for the process doing the spooling and when the job
1949 has not been spooled.
1950 ****************************************************************************/
1952 char *print_job_fname(const char* sharename, uint32 jobid)
1954 struct printjob *pjob = print_job_find(sharename, jobid);
1955 if (!pjob || pjob->spooled || pjob->pid != getpid())
1956 return NULL;
1957 return pjob->filename;
1961 /****************************************************************************
1962 Give the filename used for a jobid.
1963 Only valid for the process doing the spooling and when the job
1964 has not been spooled.
1965 ****************************************************************************/
1967 struct spoolss_DeviceMode *print_job_devmode(const char* sharename, uint32 jobid)
1969 struct printjob *pjob = print_job_find(sharename, jobid);
1971 if ( !pjob )
1972 return NULL;
1974 return pjob->devmode;
1977 /****************************************************************************
1978 Set the name of a job. Only possible for owner.
1979 ****************************************************************************/
1981 bool print_job_set_name(struct tevent_context *ev,
1982 struct messaging_context *msg_ctx,
1983 const char *sharename, uint32 jobid, const char *name)
1985 struct printjob *pjob;
1987 pjob = print_job_find(sharename, jobid);
1988 if (!pjob || pjob->pid != getpid())
1989 return False;
1991 fstrcpy(pjob->jobname, name);
1992 return pjob_store(ev, msg_ctx, sharename, jobid, pjob);
1995 /****************************************************************************
1996 Get the name of a job. Only possible for owner.
1997 ****************************************************************************/
1999 bool print_job_get_name(TALLOC_CTX *mem_ctx, const char *sharename, uint32_t jobid, char **name)
2001 struct printjob *pjob;
2003 pjob = print_job_find(sharename, jobid);
2004 if (!pjob || pjob->pid != getpid()) {
2005 return false;
2008 *name = talloc_strdup(mem_ctx, pjob->jobname);
2009 if (!*name) {
2010 return false;
2013 return true;
2017 /***************************************************************************
2018 Remove a jobid from the 'jobs added' list.
2019 ***************************************************************************/
2021 static bool remove_from_jobs_added(const char* sharename, uint32 jobid)
2023 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2024 TDB_DATA data, key;
2025 size_t job_count, i;
2026 bool ret = False;
2027 bool gotlock = False;
2029 if (!pdb) {
2030 return False;
2033 ZERO_STRUCT(data);
2035 key = string_tdb_data("INFO/jobs_added");
2037 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) != 0)
2038 goto out;
2040 gotlock = True;
2042 data = tdb_fetch_compat(pdb->tdb, key);
2044 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
2045 goto out;
2047 job_count = data.dsize / 4;
2048 for (i = 0; i < job_count; i++) {
2049 uint32 ch_jobid;
2051 ch_jobid = IVAL(data.dptr, i*4);
2052 if (ch_jobid == jobid) {
2053 if (i < job_count -1 )
2054 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
2055 data.dsize -= 4;
2056 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) != 0)
2057 goto out;
2058 break;
2062 ret = True;
2063 out:
2065 if (gotlock)
2066 tdb_chainunlock(pdb->tdb, key);
2067 SAFE_FREE(data.dptr);
2068 release_print_db(pdb);
2069 if (ret)
2070 DEBUG(10,("remove_from_jobs_added: removed jobid %u\n", (unsigned int)jobid ));
2071 else
2072 DEBUG(10,("remove_from_jobs_added: Failed to remove jobid %u\n", (unsigned int)jobid ));
2073 return ret;
2076 /****************************************************************************
2077 Delete a print job - don't update queue.
2078 ****************************************************************************/
2080 static bool print_job_delete1(struct tevent_context *ev,
2081 struct messaging_context *msg_ctx,
2082 int snum, uint32 jobid)
2084 const char* sharename = lp_const_servicename(snum);
2085 struct printjob *pjob = print_job_find(sharename, jobid);
2086 int result = 0;
2087 struct printif *current_printif = get_printer_fns( snum );
2089 if (!pjob)
2090 return False;
2093 * If already deleting just return.
2096 if (pjob->status == LPQ_DELETING)
2097 return True;
2099 /* Hrm - we need to be able to cope with deleting a job before it
2100 has reached the spooler. Just mark it as LPQ_DELETING and
2101 let the print_queue_update() code rmeove the record */
2104 if (pjob->sysjob == -1) {
2105 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
2108 /* Set the tdb entry to be deleting. */
2110 pjob->status = LPQ_DELETING;
2111 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2113 if (pjob->spooled && pjob->sysjob != -1)
2115 result = (*(current_printif->job_delete))(
2116 lp_printername(snum),
2117 lp_lprmcommand(snum),
2118 pjob);
2120 /* Delete the tdb entry if the delete succeeded or the job hasn't
2121 been spooled. */
2123 if (result == 0) {
2124 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2125 int njobs = 1;
2127 if (!pdb)
2128 return False;
2129 pjob_delete(ev, msg_ctx, sharename, jobid);
2130 /* Ensure we keep a rough count of the number of total jobs... */
2131 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
2132 release_print_db(pdb);
2136 remove_from_jobs_added( sharename, jobid );
2138 return (result == 0);
2141 /****************************************************************************
2142 Return true if the current user owns the print job.
2143 ****************************************************************************/
2145 static bool is_owner(const struct auth_session_info *server_info,
2146 const char *servicename,
2147 uint32 jobid)
2149 struct printjob *pjob = print_job_find(servicename, jobid);
2151 if (!pjob || !server_info)
2152 return False;
2154 return strequal(pjob->user, server_info->unix_info->sanitized_username);
2157 /****************************************************************************
2158 Delete a print job.
2159 ****************************************************************************/
2161 WERROR print_job_delete(const struct auth_session_info *server_info,
2162 struct messaging_context *msg_ctx,
2163 int snum, uint32_t jobid)
2165 const char* sharename = lp_const_servicename(snum);
2166 struct printjob *pjob;
2167 bool owner;
2168 char *fname;
2170 owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2172 /* Check access against security descriptor or whether the user
2173 owns their job. */
2175 if (!owner &&
2176 !print_access_check(server_info, msg_ctx, snum,
2177 JOB_ACCESS_ADMINISTER)) {
2178 DEBUG(3, ("delete denied by security descriptor\n"));
2180 /* BEGIN_ADMIN_LOG */
2181 sys_adminlog( LOG_ERR,
2182 "Permission denied-- user not allowed to delete, \
2183 pause, or resume print job. User name: %s. Printer name: %s.",
2184 uidtoname(server_info->unix_token->uid),
2185 lp_printername(snum) );
2186 /* END_ADMIN_LOG */
2188 return WERR_ACCESS_DENIED;
2192 * get the spooled filename of the print job
2193 * if this works, then the file has not been spooled
2194 * to the underlying print system. Just delete the
2195 * spool file & return.
2198 fname = print_job_fname(sharename, jobid);
2199 if (fname != NULL) {
2200 /* remove the spool file */
2201 DEBUG(10, ("print_job_delete: "
2202 "Removing spool file [%s]\n", fname));
2203 if (unlink(fname) == -1) {
2204 return map_werror_from_unix(errno);
2208 if (!print_job_delete1(server_event_context(), msg_ctx, snum, jobid)) {
2209 return WERR_ACCESS_DENIED;
2212 /* force update the database and say the delete failed if the
2213 job still exists */
2215 print_queue_update(msg_ctx, snum, True);
2217 pjob = print_job_find(sharename, jobid);
2218 if (pjob && (pjob->status != LPQ_DELETING)) {
2219 return WERR_ACCESS_DENIED;
2222 return WERR_PRINTER_HAS_JOBS_QUEUED;
2225 /****************************************************************************
2226 Pause a job.
2227 ****************************************************************************/
2229 bool print_job_pause(const struct auth_session_info *server_info,
2230 struct messaging_context *msg_ctx,
2231 int snum, uint32 jobid, WERROR *errcode)
2233 const char* sharename = lp_const_servicename(snum);
2234 struct printjob *pjob;
2235 int ret = -1;
2236 struct printif *current_printif = get_printer_fns( snum );
2238 pjob = print_job_find(sharename, jobid);
2240 if (!pjob || !server_info) {
2241 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2242 (unsigned int)jobid ));
2243 return False;
2246 if (!pjob->spooled || pjob->sysjob == -1) {
2247 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2248 (int)pjob->sysjob, (unsigned int)jobid ));
2249 return False;
2252 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2253 !print_access_check(server_info, msg_ctx, snum,
2254 JOB_ACCESS_ADMINISTER)) {
2255 DEBUG(3, ("pause denied by security descriptor\n"));
2257 /* BEGIN_ADMIN_LOG */
2258 sys_adminlog( LOG_ERR,
2259 "Permission denied-- user not allowed to delete, \
2260 pause, or resume print job. User name: %s. Printer name: %s.",
2261 uidtoname(server_info->unix_token->uid),
2262 lp_printername(snum) );
2263 /* END_ADMIN_LOG */
2265 *errcode = WERR_ACCESS_DENIED;
2266 return False;
2269 /* need to pause the spooled entry */
2270 ret = (*(current_printif->job_pause))(snum, pjob);
2272 if (ret != 0) {
2273 *errcode = WERR_INVALID_PARAM;
2274 return False;
2277 /* force update the database */
2278 print_cache_flush(lp_const_servicename(snum));
2280 /* Send a printer notify message */
2282 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2283 JOB_STATUS_PAUSED);
2285 /* how do we tell if this succeeded? */
2287 return True;
2290 /****************************************************************************
2291 Resume a job.
2292 ****************************************************************************/
2294 bool print_job_resume(const struct auth_session_info *server_info,
2295 struct messaging_context *msg_ctx,
2296 int snum, uint32 jobid, WERROR *errcode)
2298 const char *sharename = lp_const_servicename(snum);
2299 struct printjob *pjob;
2300 int ret;
2301 struct printif *current_printif = get_printer_fns( snum );
2303 pjob = print_job_find(sharename, jobid);
2305 if (!pjob || !server_info) {
2306 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2307 (unsigned int)jobid ));
2308 return False;
2311 if (!pjob->spooled || pjob->sysjob == -1) {
2312 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2313 (int)pjob->sysjob, (unsigned int)jobid ));
2314 return False;
2317 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2318 !print_access_check(server_info, msg_ctx, snum,
2319 JOB_ACCESS_ADMINISTER)) {
2320 DEBUG(3, ("resume denied by security descriptor\n"));
2321 *errcode = WERR_ACCESS_DENIED;
2323 /* BEGIN_ADMIN_LOG */
2324 sys_adminlog( LOG_ERR,
2325 "Permission denied-- user not allowed to delete, \
2326 pause, or resume print job. User name: %s. Printer name: %s.",
2327 uidtoname(server_info->unix_token->uid),
2328 lp_printername(snum) );
2329 /* END_ADMIN_LOG */
2330 return False;
2333 ret = (*(current_printif->job_resume))(snum, pjob);
2335 if (ret != 0) {
2336 *errcode = WERR_INVALID_PARAM;
2337 return False;
2340 /* force update the database */
2341 print_cache_flush(lp_const_servicename(snum));
2343 /* Send a printer notify message */
2345 notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2346 JOB_STATUS_QUEUED);
2348 return True;
2351 /****************************************************************************
2352 Write to a print file.
2353 ****************************************************************************/
2355 ssize_t print_job_write(struct tevent_context *ev,
2356 struct messaging_context *msg_ctx,
2357 int snum, uint32 jobid, const char *buf, size_t size)
2359 const char* sharename = lp_const_servicename(snum);
2360 ssize_t return_code;
2361 struct printjob *pjob;
2363 pjob = print_job_find(sharename, jobid);
2365 if (!pjob)
2366 return -1;
2367 /* don't allow another process to get this info - it is meaningless */
2368 if (pjob->pid != getpid())
2369 return -1;
2371 /* if SMBD is spooling this can't be allowed */
2372 if (pjob->status == PJOB_SMBD_SPOOLING) {
2373 return -1;
2376 return_code = write_data(pjob->fd, buf, size);
2378 if (return_code>0) {
2379 pjob->size += size;
2380 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2382 return return_code;
2385 /****************************************************************************
2386 Get the queue status - do not update if db is out of date.
2387 ****************************************************************************/
2389 static int get_queue_status(const char* sharename, print_status_struct *status)
2391 fstring keystr;
2392 TDB_DATA data;
2393 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2394 int len;
2396 if (status) {
2397 ZERO_STRUCTP(status);
2400 if (!pdb)
2401 return 0;
2403 if (status) {
2404 fstr_sprintf(keystr, "STATUS/%s", sharename);
2405 data = tdb_fetch_compat(pdb->tdb, string_tdb_data(keystr));
2406 if (data.dptr) {
2407 if (data.dsize == sizeof(print_status_struct))
2408 /* this memcpy is ok since the status struct was
2409 not packed before storing it in the tdb */
2410 memcpy(status, data.dptr, sizeof(print_status_struct));
2411 SAFE_FREE(data.dptr);
2414 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2415 release_print_db(pdb);
2416 return (len == -1 ? 0 : len);
2419 /****************************************************************************
2420 Determine the number of jobs in a queue.
2421 ****************************************************************************/
2423 int print_queue_length(struct messaging_context *msg_ctx, int snum,
2424 print_status_struct *pstatus)
2426 const char* sharename = lp_const_servicename( snum );
2427 print_status_struct status;
2428 int len;
2430 ZERO_STRUCT( status );
2432 /* make sure the database is up to date */
2433 if (print_cache_expired(lp_const_servicename(snum), True))
2434 print_queue_update(msg_ctx, snum, False);
2436 /* also fetch the queue status */
2437 memset(&status, 0, sizeof(status));
2438 len = get_queue_status(sharename, &status);
2440 if (pstatus)
2441 *pstatus = status;
2443 return len;
2446 /***************************************************************************
2447 Allocate a jobid. Hold the lock for as short a time as possible.
2448 ***************************************************************************/
2450 static WERROR allocate_print_jobid(struct tdb_print_db *pdb, int snum,
2451 const char *sharename, uint32 *pjobid)
2453 int i;
2454 uint32 jobid;
2455 enum TDB_ERROR terr;
2456 int ret;
2458 *pjobid = (uint32)-1;
2460 for (i = 0; i < 3; i++) {
2461 /* Lock the database - only wait 20 seconds. */
2462 ret = tdb_lock_bystring_with_timeout(pdb->tdb,
2463 "INFO/nextjob", 20);
2464 if (ret != 0) {
2465 DEBUG(0, ("allocate_print_jobid: "
2466 "Failed to lock printing database %s\n",
2467 sharename));
2468 terr = tdb_error(pdb->tdb);
2469 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2472 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2473 terr = tdb_error(pdb->tdb);
2474 if (terr != TDB_ERR_NOEXIST) {
2475 DEBUG(0, ("allocate_print_jobid: "
2476 "Failed to fetch INFO/nextjob "
2477 "for print queue %s\n", sharename));
2478 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2479 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2481 DEBUG(10, ("allocate_print_jobid: "
2482 "No existing jobid in %s\n", sharename));
2483 jobid = 0;
2486 DEBUG(10, ("allocate_print_jobid: "
2487 "Read jobid %u from %s\n", jobid, sharename));
2489 jobid = NEXT_JOBID(jobid);
2491 ret = tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid);
2492 if (ret != 0) {
2493 terr = tdb_error(pdb->tdb);
2494 DEBUG(3, ("allocate_print_jobid: "
2495 "Failed to store INFO/nextjob.\n"));
2496 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2497 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2500 /* We've finished with the INFO/nextjob lock. */
2501 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2503 if (!print_job_exists(sharename, jobid)) {
2504 break;
2506 DEBUG(10, ("allocate_print_jobid: "
2507 "Found jobid %u in %s\n", jobid, sharename));
2510 if (i > 2) {
2511 DEBUG(0, ("allocate_print_jobid: "
2512 "Failed to allocate a print job for queue %s\n",
2513 sharename));
2514 /* Probably full... */
2515 return WERR_NO_SPOOL_SPACE;
2518 /* Store a dummy placeholder. */
2520 uint32_t tmp;
2521 TDB_DATA dum;
2522 dum.dptr = NULL;
2523 dum.dsize = 0;
2524 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2525 TDB_INSERT) != 0) {
2526 DEBUG(3, ("allocate_print_jobid: "
2527 "jobid (%d) failed to store placeholder.\n",
2528 jobid ));
2529 terr = tdb_error(pdb->tdb);
2530 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2534 *pjobid = jobid;
2535 return WERR_OK;
2538 /***************************************************************************
2539 Append a jobid to the 'jobs added' list.
2540 ***************************************************************************/
2542 static bool add_to_jobs_added(struct tdb_print_db *pdb, uint32 jobid)
2544 TDB_DATA data;
2545 uint32 store_jobid;
2547 SIVAL(&store_jobid, 0, jobid);
2548 data.dptr = (uint8 *)&store_jobid;
2549 data.dsize = 4;
2551 DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
2553 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_added"),
2554 data) == 0);
2558 /***************************************************************************
2559 Do all checks needed to determine if we can start a job.
2560 ***************************************************************************/
2562 static WERROR print_job_checks(const struct auth_session_info *server_info,
2563 struct messaging_context *msg_ctx,
2564 int snum, int *njobs)
2566 const char *sharename = lp_const_servicename(snum);
2567 uint64_t dspace, dsize;
2568 uint64_t minspace;
2569 int ret;
2571 if (!print_access_check(server_info, msg_ctx, snum,
2572 PRINTER_ACCESS_USE)) {
2573 DEBUG(3, ("print_job_checks: "
2574 "job start denied by security descriptor\n"));
2575 return WERR_ACCESS_DENIED;
2578 if (!print_time_access_check(server_info, msg_ctx, sharename)) {
2579 DEBUG(3, ("print_job_checks: "
2580 "job start denied by time check\n"));
2581 return WERR_ACCESS_DENIED;
2584 /* see if we have sufficient disk space */
2585 if (lp_minprintspace(snum)) {
2586 minspace = lp_minprintspace(snum);
2587 ret = sys_fsusage(lp_pathname(snum), &dspace, &dsize);
2588 if (ret == 0 && dspace < 2*minspace) {
2589 DEBUG(3, ("print_job_checks: "
2590 "disk space check failed.\n"));
2591 return WERR_NO_SPOOL_SPACE;
2595 /* for autoloaded printers, check that the printcap entry still exists */
2596 if (lp_autoloaded(snum) && !pcap_printername_ok(sharename)) {
2597 DEBUG(3, ("print_job_checks: printer name %s check failed.\n",
2598 sharename));
2599 return WERR_ACCESS_DENIED;
2602 /* Insure the maximum queue size is not violated */
2603 *njobs = print_queue_length(msg_ctx, snum, NULL);
2604 if (*njobs > lp_maxprintjobs(snum)) {
2605 DEBUG(3, ("print_job_checks: Queue %s number of jobs (%d) "
2606 "larger than max printjobs per queue (%d).\n",
2607 sharename, *njobs, lp_maxprintjobs(snum)));
2608 return WERR_NO_SPOOL_SPACE;
2611 return WERR_OK;
2614 /***************************************************************************
2615 Create a job file.
2616 ***************************************************************************/
2618 static WERROR print_job_spool_file(int snum, uint32_t jobid,
2619 const char *output_file,
2620 struct printjob *pjob)
2622 WERROR werr;
2623 SMB_STRUCT_STAT st;
2624 const char *path;
2625 int len;
2627 /* if this file is within the printer path, it means that smbd
2628 * is spooling it and will pass us control when it is finished.
2629 * Verify that the file name is ok, within path, and it is
2630 * already already there */
2631 if (output_file) {
2632 path = lp_pathname(snum);
2633 len = strlen(path);
2634 if (strncmp(output_file, path, len) == 0 &&
2635 (output_file[len - 1] == '/' || output_file[len] == '/')) {
2637 /* verify path is not too long */
2638 if (strlen(output_file) >= sizeof(pjob->filename)) {
2639 return WERR_INVALID_NAME;
2642 /* verify that the file exists */
2643 if (sys_stat(output_file, &st, false) != 0) {
2644 return WERR_INVALID_NAME;
2647 fstrcpy(pjob->filename, output_file);
2649 DEBUG(3, ("print_job_spool_file:"
2650 "External spooling activated"));
2652 /* we do not open the file until spooling is done */
2653 pjob->fd = -1;
2654 pjob->status = PJOB_SMBD_SPOOLING;
2656 return WERR_OK;
2660 slprintf(pjob->filename, sizeof(pjob->filename)-1,
2661 "%s/%s%.8u.XXXXXX", lp_pathname(snum),
2662 PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2663 pjob->fd = mkstemp(pjob->filename);
2665 if (pjob->fd == -1) {
2666 werr = map_werror_from_unix(errno);
2667 if (W_ERROR_EQUAL(werr, WERR_ACCESS_DENIED)) {
2668 /* Common setup error, force a report. */
2669 DEBUG(0, ("print_job_spool_file: "
2670 "insufficient permissions to open spool "
2671 "file %s.\n", pjob->filename));
2672 } else {
2673 /* Normal case, report at level 3 and above. */
2674 DEBUG(3, ("print_job_spool_file: "
2675 "can't open spool file %s\n",
2676 pjob->filename));
2678 return werr;
2681 return WERR_OK;
2684 /***************************************************************************
2685 Start spooling a job - return the jobid.
2686 ***************************************************************************/
2688 WERROR print_job_start(const struct auth_session_info *server_info,
2689 struct messaging_context *msg_ctx,
2690 const char *clientmachine,
2691 int snum, const char *docname, const char *filename,
2692 struct spoolss_DeviceMode *devmode, uint32_t *_jobid)
2694 uint32_t jobid;
2695 char *path;
2696 struct printjob pjob;
2697 const char *sharename = lp_const_servicename(snum);
2698 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2699 int njobs;
2700 WERROR werr;
2702 if (!pdb) {
2703 return WERR_INTERNAL_DB_CORRUPTION;
2706 path = lp_pathname(snum);
2708 werr = print_job_checks(server_info, msg_ctx, snum, &njobs);
2709 if (!W_ERROR_IS_OK(werr)) {
2710 release_print_db(pdb);
2711 return werr;
2714 DEBUG(10, ("print_job_start: "
2715 "Queue %s number of jobs (%d), max printjobs = %d\n",
2716 sharename, njobs, lp_maxprintjobs(snum)));
2718 werr = allocate_print_jobid(pdb, snum, sharename, &jobid);
2719 if (!W_ERROR_IS_OK(werr)) {
2720 goto fail;
2723 /* create the database entry */
2725 ZERO_STRUCT(pjob);
2727 pjob.pid = getpid();
2728 pjob.jobid = jobid;
2729 pjob.sysjob = -1;
2730 pjob.fd = -1;
2731 pjob.starttime = time(NULL);
2732 pjob.status = LPQ_SPOOLING;
2733 pjob.size = 0;
2734 pjob.spooled = False;
2735 pjob.smbjob = True;
2736 pjob.devmode = devmode;
2738 fstrcpy(pjob.jobname, docname);
2740 fstrcpy(pjob.clientmachine, clientmachine);
2742 fstrcpy(pjob.user, lp_printjob_username(snum));
2743 standard_sub_advanced(sharename, server_info->unix_info->sanitized_username,
2744 path, server_info->unix_token->gid,
2745 server_info->unix_info->sanitized_username,
2746 server_info->info->domain_name,
2747 pjob.user, sizeof(pjob.user));
2749 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2751 /* we have a job entry - now create the spool file */
2752 werr = print_job_spool_file(snum, jobid, filename, &pjob);
2753 if (!W_ERROR_IS_OK(werr)) {
2754 goto fail;
2757 pjob_store(server_event_context(), msg_ctx, sharename, jobid, &pjob);
2759 /* Update the 'jobs added' entry used by print_queue_status. */
2760 add_to_jobs_added(pdb, jobid);
2762 /* Ensure we keep a rough count of the number of total jobs... */
2763 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2765 release_print_db(pdb);
2767 *_jobid = jobid;
2768 return WERR_OK;
2770 fail:
2771 if (jobid != -1) {
2772 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2775 release_print_db(pdb);
2777 DEBUG(3, ("print_job_start: returning fail. "
2778 "Error = %s\n", win_errstr(werr)));
2779 return werr;
2782 /****************************************************************************
2783 Update the number of pages spooled to jobid
2784 ****************************************************************************/
2786 void print_job_endpage(struct messaging_context *msg_ctx,
2787 int snum, uint32 jobid)
2789 const char* sharename = lp_const_servicename(snum);
2790 struct printjob *pjob;
2792 pjob = print_job_find(sharename, jobid);
2793 if (!pjob)
2794 return;
2795 /* don't allow another process to get this info - it is meaningless */
2796 if (pjob->pid != getpid())
2797 return;
2799 pjob->page_count++;
2800 pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
2803 /****************************************************************************
2804 Print a file - called on closing the file. This spools the job.
2805 If normal close is false then we're tearing down the jobs - treat as an
2806 error.
2807 ****************************************************************************/
2809 NTSTATUS print_job_end(struct messaging_context *msg_ctx, int snum,
2810 uint32 jobid, enum file_close_type close_type)
2812 const char* sharename = lp_const_servicename(snum);
2813 struct printjob *pjob;
2814 int ret;
2815 SMB_STRUCT_STAT sbuf;
2816 struct printif *current_printif = get_printer_fns( snum );
2817 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2819 pjob = print_job_find(sharename, jobid);
2821 if (!pjob) {
2822 return NT_STATUS_PRINT_CANCELLED;
2825 if (pjob->spooled || pjob->pid != getpid()) {
2826 return NT_STATUS_ACCESS_DENIED;
2829 if (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) {
2830 if (pjob->status == PJOB_SMBD_SPOOLING) {
2831 /* take over the file now, smbd is done */
2832 if (sys_stat(pjob->filename, &sbuf, false) != 0) {
2833 status = map_nt_error_from_unix(errno);
2834 DEBUG(3, ("print_job_end: "
2835 "stat file failed for jobid %d\n",
2836 jobid));
2837 goto fail;
2840 pjob->status = LPQ_SPOOLING;
2842 } else {
2844 if ((sys_fstat(pjob->fd, &sbuf, false) != 0)) {
2845 status = map_nt_error_from_unix(errno);
2846 close(pjob->fd);
2847 DEBUG(3, ("print_job_end: "
2848 "stat file failed for jobid %d\n",
2849 jobid));
2850 goto fail;
2853 close(pjob->fd);
2856 pjob->size = sbuf.st_ex_size;
2857 } else {
2860 * Not a normal close, something has gone wrong. Cleanup.
2862 if (pjob->fd != -1) {
2863 close(pjob->fd);
2865 goto fail;
2868 /* Technically, this is not quite right. If the printer has a separator
2869 * page turned on, the NT spooler prints the separator page even if the
2870 * print job is 0 bytes. 010215 JRR */
2871 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
2872 /* don't bother spooling empty files or something being deleted. */
2873 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
2874 pjob->filename, pjob->size ? "deleted" : "zero length" ));
2875 unlink(pjob->filename);
2876 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2877 return NT_STATUS_OK;
2880 ret = (*(current_printif->job_submit))(snum, pjob);
2882 if (ret) {
2883 status = NT_STATUS_PRINT_CANCELLED;
2884 goto fail;
2887 /* The print job has been successfully handed over to the back-end */
2889 pjob->spooled = True;
2890 pjob->status = LPQ_QUEUED;
2891 pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
2893 /* make sure the database is up to date */
2894 if (print_cache_expired(lp_const_servicename(snum), True))
2895 print_queue_update(msg_ctx, snum, False);
2897 return NT_STATUS_OK;
2899 fail:
2901 /* The print job was not successfully started. Cleanup */
2902 /* Still need to add proper error return propagation! 010122:JRR */
2903 pjob->fd = -1;
2904 unlink(pjob->filename);
2905 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2906 return status;
2909 /****************************************************************************
2910 Get a snapshot of jobs in the system without traversing.
2911 ****************************************************************************/
2913 static bool get_stored_queue_info(struct messaging_context *msg_ctx,
2914 struct tdb_print_db *pdb, int snum,
2915 int *pcount, print_queue_struct **ppqueue)
2917 TDB_DATA data, cgdata, jcdata;
2918 print_queue_struct *queue = NULL;
2919 uint32 qcount = 0;
2920 uint32 extra_count = 0;
2921 uint32_t changed_count = 0;
2922 int total_count = 0;
2923 size_t len = 0;
2924 uint32 i;
2925 int max_reported_jobs = lp_max_reported_jobs(snum);
2926 bool ret = False;
2927 const char* sharename = lp_servicename(snum);
2929 /* make sure the database is up to date */
2930 if (print_cache_expired(lp_const_servicename(snum), True))
2931 print_queue_update(msg_ctx, snum, False);
2933 *pcount = 0;
2934 *ppqueue = NULL;
2936 ZERO_STRUCT(data);
2937 ZERO_STRUCT(cgdata);
2939 /* Get the stored queue data. */
2940 data = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
2942 if (data.dptr && data.dsize >= sizeof(qcount))
2943 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
2945 /* Get the added jobs list. */
2946 cgdata = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_added"));
2947 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
2948 extra_count = cgdata.dsize/4;
2950 /* Get the changed jobs list. */
2951 jcdata = tdb_fetch_compat(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
2952 if (jcdata.dptr != NULL && (jcdata.dsize % 4 == 0))
2953 changed_count = jcdata.dsize / 4;
2955 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
2957 /* Allocate the queue size. */
2958 if (qcount == 0 && extra_count == 0)
2959 goto out;
2961 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
2962 goto out;
2964 /* Retrieve the linearised queue data. */
2966 for( i = 0; i < qcount; i++) {
2967 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
2968 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
2969 &qjob,
2970 &qsize,
2971 &qpage_count,
2972 &qstatus,
2973 &qpriority,
2974 &qtime,
2975 queue[i].fs_user,
2976 queue[i].fs_file);
2977 queue[i].job = qjob;
2978 queue[i].size = qsize;
2979 queue[i].page_count = qpage_count;
2980 queue[i].status = qstatus;
2981 queue[i].priority = qpriority;
2982 queue[i].time = qtime;
2985 total_count = qcount;
2987 /* Add new jobids to the queue. */
2988 for( i = 0; i < extra_count; i++) {
2989 uint32 jobid;
2990 struct printjob *pjob;
2992 jobid = IVAL(cgdata.dptr, i*4);
2993 DEBUG(5,("get_stored_queue_info: added job = %u\n", (unsigned int)jobid));
2994 pjob = print_job_find(lp_const_servicename(snum), jobid);
2995 if (!pjob) {
2996 DEBUG(5,("get_stored_queue_info: failed to find added job = %u\n", (unsigned int)jobid));
2997 remove_from_jobs_added(sharename, jobid);
2998 continue;
3001 queue[total_count].job = jobid;
3002 queue[total_count].size = pjob->size;
3003 queue[total_count].page_count = pjob->page_count;
3004 queue[total_count].status = pjob->status;
3005 queue[total_count].priority = 1;
3006 queue[total_count].time = pjob->starttime;
3007 fstrcpy(queue[total_count].fs_user, pjob->user);
3008 fstrcpy(queue[total_count].fs_file, pjob->jobname);
3009 total_count++;
3012 /* Update the changed jobids. */
3013 for (i = 0; i < changed_count; i++) {
3014 uint32_t jobid = IVAL(jcdata.dptr, i * 4);
3015 uint32_t j;
3016 bool found = false;
3018 for (j = 0; j < total_count; j++) {
3019 if (queue[j].job == jobid) {
3020 found = true;
3021 break;
3025 if (found) {
3026 struct printjob *pjob;
3028 DEBUG(5,("get_stored_queue_info: changed job: %u\n",
3029 (unsigned int) jobid));
3031 pjob = print_job_find(sharename, jobid);
3032 if (pjob == NULL) {
3033 DEBUG(5,("get_stored_queue_info: failed to find "
3034 "changed job = %u\n",
3035 (unsigned int) jobid));
3036 remove_from_jobs_changed(sharename, jobid);
3037 continue;
3040 queue[j].job = jobid;
3041 queue[j].size = pjob->size;
3042 queue[j].page_count = pjob->page_count;
3043 queue[j].status = pjob->status;
3044 queue[j].priority = 1;
3045 queue[j].time = pjob->starttime;
3046 fstrcpy(queue[j].fs_user, pjob->user);
3047 fstrcpy(queue[j].fs_file, pjob->jobname);
3049 DEBUG(5,("get_stored_queue_info: updated queue[%u], jobid: %u, jobname: %s\n",
3050 (unsigned int) j, (unsigned int) jobid, pjob->jobname));
3053 remove_from_jobs_changed(sharename, jobid);
3056 /* Sort the queue by submission time otherwise they are displayed
3057 in hash order. */
3059 TYPESAFE_QSORT(queue, total_count, printjob_comp);
3061 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
3063 if (max_reported_jobs && total_count > max_reported_jobs)
3064 total_count = max_reported_jobs;
3066 *ppqueue = queue;
3067 *pcount = total_count;
3069 ret = True;
3071 out:
3073 SAFE_FREE(data.dptr);
3074 SAFE_FREE(cgdata.dptr);
3075 return ret;
3078 /****************************************************************************
3079 Get a printer queue listing.
3080 set queue = NULL and status = NULL if you just want to update the cache
3081 ****************************************************************************/
3083 int print_queue_status(struct messaging_context *msg_ctx, int snum,
3084 print_queue_struct **ppqueue,
3085 print_status_struct *status)
3087 fstring keystr;
3088 TDB_DATA data, key;
3089 const char *sharename;
3090 struct tdb_print_db *pdb;
3091 int count = 0;
3093 /* make sure the database is up to date */
3095 if (print_cache_expired(lp_const_servicename(snum), True))
3096 print_queue_update(msg_ctx, snum, False);
3098 /* return if we are done */
3099 if ( !ppqueue || !status )
3100 return 0;
3102 *ppqueue = NULL;
3103 sharename = lp_const_servicename(snum);
3104 pdb = get_print_db_byname(sharename);
3106 if (!pdb)
3107 return 0;
3110 * Fetch the queue status. We must do this first, as there may
3111 * be no jobs in the queue.
3114 ZERO_STRUCTP(status);
3115 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
3116 key = string_tdb_data(keystr);
3118 data = tdb_fetch_compat(pdb->tdb, key);
3119 if (data.dptr) {
3120 if (data.dsize == sizeof(*status)) {
3121 /* this memcpy is ok since the status struct was
3122 not packed before storing it in the tdb */
3123 memcpy(status, data.dptr, sizeof(*status));
3125 SAFE_FREE(data.dptr);
3129 * Now, fetch the print queue information. We first count the number
3130 * of entries, and then only retrieve the queue if necessary.
3133 if (!get_stored_queue_info(msg_ctx, pdb, snum, &count, ppqueue)) {
3134 release_print_db(pdb);
3135 return 0;
3138 release_print_db(pdb);
3139 return count;
3142 /****************************************************************************
3143 Pause a queue.
3144 ****************************************************************************/
3146 WERROR print_queue_pause(const struct auth_session_info *server_info,
3147 struct messaging_context *msg_ctx, int snum)
3149 int ret;
3150 struct printif *current_printif = get_printer_fns( snum );
3152 if (!print_access_check(server_info, msg_ctx, snum,
3153 PRINTER_ACCESS_ADMINISTER)) {
3154 return WERR_ACCESS_DENIED;
3158 become_root();
3160 ret = (*(current_printif->queue_pause))(snum);
3162 unbecome_root();
3164 if (ret != 0) {
3165 return WERR_INVALID_PARAM;
3168 /* force update the database */
3169 print_cache_flush(lp_const_servicename(snum));
3171 /* Send a printer notify message */
3173 notify_printer_status(server_event_context(), msg_ctx, snum,
3174 PRINTER_STATUS_PAUSED);
3176 return WERR_OK;
3179 /****************************************************************************
3180 Resume a queue.
3181 ****************************************************************************/
3183 WERROR print_queue_resume(const struct auth_session_info *server_info,
3184 struct messaging_context *msg_ctx, int snum)
3186 int ret;
3187 struct printif *current_printif = get_printer_fns( snum );
3189 if (!print_access_check(server_info, msg_ctx, snum,
3190 PRINTER_ACCESS_ADMINISTER)) {
3191 return WERR_ACCESS_DENIED;
3194 become_root();
3196 ret = (*(current_printif->queue_resume))(snum);
3198 unbecome_root();
3200 if (ret != 0) {
3201 return WERR_INVALID_PARAM;
3204 /* make sure the database is up to date */
3205 if (print_cache_expired(lp_const_servicename(snum), True))
3206 print_queue_update(msg_ctx, snum, True);
3208 /* Send a printer notify message */
3210 notify_printer_status(server_event_context(), msg_ctx, snum,
3211 PRINTER_STATUS_OK);
3213 return WERR_OK;
3216 /****************************************************************************
3217 Purge a queue - implemented by deleting all jobs that we can delete.
3218 ****************************************************************************/
3220 WERROR print_queue_purge(const struct auth_session_info *server_info,
3221 struct messaging_context *msg_ctx, int snum)
3223 print_queue_struct *queue;
3224 print_status_struct status;
3225 int njobs, i;
3226 bool can_job_admin;
3228 /* Force and update so the count is accurate (i.e. not a cached count) */
3229 print_queue_update(msg_ctx, snum, True);
3231 can_job_admin = print_access_check(server_info,
3232 msg_ctx,
3233 snum,
3234 JOB_ACCESS_ADMINISTER);
3235 njobs = print_queue_status(msg_ctx, snum, &queue, &status);
3237 if ( can_job_admin )
3238 become_root();
3240 for (i=0;i<njobs;i++) {
3241 bool owner = is_owner(server_info, lp_const_servicename(snum),
3242 queue[i].job);
3244 if (owner || can_job_admin) {
3245 print_job_delete1(server_event_context(), msg_ctx,
3246 snum, queue[i].job);
3250 if ( can_job_admin )
3251 unbecome_root();
3253 /* update the cache */
3254 print_queue_update(msg_ctx, snum, True);
3256 SAFE_FREE(queue);
3258 return WERR_OK;