build: get the SONAME right for installed libraries
[Samba/gebeck_regimport.git] / source3 / printing / printing.c
blobb0f22c9b6f5bfd5d25c25a75f59d6a1115155e3d
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 "printing.h"
24 #include "librpc/gen_ndr/messaging.h"
26 extern struct current_user current_user;
27 extern userdom_struct current_user_info;
29 /* Current printer interface */
30 static bool remove_from_jobs_changed(const char* sharename, uint32 jobid);
33 the printing backend revolves around a tdb database that stores the
34 SMB view of the print queue
36 The key for this database is a jobid - a internally generated number that
37 uniquely identifies a print job
39 reading the print queue involves two steps:
40 - possibly running lpq and updating the internal database from that
41 - reading entries from the database
43 jobids are assigned when a job starts spooling.
46 static TDB_CONTEXT *rap_tdb;
47 static uint16 next_rap_jobid;
48 struct rap_jobid_key {
49 fstring sharename;
50 uint32 jobid;
53 /***************************************************************************
54 Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
55 bit RPC jobids.... JRA.
56 ***************************************************************************/
58 uint16 pjobid_to_rap(const char* sharename, uint32 jobid)
60 uint16 rap_jobid;
61 TDB_DATA data, key;
62 struct rap_jobid_key jinfo;
63 uint8 buf[2];
65 DEBUG(10,("pjobid_to_rap: called.\n"));
67 if (!rap_tdb) {
68 /* Create the in-memory tdb. */
69 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
70 if (!rap_tdb)
71 return 0;
74 ZERO_STRUCT( jinfo );
75 fstrcpy( jinfo.sharename, sharename );
76 jinfo.jobid = jobid;
77 key.dptr = (uint8 *)&jinfo;
78 key.dsize = sizeof(jinfo);
80 data = tdb_fetch(rap_tdb, key);
81 if (data.dptr && data.dsize == sizeof(uint16)) {
82 rap_jobid = SVAL(data.dptr, 0);
83 SAFE_FREE(data.dptr);
84 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
85 (unsigned int)jobid, (unsigned int)rap_jobid));
86 return rap_jobid;
88 SAFE_FREE(data.dptr);
89 /* Not found - create and store mapping. */
90 rap_jobid = ++next_rap_jobid;
91 if (rap_jobid == 0)
92 rap_jobid = ++next_rap_jobid;
93 SSVAL(buf,0,rap_jobid);
94 data.dptr = buf;
95 data.dsize = sizeof(rap_jobid);
96 tdb_store(rap_tdb, key, data, TDB_REPLACE);
97 tdb_store(rap_tdb, data, key, TDB_REPLACE);
99 DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
100 (unsigned int)jobid, (unsigned int)rap_jobid));
101 return rap_jobid;
104 bool rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
106 TDB_DATA data, key;
107 uint8 buf[2];
109 DEBUG(10,("rap_to_pjobid called.\n"));
111 if (!rap_tdb)
112 return False;
114 SSVAL(buf,0,rap_jobid);
115 key.dptr = buf;
116 key.dsize = sizeof(rap_jobid);
117 data = tdb_fetch(rap_tdb, key);
118 if ( data.dptr && data.dsize == sizeof(struct rap_jobid_key) )
120 struct rap_jobid_key *jinfo = (struct rap_jobid_key*)data.dptr;
121 if (sharename != NULL) {
122 fstrcpy( sharename, jinfo->sharename );
124 *pjobid = jinfo->jobid;
125 DEBUG(10,("rap_to_pjobid: jobid %u maps to RAP jobid %u\n",
126 (unsigned int)*pjobid, (unsigned int)rap_jobid));
127 SAFE_FREE(data.dptr);
128 return True;
131 DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
132 (unsigned int)rap_jobid));
133 SAFE_FREE(data.dptr);
134 return False;
137 static void rap_jobid_delete(const char* sharename, uint32 jobid)
139 TDB_DATA key, data;
140 uint16 rap_jobid;
141 struct rap_jobid_key jinfo;
142 uint8 buf[2];
144 DEBUG(10,("rap_jobid_delete: called.\n"));
146 if (!rap_tdb)
147 return;
149 ZERO_STRUCT( jinfo );
150 fstrcpy( jinfo.sharename, sharename );
151 jinfo.jobid = jobid;
152 key.dptr = (uint8 *)&jinfo;
153 key.dsize = sizeof(jinfo);
155 data = tdb_fetch(rap_tdb, key);
156 if (!data.dptr || (data.dsize != sizeof(uint16))) {
157 DEBUG(10,("rap_jobid_delete: cannot find jobid %u\n",
158 (unsigned int)jobid ));
159 SAFE_FREE(data.dptr);
160 return;
163 DEBUG(10,("rap_jobid_delete: deleting jobid %u\n",
164 (unsigned int)jobid ));
166 rap_jobid = SVAL(data.dptr, 0);
167 SAFE_FREE(data.dptr);
168 SSVAL(buf,0,rap_jobid);
169 data.dptr = buf;
170 data.dsize = sizeof(rap_jobid);
171 tdb_delete(rap_tdb, key);
172 tdb_delete(rap_tdb, data);
175 static int get_queue_status(const char* sharename, print_status_struct *);
177 /****************************************************************************
178 Initialise the printing backend. Called once at startup before the fork().
179 ****************************************************************************/
181 bool print_backend_init(struct messaging_context *msg_ctx)
183 const char *sversion = "INFO/version";
184 int services = lp_numservices();
185 int snum;
187 unlink(cache_path("printing.tdb"));
188 mkdir(cache_path("printing"),0755);
190 /* handle a Samba upgrade */
192 for (snum = 0; snum < services; snum++) {
193 struct tdb_print_db *pdb;
194 if (!lp_print_ok(snum))
195 continue;
197 pdb = get_print_db_byname(lp_const_servicename(snum));
198 if (!pdb)
199 continue;
200 if (tdb_lock_bystring(pdb->tdb, sversion) == -1) {
201 DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
202 release_print_db(pdb);
203 return False;
205 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
206 tdb_wipe_all(pdb->tdb);
207 tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
209 tdb_unlock_bystring(pdb->tdb, sversion);
210 release_print_db(pdb);
213 close_all_print_db(); /* Don't leave any open. */
215 /* do NT print initialization... */
216 return nt_printing_init(msg_ctx);
219 /****************************************************************************
220 Shut down printing backend. Called once at shutdown to close the tdb.
221 ****************************************************************************/
223 void printing_end(void)
225 close_all_print_db(); /* Don't leave any open. */
228 /****************************************************************************
229 Retrieve the set of printing functions for a given service. This allows
230 us to set the printer function table based on the value of the 'printing'
231 service parameter.
233 Use the generic interface as the default and only use cups interface only
234 when asked for (and only when supported)
235 ****************************************************************************/
237 static struct printif *get_printer_fns_from_type( enum printing_types type )
239 struct printif *printer_fns = &generic_printif;
241 #ifdef HAVE_CUPS
242 if ( type == PRINT_CUPS ) {
243 printer_fns = &cups_printif;
245 #endif /* HAVE_CUPS */
247 #ifdef HAVE_IPRINT
248 if ( type == PRINT_IPRINT ) {
249 printer_fns = &iprint_printif;
251 #endif /* HAVE_IPRINT */
253 printer_fns->type = type;
255 return printer_fns;
258 static struct printif *get_printer_fns( int snum )
260 return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
264 /****************************************************************************
265 Useful function to generate a tdb key.
266 ****************************************************************************/
268 static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
270 TDB_DATA ret;
272 SIVAL(tmp, 0, jobid);
273 ret.dptr = (uint8 *)tmp;
274 ret.dsize = sizeof(*tmp);
275 return ret;
278 /***********************************************************************
279 unpack a pjob from a tdb buffer
280 ***********************************************************************/
282 int unpack_pjob( uint8 *buf, int buflen, struct printjob *pjob )
284 int len = 0;
285 int used;
286 uint32 pjpid, pjsysjob, pjfd, pjstarttime, pjstatus;
287 uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
289 if ( !buf || !pjob )
290 return -1;
292 len += tdb_unpack(buf+len, buflen-len, "dddddddddffff",
293 &pjpid,
294 &pjsysjob,
295 &pjfd,
296 &pjstarttime,
297 &pjstatus,
298 &pjsize,
299 &pjpage_count,
300 &pjspooled,
301 &pjsmbjob,
302 pjob->filename,
303 pjob->jobname,
304 pjob->user,
305 pjob->queuename);
307 if ( len == -1 )
308 return -1;
310 if ( (used = unpack_devicemode(&pjob->nt_devmode, buf+len, buflen-len)) == -1 )
311 return -1;
313 len += used;
315 pjob->pid = pjpid;
316 pjob->sysjob = pjsysjob;
317 pjob->fd = pjfd;
318 pjob->starttime = pjstarttime;
319 pjob->status = pjstatus;
320 pjob->size = pjsize;
321 pjob->page_count = pjpage_count;
322 pjob->spooled = pjspooled;
323 pjob->smbjob = pjsmbjob;
325 return len;
329 /****************************************************************************
330 Useful function to find a print job in the database.
331 ****************************************************************************/
333 static struct printjob *print_job_find(const char *sharename, uint32 jobid)
335 static struct printjob pjob;
336 uint32_t tmp;
337 TDB_DATA ret;
338 struct tdb_print_db *pdb = get_print_db_byname(sharename);
340 DEBUG(10,("print_job_find: looking up job %u for share %s\n",
341 (unsigned int)jobid, sharename ));
343 if (!pdb) {
344 return NULL;
347 ret = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
348 release_print_db(pdb);
350 if (!ret.dptr) {
351 DEBUG(10,("print_job_find: failed to find jobid %u.\n", (unsigned int)jobid ));
352 return NULL;
355 if ( pjob.nt_devmode ) {
356 free_nt_devicemode( &pjob.nt_devmode );
359 ZERO_STRUCT( pjob );
361 if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
362 DEBUG(10,("print_job_find: failed to unpack jobid %u.\n", (unsigned int)jobid ));
363 SAFE_FREE(ret.dptr);
364 return NULL;
367 SAFE_FREE(ret.dptr);
369 DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
370 (int)pjob.sysjob, (unsigned int)jobid ));
372 return &pjob;
375 /* Convert a unix jobid to a smb jobid */
377 struct unixjob_traverse_state {
378 int sysjob;
379 uint32 sysjob_to_jobid_value;
382 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
383 TDB_DATA data, void *private_data)
385 struct printjob *pjob;
386 struct unixjob_traverse_state *state =
387 (struct unixjob_traverse_state *)private_data;
389 if (!data.dptr || data.dsize == 0)
390 return 0;
392 pjob = (struct printjob *)data.dptr;
393 if (key.dsize != sizeof(uint32))
394 return 0;
396 if (state->sysjob == pjob->sysjob) {
397 uint32 jobid = IVAL(key.dptr,0);
399 state->sysjob_to_jobid_value = jobid;
400 return 1;
403 return 0;
406 /****************************************************************************
407 This is a *horribly expensive call as we have to iterate through all the
408 current printer tdb's. Don't do this often ! JRA.
409 ****************************************************************************/
411 uint32 sysjob_to_jobid(int unix_jobid)
413 int services = lp_numservices();
414 int snum;
415 struct unixjob_traverse_state state;
417 state.sysjob = unix_jobid;
418 state.sysjob_to_jobid_value = (uint32)-1;
420 for (snum = 0; snum < services; snum++) {
421 struct tdb_print_db *pdb;
422 if (!lp_print_ok(snum))
423 continue;
424 pdb = get_print_db_byname(lp_const_servicename(snum));
425 if (!pdb) {
426 continue;
428 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
429 release_print_db(pdb);
430 if (state.sysjob_to_jobid_value != (uint32)-1)
431 return state.sysjob_to_jobid_value;
433 return (uint32)-1;
436 /****************************************************************************
437 Send notifications based on what has changed after a pjob_store.
438 ****************************************************************************/
440 static const struct {
441 uint32 lpq_status;
442 uint32 spoolss_status;
443 } lpq_to_spoolss_status_map[] = {
444 { LPQ_QUEUED, JOB_STATUS_QUEUED },
445 { LPQ_PAUSED, JOB_STATUS_PAUSED },
446 { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
447 { LPQ_PRINTING, JOB_STATUS_PRINTING },
448 { LPQ_DELETING, JOB_STATUS_DELETING },
449 { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
450 { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
451 { LPQ_PRINTED, JOB_STATUS_PRINTED },
452 { LPQ_DELETED, JOB_STATUS_DELETED },
453 { LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
454 { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
455 { -1, 0 }
458 /* Convert a lpq status value stored in printing.tdb into the
459 appropriate win32 API constant. */
461 static uint32 map_to_spoolss_status(uint32 lpq_status)
463 int i = 0;
465 while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
466 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
467 return lpq_to_spoolss_status_map[i].spoolss_status;
468 i++;
471 return 0;
474 static void pjob_store_notify(const char* sharename, uint32 jobid, struct printjob *old_data,
475 struct printjob *new_data)
477 bool new_job = False;
479 if (!old_data)
480 new_job = True;
482 /* Job attributes that can't be changed. We only send
483 notification for these on a new job. */
485 /* ACHTUNG! Due to a bug in Samba's spoolss parsing of the
486 NOTIFY_INFO_DATA buffer, we *have* to send the job submission
487 time first or else we'll end up with potential alignment
488 errors. I don't think the systemtime should be spooled as
489 a string, but this gets us around that error.
490 --jerry (i'll feel dirty for this) */
492 if (new_job) {
493 notify_job_submitted(sharename, jobid, new_data->starttime);
494 notify_job_username(sharename, jobid, new_data->user);
497 if (new_job || !strequal(old_data->jobname, new_data->jobname))
498 notify_job_name(sharename, jobid, new_data->jobname);
500 /* Job attributes of a new job or attributes that can be
501 modified. */
503 if (new_job || !strequal(old_data->jobname, new_data->jobname))
504 notify_job_name(sharename, jobid, new_data->jobname);
506 if (new_job || old_data->status != new_data->status)
507 notify_job_status(sharename, jobid, map_to_spoolss_status(new_data->status));
509 if (new_job || old_data->size != new_data->size)
510 notify_job_total_bytes(sharename, jobid, new_data->size);
512 if (new_job || old_data->page_count != new_data->page_count)
513 notify_job_total_pages(sharename, jobid, new_data->page_count);
516 /****************************************************************************
517 Store a job structure back to the database.
518 ****************************************************************************/
520 static bool pjob_store(const char* sharename, uint32 jobid, struct printjob *pjob)
522 uint32_t tmp;
523 TDB_DATA old_data, new_data;
524 bool ret = False;
525 struct tdb_print_db *pdb = get_print_db_byname(sharename);
526 uint8 *buf = NULL;
527 int len, newlen, buflen;
530 if (!pdb)
531 return False;
533 /* Get old data */
535 old_data = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
537 /* Doh! Now we have to pack/unpack data since the NT_DEVICEMODE was added */
539 newlen = 0;
541 do {
542 len = 0;
543 buflen = newlen;
544 len += tdb_pack(buf+len, buflen-len, "dddddddddffff",
545 (uint32)pjob->pid,
546 (uint32)pjob->sysjob,
547 (uint32)pjob->fd,
548 (uint32)pjob->starttime,
549 (uint32)pjob->status,
550 (uint32)pjob->size,
551 (uint32)pjob->page_count,
552 (uint32)pjob->spooled,
553 (uint32)pjob->smbjob,
554 pjob->filename,
555 pjob->jobname,
556 pjob->user,
557 pjob->queuename);
559 len += pack_devicemode(pjob->nt_devmode, buf+len, buflen-len);
561 if (buflen != len) {
562 buf = (uint8 *)SMB_REALLOC(buf, len);
563 if (!buf) {
564 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
565 goto done;
567 newlen = len;
569 } while ( buflen != len );
572 /* Store new data */
574 new_data.dptr = buf;
575 new_data.dsize = len;
576 ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
577 TDB_REPLACE) == 0);
579 release_print_db(pdb);
581 /* Send notify updates for what has changed */
583 if ( ret ) {
584 struct printjob old_pjob;
586 if ( old_data.dsize )
588 if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
590 pjob_store_notify( sharename, jobid, &old_pjob , pjob );
591 free_nt_devicemode( &old_pjob.nt_devmode );
594 else {
595 /* new job */
596 pjob_store_notify( sharename, jobid, NULL, pjob );
600 done:
601 SAFE_FREE( old_data.dptr );
602 SAFE_FREE( buf );
604 return ret;
607 /****************************************************************************
608 Remove a job structure from the database.
609 ****************************************************************************/
611 void pjob_delete(const char* sharename, uint32 jobid)
613 uint32_t tmp;
614 struct printjob *pjob;
615 uint32 job_status = 0;
616 struct tdb_print_db *pdb;
618 pdb = get_print_db_byname( sharename );
620 if (!pdb)
621 return;
623 pjob = print_job_find( sharename, jobid );
625 if (!pjob) {
626 DEBUG(5, ("pjob_delete: we were asked to delete nonexistent job %u\n",
627 (unsigned int)jobid));
628 release_print_db(pdb);
629 return;
632 /* We must cycle through JOB_STATUS_DELETING and
633 JOB_STATUS_DELETED for the port monitor to delete the job
634 properly. */
636 job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
637 notify_job_status(sharename, jobid, job_status);
639 /* Remove from printing.tdb */
641 tdb_delete(pdb->tdb, print_key(jobid, &tmp));
642 remove_from_jobs_changed(sharename, jobid);
643 release_print_db( pdb );
644 rap_jobid_delete(sharename, jobid);
647 /****************************************************************************
648 List a unix job in the print database.
649 ****************************************************************************/
651 static void print_unix_job(const char *sharename, print_queue_struct *q, uint32 jobid)
653 struct printjob pj, *old_pj;
655 if (jobid == (uint32)-1)
656 jobid = q->job + UNIX_JOB_START;
658 /* Preserve the timestamp on an existing unix print job */
660 old_pj = print_job_find(sharename, jobid);
662 ZERO_STRUCT(pj);
664 pj.pid = (pid_t)-1;
665 pj.sysjob = q->job;
666 pj.fd = -1;
667 pj.starttime = old_pj ? old_pj->starttime : q->time;
668 pj.status = q->status;
669 pj.size = q->size;
670 pj.spooled = True;
671 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
672 if (jobid < UNIX_JOB_START) {
673 pj.smbjob = True;
674 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
675 } else {
676 pj.smbjob = False;
677 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
679 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
680 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
682 pjob_store(sharename, jobid, &pj);
686 struct traverse_struct {
687 print_queue_struct *queue;
688 int qcount, snum, maxcount, total_jobs;
689 const char *sharename;
690 time_t lpq_time;
691 const char *lprm_command;
692 struct printif *print_if;
695 /****************************************************************************
696 Utility fn to delete any jobs that are no longer active.
697 ****************************************************************************/
699 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
701 struct traverse_struct *ts = (struct traverse_struct *)state;
702 struct printjob pjob;
703 uint32 jobid;
704 int i = 0;
706 if ( key.dsize != sizeof(jobid) )
707 return 0;
709 jobid = IVAL(key.dptr, 0);
710 if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
711 return 0;
712 free_nt_devicemode( &pjob.nt_devmode );
715 if (!pjob.smbjob) {
716 /* remove a unix job if it isn't in the system queue any more */
718 for (i=0;i<ts->qcount;i++) {
719 uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
720 if (jobid == u_jobid)
721 break;
723 if (i == ts->qcount) {
724 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
725 (unsigned int)jobid ));
726 pjob_delete(ts->sharename, jobid);
727 return 0;
730 /* need to continue the the bottom of the function to
731 save the correct attributes */
734 /* maybe it hasn't been spooled yet */
735 if (!pjob.spooled) {
736 /* if a job is not spooled and the process doesn't
737 exist then kill it. This cleans up after smbd
738 deaths */
739 if (!process_exists_by_pid(pjob.pid)) {
740 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
741 (unsigned int)jobid, (unsigned int)pjob.pid ));
742 pjob_delete(ts->sharename, jobid);
743 } else
744 ts->total_jobs++;
745 return 0;
748 /* this check only makes sense for jobs submitted from Windows clients */
750 if ( pjob.smbjob ) {
751 for (i=0;i<ts->qcount;i++) {
752 uint32 curr_jobid;
754 if ( pjob.status == LPQ_DELETED )
755 continue;
757 curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
759 if (jobid == curr_jobid) {
761 /* try to clean up any jobs that need to be deleted */
763 if ( pjob.status == LPQ_DELETING ) {
764 int result;
766 result = (*(ts->print_if->job_delete))(
767 ts->sharename, ts->lprm_command, &pjob );
769 if ( result != 0 ) {
770 /* if we can't delete, then reset the job status */
771 pjob.status = LPQ_QUEUED;
772 pjob_store(ts->sharename, jobid, &pjob);
774 else {
775 /* if we deleted the job, the remove the tdb record */
776 pjob_delete(ts->sharename, jobid);
777 pjob.status = LPQ_DELETED;
782 break;
787 /* The job isn't in the system queue - we have to assume it has
788 completed, so delete the database entry. */
790 if (i == ts->qcount) {
792 /* A race can occur between the time a job is spooled and
793 when it appears in the lpq output. This happens when
794 the job is added to printing.tdb when another smbd
795 running print_queue_update() has completed a lpq and
796 is currently traversing the printing tdb and deleting jobs.
797 Don't delete the job if it was submitted after the lpq_time. */
799 if (pjob.starttime < ts->lpq_time) {
800 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
801 (unsigned int)jobid,
802 (unsigned int)pjob.starttime,
803 (unsigned int)ts->lpq_time ));
804 pjob_delete(ts->sharename, jobid);
805 } else
806 ts->total_jobs++;
807 return 0;
810 /* Save the pjob attributes we will store.
811 FIXME!!! This is the only place where queue->job
812 represents the SMB jobid --jerry */
814 ts->queue[i].job = jobid;
815 ts->queue[i].size = pjob.size;
816 ts->queue[i].page_count = pjob.page_count;
817 ts->queue[i].status = pjob.status;
818 ts->queue[i].priority = 1;
819 ts->queue[i].time = pjob.starttime;
820 fstrcpy(ts->queue[i].fs_user, pjob.user);
821 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
823 ts->total_jobs++;
825 return 0;
828 /****************************************************************************
829 Check if the print queue has been updated recently enough.
830 ****************************************************************************/
832 static void print_cache_flush(const char *sharename)
834 fstring key;
835 struct tdb_print_db *pdb = get_print_db_byname(sharename);
837 if (!pdb)
838 return;
839 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
840 tdb_store_int32(pdb->tdb, key, -1);
841 release_print_db(pdb);
844 /****************************************************************************
845 Check if someone already thinks they are doing the update.
846 ****************************************************************************/
848 static pid_t get_updating_pid(const char *sharename)
850 fstring keystr;
851 TDB_DATA data, key;
852 pid_t updating_pid;
853 struct tdb_print_db *pdb = get_print_db_byname(sharename);
855 if (!pdb)
856 return (pid_t)-1;
857 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
858 key = string_tdb_data(keystr);
860 data = tdb_fetch(pdb->tdb, key);
861 release_print_db(pdb);
862 if (!data.dptr || data.dsize != sizeof(pid_t)) {
863 SAFE_FREE(data.dptr);
864 return (pid_t)-1;
867 updating_pid = IVAL(data.dptr, 0);
868 SAFE_FREE(data.dptr);
870 if (process_exists_by_pid(updating_pid))
871 return updating_pid;
873 return (pid_t)-1;
876 /****************************************************************************
877 Set the fact that we're doing the update, or have finished doing the update
878 in the tdb.
879 ****************************************************************************/
881 static void set_updating_pid(const fstring sharename, bool updating)
883 fstring keystr;
884 TDB_DATA key;
885 TDB_DATA data;
886 pid_t updating_pid = sys_getpid();
887 uint8 buffer[4];
889 struct tdb_print_db *pdb = get_print_db_byname(sharename);
891 if (!pdb)
892 return;
894 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
895 key = string_tdb_data(keystr);
897 DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
898 updating ? "" : "not ",
899 sharename ));
901 if ( !updating ) {
902 tdb_delete(pdb->tdb, key);
903 release_print_db(pdb);
904 return;
907 SIVAL( buffer, 0, updating_pid);
908 data.dptr = buffer;
909 data.dsize = 4; /* we always assume this is a 4 byte value */
911 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
912 release_print_db(pdb);
915 /****************************************************************************
916 Sort print jobs by submittal time.
917 ****************************************************************************/
919 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
921 /* Silly cases */
923 if (!j1 && !j2)
924 return 0;
925 if (!j1)
926 return -1;
927 if (!j2)
928 return 1;
930 /* Sort on job start time */
932 if (j1->time == j2->time)
933 return 0;
934 return (j1->time > j2->time) ? 1 : -1;
937 /****************************************************************************
938 Store the sorted queue representation for later portmon retrieval.
939 Skip deleted jobs
940 ****************************************************************************/
942 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
944 TDB_DATA data;
945 int max_reported_jobs = lp_max_reported_jobs(pts->snum);
946 print_queue_struct *queue = pts->queue;
947 size_t len;
948 size_t i;
949 unsigned int qcount;
951 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
952 pts->qcount = max_reported_jobs;
953 qcount = 0;
955 /* Work out the size. */
956 data.dsize = 0;
957 data.dsize += tdb_pack(NULL, 0, "d", qcount);
959 for (i = 0; i < pts->qcount; i++) {
960 if ( queue[i].status == LPQ_DELETED )
961 continue;
963 qcount++;
964 data.dsize += tdb_pack(NULL, 0, "ddddddff",
965 (uint32)queue[i].job,
966 (uint32)queue[i].size,
967 (uint32)queue[i].page_count,
968 (uint32)queue[i].status,
969 (uint32)queue[i].priority,
970 (uint32)queue[i].time,
971 queue[i].fs_user,
972 queue[i].fs_file);
975 if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
976 return;
978 len = 0;
979 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
980 for (i = 0; i < pts->qcount; i++) {
981 if ( queue[i].status == LPQ_DELETED )
982 continue;
984 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
985 (uint32)queue[i].job,
986 (uint32)queue[i].size,
987 (uint32)queue[i].page_count,
988 (uint32)queue[i].status,
989 (uint32)queue[i].priority,
990 (uint32)queue[i].time,
991 queue[i].fs_user,
992 queue[i].fs_file);
995 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
996 TDB_REPLACE);
997 SAFE_FREE(data.dptr);
998 return;
1001 static TDB_DATA get_jobs_changed_data(struct tdb_print_db *pdb)
1003 TDB_DATA data;
1005 ZERO_STRUCT(data);
1007 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
1008 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1009 SAFE_FREE(data.dptr);
1010 ZERO_STRUCT(data);
1013 return data;
1016 static void check_job_changed(const char *sharename, TDB_DATA data, uint32 jobid)
1018 unsigned int i;
1019 unsigned int job_count = data.dsize / 4;
1021 for (i = 0; i < job_count; i++) {
1022 uint32 ch_jobid;
1024 ch_jobid = IVAL(data.dptr, i*4);
1025 if (ch_jobid == jobid)
1026 remove_from_jobs_changed(sharename, jobid);
1030 /****************************************************************************
1031 Check if the print queue has been updated recently enough.
1032 ****************************************************************************/
1034 static bool print_cache_expired(const char *sharename, bool check_pending)
1036 fstring key;
1037 time_t last_qscan_time, time_now = time(NULL);
1038 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1039 bool result = False;
1041 if (!pdb)
1042 return False;
1044 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1045 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1048 * Invalidate the queue for 3 reasons.
1049 * (1). last queue scan time == -1.
1050 * (2). Current time - last queue scan time > allowed cache time.
1051 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1052 * This last test picks up machines for which the clock has been moved
1053 * forward, an lpq scan done and then the clock moved back. Otherwise
1054 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1057 if (last_qscan_time == ((time_t)-1)
1058 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1059 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1061 uint32 u;
1062 time_t msg_pending_time;
1064 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1065 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1066 sharename, (int)last_qscan_time, (int)time_now,
1067 (int)lp_lpqcachetime() ));
1069 /* check if another smbd has already sent a message to update the
1070 queue. Give the pending message one minute to clear and
1071 then send another message anyways. Make sure to check for
1072 clocks that have been run forward and then back again. */
1074 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1076 if ( check_pending
1077 && tdb_fetch_uint32( pdb->tdb, key, &u )
1078 && (msg_pending_time=u) > 0
1079 && msg_pending_time <= time_now
1080 && (time_now - msg_pending_time) < 60 )
1082 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1083 sharename));
1084 goto done;
1087 result = True;
1090 done:
1091 release_print_db(pdb);
1092 return result;
1095 /****************************************************************************
1096 main work for updating the lpq cahe for a printer queue
1097 ****************************************************************************/
1099 static void print_queue_update_internal( const char *sharename,
1100 struct printif *current_printif,
1101 char *lpq_command, char *lprm_command )
1103 int i, qcount;
1104 print_queue_struct *queue = NULL;
1105 print_status_struct status;
1106 print_status_struct old_status;
1107 struct printjob *pjob;
1108 struct traverse_struct tstruct;
1109 TDB_DATA data, key;
1110 TDB_DATA jcdata;
1111 fstring keystr, cachestr;
1112 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1114 if (!pdb) {
1115 return;
1118 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1119 sharename, current_printif->type, lpq_command));
1122 * Update the cache time FIRST ! Stops others even
1123 * attempting to get the lock and doing this
1124 * if the lpq takes a long time.
1127 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1128 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1130 /* get the current queue using the appropriate interface */
1131 ZERO_STRUCT(status);
1133 qcount = (*(current_printif->queue_get))(sharename,
1134 current_printif->type,
1135 lpq_command, &queue, &status);
1137 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1138 qcount, (qcount != 1) ? "s" : "", sharename));
1140 /* Sort the queue by submission time otherwise they are displayed
1141 in hash order. */
1143 TYPESAFE_QSORT(queue, qcount, printjob_comp);
1146 any job in the internal database that is marked as spooled
1147 and doesn't exist in the system queue is considered finished
1148 and removed from the database
1150 any job in the system database but not in the internal database
1151 is added as a unix job
1153 fill in any system job numbers as we go
1156 jcdata = get_jobs_changed_data(pdb);
1158 for (i=0; i<qcount; i++) {
1159 uint32 jobid = print_parse_jobid(queue[i].fs_file);
1161 if (jobid == (uint32)-1) {
1162 /* assume its a unix print job */
1163 print_unix_job(sharename, &queue[i], jobid);
1164 continue;
1167 /* we have an active SMB print job - update its status */
1168 pjob = print_job_find(sharename, jobid);
1169 if (!pjob) {
1170 /* err, somethings wrong. Probably smbd was restarted
1171 with jobs in the queue. All we can do is treat them
1172 like unix jobs. Pity. */
1173 print_unix_job(sharename, &queue[i], jobid);
1174 continue;
1177 pjob->sysjob = queue[i].job;
1179 /* don't reset the status on jobs to be deleted */
1181 if ( pjob->status != LPQ_DELETING )
1182 pjob->status = queue[i].status;
1184 pjob_store(sharename, jobid, pjob);
1186 check_job_changed(sharename, jcdata, jobid);
1189 SAFE_FREE(jcdata.dptr);
1191 /* now delete any queued entries that don't appear in the
1192 system queue */
1193 tstruct.queue = queue;
1194 tstruct.qcount = qcount;
1195 tstruct.snum = -1;
1196 tstruct.total_jobs = 0;
1197 tstruct.lpq_time = time(NULL);
1198 tstruct.sharename = sharename;
1199 tstruct.lprm_command = lprm_command;
1200 tstruct.print_if = current_printif;
1202 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1204 /* Store the linearised queue, max jobs only. */
1205 store_queue_struct(pdb, &tstruct);
1207 SAFE_FREE(tstruct.queue);
1209 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1210 sharename, tstruct.total_jobs ));
1212 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1214 get_queue_status(sharename, &old_status);
1215 if (old_status.qcount != qcount)
1216 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1217 old_status.qcount, qcount, sharename));
1219 /* store the new queue status structure */
1220 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1221 key = string_tdb_data(keystr);
1223 status.qcount = qcount;
1224 data.dptr = (uint8 *)&status;
1225 data.dsize = sizeof(status);
1226 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1229 * Update the cache time again. We want to do this call
1230 * as little as possible...
1233 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1234 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1236 /* clear the msg pending record for this queue */
1238 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1240 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1241 /* log a message but continue on */
1243 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1244 sharename));
1247 release_print_db( pdb );
1249 return;
1252 /****************************************************************************
1253 Update the internal database from the system print queue for a queue.
1254 obtain a lock on the print queue before proceeding (needed when mutiple
1255 smbd processes maytry to update the lpq cache concurrently).
1256 ****************************************************************************/
1258 static void print_queue_update_with_lock( const char *sharename,
1259 struct printif *current_printif,
1260 char *lpq_command, char *lprm_command )
1262 fstring keystr;
1263 struct tdb_print_db *pdb;
1265 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1266 pdb = get_print_db_byname(sharename);
1267 if (!pdb)
1268 return;
1270 if ( !print_cache_expired(sharename, False) ) {
1271 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1272 release_print_db(pdb);
1273 return;
1277 * Check to see if someone else is doing this update.
1278 * This is essentially a mutex on the update.
1281 if (get_updating_pid(sharename) != -1) {
1282 release_print_db(pdb);
1283 return;
1286 /* Lock the queue for the database update */
1288 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1289 /* Only wait 10 seconds for this. */
1290 if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) == -1) {
1291 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1292 release_print_db(pdb);
1293 return;
1297 * Ensure that no one else got in here.
1298 * If the updating pid is still -1 then we are
1299 * the winner.
1302 if (get_updating_pid(sharename) != -1) {
1304 * Someone else is doing the update, exit.
1306 tdb_unlock_bystring(pdb->tdb, keystr);
1307 release_print_db(pdb);
1308 return;
1312 * We're going to do the update ourselves.
1315 /* Tell others we're doing the update. */
1316 set_updating_pid(sharename, True);
1319 * Allow others to enter and notice we're doing
1320 * the update.
1323 tdb_unlock_bystring(pdb->tdb, keystr);
1325 /* do the main work now */
1327 print_queue_update_internal( sharename, current_printif,
1328 lpq_command, lprm_command );
1330 /* Delete our pid from the db. */
1331 set_updating_pid(sharename, False);
1332 release_print_db(pdb);
1335 /****************************************************************************
1336 this is the receive function of the background lpq updater
1337 ****************************************************************************/
1338 static void print_queue_receive(struct messaging_context *msg,
1339 void *private_data,
1340 uint32_t msg_type,
1341 struct server_id server_id,
1342 DATA_BLOB *data)
1344 fstring sharename;
1345 char *lpqcommand = NULL, *lprmcommand = NULL;
1346 int printing_type;
1347 size_t len;
1349 len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1350 sharename,
1351 &printing_type,
1352 &lpqcommand,
1353 &lprmcommand );
1355 if ( len == -1 ) {
1356 SAFE_FREE(lpqcommand);
1357 SAFE_FREE(lprmcommand);
1358 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1359 return;
1362 print_queue_update_with_lock(sharename,
1363 get_printer_fns_from_type((enum printing_types)printing_type),
1364 lpqcommand, lprmcommand );
1366 SAFE_FREE(lpqcommand);
1367 SAFE_FREE(lprmcommand);
1368 return;
1371 static void printing_pause_fd_handler(struct tevent_context *ev,
1372 struct tevent_fd *fde,
1373 uint16_t flags,
1374 void *private_data)
1377 * If pause_pipe[1] is closed it means the parent smbd
1378 * and children exited or aborted.
1380 exit_server_cleanly(NULL);
1383 static void add_child_pid(pid_t pid)
1385 extern struct child_pid *children;
1386 struct child_pid *child;
1387 extern int num_children;
1389 child = SMB_MALLOC_P(struct child_pid);
1390 if (child == NULL) {
1391 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
1392 return;
1394 child->pid = pid;
1395 DLIST_ADD(children, child);
1396 num_children += 1;
1399 static pid_t background_lpq_updater_pid = -1;
1401 /****************************************************************************
1402 main thread of the background lpq updater
1403 ****************************************************************************/
1404 void start_background_queue(void)
1406 /* Use local variables for this as we don't
1407 * need to save the parent side of this, just
1408 * ensure it closes when the process exits.
1410 int pause_pipe[2];
1412 DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
1414 if (pipe(pause_pipe) == -1) {
1415 DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
1416 exit(1);
1419 background_lpq_updater_pid = sys_fork();
1421 if (background_lpq_updater_pid == -1) {
1422 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
1423 exit(1);
1426 /* Track the printing pid along with other smbd children */
1427 add_child_pid(background_lpq_updater_pid);
1429 if(background_lpq_updater_pid == 0) {
1430 struct tevent_fd *fde;
1431 int ret;
1433 /* Child. */
1434 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
1436 close(pause_pipe[0]);
1437 pause_pipe[0] = -1;
1439 if (!NT_STATUS_IS_OK(reinit_after_fork(smbd_messaging_context(),
1440 smbd_event_context(),
1441 true))) {
1442 DEBUG(0,("reinit_after_fork() failed\n"));
1443 smb_panic("reinit_after_fork() failed");
1446 smbd_setup_sig_term_handler();
1447 smbd_setup_sig_hup_handler();
1449 if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_SMBD
1450 |FLAG_MSG_PRINT_GENERAL)) {
1451 exit(1);
1454 if (!locking_init()) {
1455 exit(1);
1458 messaging_register(smbd_messaging_context(), NULL,
1459 MSG_PRINTER_UPDATE, print_queue_receive);
1461 fde = tevent_add_fd(smbd_event_context(), smbd_event_context(),
1462 pause_pipe[1], TEVENT_FD_READ,
1463 printing_pause_fd_handler,
1464 NULL);
1465 if (!fde) {
1466 DEBUG(0,("tevent_add_fd() failed for pause_pipe\n"));
1467 smb_panic("tevent_add_fd() failed for pause_pipe");
1470 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
1471 ret = tevent_loop_wait(smbd_event_context());
1472 /* should not be reached */
1473 DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
1474 ret, (ret == 0) ? "out of events" : strerror(errno)));
1475 exit(1);
1478 close(pause_pipe[1]);
1481 /****************************************************************************
1482 update the internal database from the system print queue for a queue
1483 ****************************************************************************/
1485 static void print_queue_update(int snum, bool force)
1487 fstring key;
1488 fstring sharename;
1489 char *lpqcommand = NULL;
1490 char *lprmcommand = NULL;
1491 uint8 *buffer = NULL;
1492 size_t len = 0;
1493 size_t newlen;
1494 struct tdb_print_db *pdb;
1495 int type;
1496 struct printif *current_printif;
1497 TALLOC_CTX *ctx = talloc_tos();
1499 fstrcpy( sharename, lp_const_servicename(snum));
1501 /* don't strip out characters like '$' from the printername */
1503 lpqcommand = talloc_string_sub2(ctx,
1504 lp_lpqcommand(snum),
1505 "%p",
1506 PRINTERNAME(snum),
1507 false, false, false);
1508 if (!lpqcommand) {
1509 return;
1511 lpqcommand = talloc_sub_advanced(ctx,
1512 lp_servicename(snum),
1513 current_user_info.unix_name,
1515 current_user.ut.gid,
1516 get_current_username(),
1517 current_user_info.domain,
1518 lpqcommand);
1519 if (!lpqcommand) {
1520 return;
1523 lprmcommand = talloc_string_sub2(ctx,
1524 lp_lprmcommand(snum),
1525 "%p",
1526 PRINTERNAME(snum),
1527 false, false, false);
1528 if (!lprmcommand) {
1529 return;
1531 lprmcommand = talloc_sub_advanced(ctx,
1532 lp_servicename(snum),
1533 current_user_info.unix_name,
1535 current_user.ut.gid,
1536 get_current_username(),
1537 current_user_info.domain,
1538 lprmcommand);
1539 if (!lprmcommand) {
1540 return;
1544 * Make sure that the background queue process exists.
1545 * Otherwise just do the update ourselves
1548 if ( force || background_lpq_updater_pid == -1 ) {
1549 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1550 current_printif = get_printer_fns( snum );
1551 print_queue_update_with_lock( sharename, current_printif, lpqcommand, lprmcommand );
1553 return;
1556 type = lp_printing(snum);
1558 /* get the length */
1560 len = tdb_pack( NULL, 0, "fdPP",
1561 sharename,
1562 type,
1563 lpqcommand,
1564 lprmcommand );
1566 buffer = SMB_XMALLOC_ARRAY( uint8, len );
1568 /* now pack the buffer */
1569 newlen = tdb_pack( buffer, len, "fdPP",
1570 sharename,
1571 type,
1572 lpqcommand,
1573 lprmcommand );
1575 SMB_ASSERT( newlen == len );
1577 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1578 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1579 sharename, type, lpqcommand, lprmcommand ));
1581 /* here we set a msg pending record for other smbd processes
1582 to throttle the number of duplicate print_queue_update msgs
1583 sent. */
1585 pdb = get_print_db_byname(sharename);
1586 if (!pdb) {
1587 SAFE_FREE(buffer);
1588 return;
1591 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1593 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1594 /* log a message but continue on */
1596 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1597 sharename));
1600 release_print_db( pdb );
1602 /* finally send the message */
1604 messaging_send_buf(smbd_messaging_context(),
1605 pid_to_procid(background_lpq_updater_pid),
1606 MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1608 SAFE_FREE( buffer );
1610 return;
1613 /****************************************************************************
1614 Create/Update an entry in the print tdb that will allow us to send notify
1615 updates only to interested smbd's.
1616 ****************************************************************************/
1618 bool print_notify_register_pid(int snum)
1620 TDB_DATA data;
1621 struct tdb_print_db *pdb = NULL;
1622 TDB_CONTEXT *tdb = NULL;
1623 const char *printername;
1624 uint32 mypid = (uint32)sys_getpid();
1625 bool ret = False;
1626 size_t i;
1628 /* if (snum == -1), then the change notify request was
1629 on a print server handle and we need to register on
1630 all print queus */
1632 if (snum == -1)
1634 int num_services = lp_numservices();
1635 int idx;
1637 for ( idx=0; idx<num_services; idx++ ) {
1638 if (lp_snum_ok(idx) && lp_print_ok(idx) )
1639 print_notify_register_pid(idx);
1642 return True;
1644 else /* register for a specific printer */
1646 printername = lp_const_servicename(snum);
1647 pdb = get_print_db_byname(printername);
1648 if (!pdb)
1649 return False;
1650 tdb = pdb->tdb;
1653 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1654 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1655 printername));
1656 if (pdb)
1657 release_print_db(pdb);
1658 return False;
1661 data = get_printer_notify_pid_list( tdb, printername, True );
1663 /* Add ourselves and increase the refcount. */
1665 for (i = 0; i < data.dsize; i += 8) {
1666 if (IVAL(data.dptr,i) == mypid) {
1667 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1668 SIVAL(data.dptr, i+4, new_refcount);
1669 break;
1673 if (i == data.dsize) {
1674 /* We weren't in the list. Realloc. */
1675 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1676 if (!data.dptr) {
1677 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1678 printername));
1679 goto done;
1681 data.dsize += 8;
1682 SIVAL(data.dptr,data.dsize - 8,mypid);
1683 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1686 /* Store back the record. */
1687 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1688 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1689 list for printer %s\n", printername));
1690 goto done;
1693 ret = True;
1695 done:
1697 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1698 if (pdb)
1699 release_print_db(pdb);
1700 SAFE_FREE(data.dptr);
1701 return ret;
1704 /****************************************************************************
1705 Update an entry in the print tdb that will allow us to send notify
1706 updates only to interested smbd's.
1707 ****************************************************************************/
1709 bool print_notify_deregister_pid(int snum)
1711 TDB_DATA data;
1712 struct tdb_print_db *pdb = NULL;
1713 TDB_CONTEXT *tdb = NULL;
1714 const char *printername;
1715 uint32 mypid = (uint32)sys_getpid();
1716 size_t i;
1717 bool ret = False;
1719 /* if ( snum == -1 ), we are deregister a print server handle
1720 which means to deregister on all print queues */
1722 if (snum == -1)
1724 int num_services = lp_numservices();
1725 int idx;
1727 for ( idx=0; idx<num_services; idx++ ) {
1728 if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1729 print_notify_deregister_pid(idx);
1732 return True;
1734 else /* deregister a specific printer */
1736 printername = lp_const_servicename(snum);
1737 pdb = get_print_db_byname(printername);
1738 if (!pdb)
1739 return False;
1740 tdb = pdb->tdb;
1743 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1744 DEBUG(0,("print_notify_register_pid: Failed to lock \
1745 printer %s database\n", printername));
1746 if (pdb)
1747 release_print_db(pdb);
1748 return False;
1751 data = get_printer_notify_pid_list( tdb, printername, True );
1753 /* Reduce refcount. Remove ourselves if zero. */
1755 for (i = 0; i < data.dsize; ) {
1756 if (IVAL(data.dptr,i) == mypid) {
1757 uint32 refcount = IVAL(data.dptr, i+4);
1759 refcount--;
1761 if (refcount == 0) {
1762 if (data.dsize - i > 8)
1763 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1764 data.dsize -= 8;
1765 continue;
1767 SIVAL(data.dptr, i+4, refcount);
1770 i += 8;
1773 if (data.dsize == 0)
1774 SAFE_FREE(data.dptr);
1776 /* Store back the record. */
1777 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1778 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1779 list for printer %s\n", printername));
1780 goto done;
1783 ret = True;
1785 done:
1787 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1788 if (pdb)
1789 release_print_db(pdb);
1790 SAFE_FREE(data.dptr);
1791 return ret;
1794 /****************************************************************************
1795 Check if a jobid is valid. It is valid if it exists in the database.
1796 ****************************************************************************/
1798 bool print_job_exists(const char* sharename, uint32 jobid)
1800 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1801 bool ret;
1802 uint32_t tmp;
1804 if (!pdb)
1805 return False;
1806 ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
1807 release_print_db(pdb);
1808 return ret;
1811 /****************************************************************************
1812 Give the fd used for a jobid.
1813 ****************************************************************************/
1815 int print_job_fd(const char* sharename, uint32 jobid)
1817 struct printjob *pjob = print_job_find(sharename, jobid);
1818 if (!pjob)
1819 return -1;
1820 /* don't allow another process to get this info - it is meaningless */
1821 if (pjob->pid != sys_getpid())
1822 return -1;
1823 return pjob->fd;
1826 /****************************************************************************
1827 Give the filename used for a jobid.
1828 Only valid for the process doing the spooling and when the job
1829 has not been spooled.
1830 ****************************************************************************/
1832 char *print_job_fname(const char* sharename, uint32 jobid)
1834 struct printjob *pjob = print_job_find(sharename, jobid);
1835 if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
1836 return NULL;
1837 return pjob->filename;
1841 /****************************************************************************
1842 Give the filename used for a jobid.
1843 Only valid for the process doing the spooling and when the job
1844 has not been spooled.
1845 ****************************************************************************/
1847 NT_DEVICEMODE *print_job_devmode(const char* sharename, uint32 jobid)
1849 struct printjob *pjob = print_job_find(sharename, jobid);
1851 if ( !pjob )
1852 return NULL;
1854 return pjob->nt_devmode;
1857 /****************************************************************************
1858 Set the name of a job. Only possible for owner.
1859 ****************************************************************************/
1861 bool print_job_set_name(const char *sharename, uint32 jobid, const char *name)
1863 struct printjob *pjob;
1865 pjob = print_job_find(sharename, jobid);
1866 if (!pjob || pjob->pid != sys_getpid())
1867 return False;
1869 fstrcpy(pjob->jobname, name);
1870 return pjob_store(sharename, jobid, pjob);
1873 /****************************************************************************
1874 Get the name of a job. Only possible for owner.
1875 ****************************************************************************/
1877 bool print_job_get_name(TALLOC_CTX *mem_ctx, const char *sharename, uint32_t jobid, char **name)
1879 struct printjob *pjob;
1881 pjob = print_job_find(sharename, jobid);
1882 if (!pjob || pjob->pid != sys_getpid()) {
1883 return false;
1886 *name = talloc_strdup(mem_ctx, pjob->jobname);
1887 if (!*name) {
1888 return false;
1891 return true;
1895 /***************************************************************************
1896 Remove a jobid from the 'jobs changed' list.
1897 ***************************************************************************/
1899 static bool remove_from_jobs_changed(const char* sharename, uint32 jobid)
1901 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1902 TDB_DATA data, key;
1903 size_t job_count, i;
1904 bool ret = False;
1905 bool gotlock = False;
1907 if (!pdb) {
1908 return False;
1911 ZERO_STRUCT(data);
1913 key = string_tdb_data("INFO/jobs_changed");
1915 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
1916 goto out;
1918 gotlock = True;
1920 data = tdb_fetch(pdb->tdb, key);
1922 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
1923 goto out;
1925 job_count = data.dsize / 4;
1926 for (i = 0; i < job_count; i++) {
1927 uint32 ch_jobid;
1929 ch_jobid = IVAL(data.dptr, i*4);
1930 if (ch_jobid == jobid) {
1931 if (i < job_count -1 )
1932 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
1933 data.dsize -= 4;
1934 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
1935 goto out;
1936 break;
1940 ret = True;
1941 out:
1943 if (gotlock)
1944 tdb_chainunlock(pdb->tdb, key);
1945 SAFE_FREE(data.dptr);
1946 release_print_db(pdb);
1947 if (ret)
1948 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
1949 else
1950 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
1951 return ret;
1954 /****************************************************************************
1955 Delete a print job - don't update queue.
1956 ****************************************************************************/
1958 static bool print_job_delete1(int snum, uint32 jobid)
1960 const char* sharename = lp_const_servicename(snum);
1961 struct printjob *pjob = print_job_find(sharename, jobid);
1962 int result = 0;
1963 struct printif *current_printif = get_printer_fns( snum );
1965 if (!pjob)
1966 return False;
1969 * If already deleting just return.
1972 if (pjob->status == LPQ_DELETING)
1973 return True;
1975 /* Hrm - we need to be able to cope with deleting a job before it
1976 has reached the spooler. Just mark it as LPQ_DELETING and
1977 let the print_queue_update() code rmeove the record */
1980 if (pjob->sysjob == -1) {
1981 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
1984 /* Set the tdb entry to be deleting. */
1986 pjob->status = LPQ_DELETING;
1987 pjob_store(sharename, jobid, pjob);
1989 if (pjob->spooled && pjob->sysjob != -1)
1991 result = (*(current_printif->job_delete))(
1992 PRINTERNAME(snum),
1993 lp_lprmcommand(snum),
1994 pjob);
1996 /* Delete the tdb entry if the delete succeeded or the job hasn't
1997 been spooled. */
1999 if (result == 0) {
2000 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2001 int njobs = 1;
2003 if (!pdb)
2004 return False;
2005 pjob_delete(sharename, jobid);
2006 /* Ensure we keep a rough count of the number of total jobs... */
2007 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
2008 release_print_db(pdb);
2012 remove_from_jobs_changed( sharename, jobid );
2014 return (result == 0);
2017 /****************************************************************************
2018 Return true if the current user owns the print job.
2019 ****************************************************************************/
2021 static bool is_owner(struct auth_serversupplied_info *server_info,
2022 const char *servicename,
2023 uint32 jobid)
2025 struct printjob *pjob = print_job_find(servicename, jobid);
2027 if (!pjob || !server_info)
2028 return False;
2030 return strequal(pjob->user, server_info->sanitized_username);
2033 /****************************************************************************
2034 Delete a print job.
2035 ****************************************************************************/
2037 bool print_job_delete(struct auth_serversupplied_info *server_info, int snum,
2038 uint32 jobid, WERROR *errcode)
2040 const char* sharename = lp_const_servicename( snum );
2041 struct printjob *pjob;
2042 bool owner;
2043 char *fname;
2045 *errcode = WERR_OK;
2047 owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2049 /* Check access against security descriptor or whether the user
2050 owns their job. */
2052 if (!owner &&
2053 !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2054 DEBUG(3, ("delete denied by security descriptor\n"));
2055 *errcode = WERR_ACCESS_DENIED;
2057 /* BEGIN_ADMIN_LOG */
2058 sys_adminlog( LOG_ERR,
2059 "Permission denied-- user not allowed to delete, \
2060 pause, or resume print job. User name: %s. Printer name: %s.",
2061 uidtoname(server_info->utok.uid),
2062 PRINTERNAME(snum) );
2063 /* END_ADMIN_LOG */
2065 return False;
2069 * get the spooled filename of the print job
2070 * if this works, then the file has not been spooled
2071 * to the underlying print system. Just delete the
2072 * spool file & return.
2075 if ( (fname = print_job_fname( sharename, jobid )) != NULL )
2077 /* remove the spool file */
2078 DEBUG(10,("print_job_delete: Removing spool file [%s]\n", fname ));
2079 if ( unlink( fname ) == -1 ) {
2080 *errcode = map_werror_from_unix(errno);
2081 return False;
2085 if (!print_job_delete1(snum, jobid)) {
2086 *errcode = WERR_ACCESS_DENIED;
2087 return False;
2090 /* force update the database and say the delete failed if the
2091 job still exists */
2093 print_queue_update(snum, True);
2095 pjob = print_job_find(sharename, jobid);
2096 if ( pjob && (pjob->status != LPQ_DELETING) )
2097 *errcode = WERR_ACCESS_DENIED;
2099 return (pjob == NULL );
2102 /****************************************************************************
2103 Pause a job.
2104 ****************************************************************************/
2106 bool print_job_pause(struct auth_serversupplied_info *server_info, int snum,
2107 uint32 jobid, WERROR *errcode)
2109 const char* sharename = lp_const_servicename(snum);
2110 struct printjob *pjob;
2111 int ret = -1;
2112 struct printif *current_printif = get_printer_fns( snum );
2114 pjob = print_job_find(sharename, jobid);
2116 if (!pjob || !server_info) {
2117 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2118 (unsigned int)jobid ));
2119 return False;
2122 if (!pjob->spooled || pjob->sysjob == -1) {
2123 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2124 (int)pjob->sysjob, (unsigned int)jobid ));
2125 return False;
2128 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2129 !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2130 DEBUG(3, ("pause denied by security descriptor\n"));
2132 /* BEGIN_ADMIN_LOG */
2133 sys_adminlog( LOG_ERR,
2134 "Permission denied-- user not allowed to delete, \
2135 pause, or resume print job. User name: %s. Printer name: %s.",
2136 uidtoname(server_info->utok.uid),
2137 PRINTERNAME(snum) );
2138 /* END_ADMIN_LOG */
2140 *errcode = WERR_ACCESS_DENIED;
2141 return False;
2144 /* need to pause the spooled entry */
2145 ret = (*(current_printif->job_pause))(snum, pjob);
2147 if (ret != 0) {
2148 *errcode = WERR_INVALID_PARAM;
2149 return False;
2152 /* force update the database */
2153 print_cache_flush(lp_const_servicename(snum));
2155 /* Send a printer notify message */
2157 notify_job_status(sharename, jobid, JOB_STATUS_PAUSED);
2159 /* how do we tell if this succeeded? */
2161 return True;
2164 /****************************************************************************
2165 Resume a job.
2166 ****************************************************************************/
2168 bool print_job_resume(struct auth_serversupplied_info *server_info, int snum,
2169 uint32 jobid, WERROR *errcode)
2171 const char *sharename = lp_const_servicename(snum);
2172 struct printjob *pjob;
2173 int ret;
2174 struct printif *current_printif = get_printer_fns( snum );
2176 pjob = print_job_find(sharename, jobid);
2178 if (!pjob || !server_info) {
2179 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2180 (unsigned int)jobid ));
2181 return False;
2184 if (!pjob->spooled || pjob->sysjob == -1) {
2185 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2186 (int)pjob->sysjob, (unsigned int)jobid ));
2187 return False;
2190 if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2191 !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
2192 DEBUG(3, ("resume denied by security descriptor\n"));
2193 *errcode = WERR_ACCESS_DENIED;
2195 /* BEGIN_ADMIN_LOG */
2196 sys_adminlog( LOG_ERR,
2197 "Permission denied-- user not allowed to delete, \
2198 pause, or resume print job. User name: %s. Printer name: %s.",
2199 uidtoname(server_info->utok.uid),
2200 PRINTERNAME(snum) );
2201 /* END_ADMIN_LOG */
2202 return False;
2205 ret = (*(current_printif->job_resume))(snum, pjob);
2207 if (ret != 0) {
2208 *errcode = WERR_INVALID_PARAM;
2209 return False;
2212 /* force update the database */
2213 print_cache_flush(lp_const_servicename(snum));
2215 /* Send a printer notify message */
2217 notify_job_status(sharename, jobid, JOB_STATUS_QUEUED);
2219 return True;
2222 /****************************************************************************
2223 Write to a print file.
2224 ****************************************************************************/
2226 ssize_t print_job_write(int snum, uint32 jobid, const char *buf, SMB_OFF_T pos, size_t size)
2228 const char* sharename = lp_const_servicename(snum);
2229 ssize_t return_code;
2230 struct printjob *pjob;
2232 pjob = print_job_find(sharename, jobid);
2234 if (!pjob)
2235 return -1;
2236 /* don't allow another process to get this info - it is meaningless */
2237 if (pjob->pid != sys_getpid())
2238 return -1;
2240 return_code = write_data_at_offset(pjob->fd, buf, size, pos);
2242 if (return_code>0) {
2243 pjob->size += size;
2244 pjob_store(sharename, jobid, pjob);
2246 return return_code;
2249 /****************************************************************************
2250 Get the queue status - do not update if db is out of date.
2251 ****************************************************************************/
2253 static int get_queue_status(const char* sharename, print_status_struct *status)
2255 fstring keystr;
2256 TDB_DATA data;
2257 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2258 int len;
2260 if (status) {
2261 ZERO_STRUCTP(status);
2264 if (!pdb)
2265 return 0;
2267 if (status) {
2268 fstr_sprintf(keystr, "STATUS/%s", sharename);
2269 data = tdb_fetch(pdb->tdb, string_tdb_data(keystr));
2270 if (data.dptr) {
2271 if (data.dsize == sizeof(print_status_struct))
2272 /* this memcpy is ok since the status struct was
2273 not packed before storing it in the tdb */
2274 memcpy(status, data.dptr, sizeof(print_status_struct));
2275 SAFE_FREE(data.dptr);
2278 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2279 release_print_db(pdb);
2280 return (len == -1 ? 0 : len);
2283 /****************************************************************************
2284 Determine the number of jobs in a queue.
2285 ****************************************************************************/
2287 int print_queue_length(int snum, print_status_struct *pstatus)
2289 const char* sharename = lp_const_servicename( snum );
2290 print_status_struct status;
2291 int len;
2293 ZERO_STRUCT( status );
2295 /* make sure the database is up to date */
2296 if (print_cache_expired(lp_const_servicename(snum), True))
2297 print_queue_update(snum, False);
2299 /* also fetch the queue status */
2300 memset(&status, 0, sizeof(status));
2301 len = get_queue_status(sharename, &status);
2303 if (pstatus)
2304 *pstatus = status;
2306 return len;
2309 /***************************************************************************
2310 Allocate a jobid. Hold the lock for as short a time as possible.
2311 ***************************************************************************/
2313 static bool allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char *sharename, uint32 *pjobid)
2315 int i;
2316 uint32 jobid;
2318 *pjobid = (uint32)-1;
2320 for (i = 0; i < 3; i++) {
2321 /* Lock the database - only wait 20 seconds. */
2322 if (tdb_lock_bystring_with_timeout(pdb->tdb, "INFO/nextjob", 20) == -1) {
2323 DEBUG(0,("allocate_print_jobid: failed to lock printing database %s\n", sharename));
2324 return False;
2327 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2328 if (tdb_error(pdb->tdb) != TDB_ERR_NOEXIST) {
2329 DEBUG(0, ("allocate_print_jobid: failed to fetch INFO/nextjob for print queue %s\n",
2330 sharename));
2331 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2332 return False;
2334 DEBUG(10,("allocate_print_jobid: no existing jobid in %s\n", sharename));
2335 jobid = 0;
2338 DEBUG(10,("allocate_print_jobid: read jobid %u from %s\n", jobid, sharename));
2340 jobid = NEXT_JOBID(jobid);
2342 if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
2343 DEBUG(3, ("allocate_print_jobid: failed to store INFO/nextjob.\n"));
2344 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2345 return False;
2348 /* We've finished with the INFO/nextjob lock. */
2349 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2351 if (!print_job_exists(sharename, jobid)) {
2352 break;
2354 DEBUG(10,("allocate_print_jobid: found jobid %u in %s\n", jobid, sharename));
2357 if (i > 2) {
2358 DEBUG(0, ("allocate_print_jobid: failed to allocate a print job for queue %s\n",
2359 sharename));
2360 /* Probably full... */
2361 errno = ENOSPC;
2362 return False;
2365 /* Store a dummy placeholder. */
2367 uint32_t tmp;
2368 TDB_DATA dum;
2369 dum.dptr = NULL;
2370 dum.dsize = 0;
2371 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2372 TDB_INSERT) == -1) {
2373 DEBUG(3, ("allocate_print_jobid: jobid (%d) failed to store placeholder.\n",
2374 jobid ));
2375 return False;
2379 *pjobid = jobid;
2380 return True;
2383 /***************************************************************************
2384 Append a jobid to the 'jobs changed' list.
2385 ***************************************************************************/
2387 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32 jobid)
2389 TDB_DATA data;
2390 uint32 store_jobid;
2392 SIVAL(&store_jobid, 0, jobid);
2393 data.dptr = (uint8 *)&store_jobid;
2394 data.dsize = 4;
2396 DEBUG(10,("add_to_jobs_changed: Added jobid %u\n", (unsigned int)jobid ));
2398 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
2399 data) == 0);
2402 /***************************************************************************
2403 Start spooling a job - return the jobid.
2404 ***************************************************************************/
2406 uint32 print_job_start(struct auth_serversupplied_info *server_info, int snum,
2407 const char *jobname, NT_DEVICEMODE *nt_devmode )
2409 uint32 jobid;
2410 char *path;
2411 struct printjob pjob;
2412 const char *sharename = lp_const_servicename(snum);
2413 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2414 int njobs;
2416 errno = 0;
2418 if (!pdb)
2419 return (uint32)-1;
2421 if (!print_access_check(server_info, snum, PRINTER_ACCESS_USE)) {
2422 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
2423 release_print_db(pdb);
2424 return (uint32)-1;
2427 if (!print_time_access_check(lp_servicename(snum))) {
2428 DEBUG(3, ("print_job_start: job start denied by time check\n"));
2429 release_print_db(pdb);
2430 return (uint32)-1;
2433 path = lp_pathname(snum);
2435 /* see if we have sufficient disk space */
2436 if (lp_minprintspace(snum)) {
2437 uint64_t dspace, dsize;
2438 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
2439 dspace < 2*(uint64_t)lp_minprintspace(snum)) {
2440 DEBUG(3, ("print_job_start: disk space check failed.\n"));
2441 release_print_db(pdb);
2442 errno = ENOSPC;
2443 return (uint32)-1;
2447 /* for autoloaded printers, check that the printcap entry still exists */
2448 if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum))) {
2449 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
2450 release_print_db(pdb);
2451 errno = ENOENT;
2452 return (uint32)-1;
2455 /* Insure the maximum queue size is not violated */
2456 if ((njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
2457 DEBUG(3, ("print_job_start: Queue %s number of jobs (%d) larger than max printjobs per queue (%d).\n",
2458 sharename, njobs, lp_maxprintjobs(snum) ));
2459 release_print_db(pdb);
2460 errno = ENOSPC;
2461 return (uint32)-1;
2464 DEBUG(10,("print_job_start: Queue %s number of jobs (%d), max printjobs = %d\n",
2465 sharename, njobs, lp_maxprintjobs(snum) ));
2467 if (!allocate_print_jobid(pdb, snum, sharename, &jobid))
2468 goto fail;
2470 /* create the database entry */
2472 ZERO_STRUCT(pjob);
2474 pjob.pid = sys_getpid();
2475 pjob.sysjob = -1;
2476 pjob.fd = -1;
2477 pjob.starttime = time(NULL);
2478 pjob.status = LPQ_SPOOLING;
2479 pjob.size = 0;
2480 pjob.spooled = False;
2481 pjob.smbjob = True;
2482 pjob.nt_devmode = nt_devmode;
2484 fstrcpy(pjob.jobname, jobname);
2486 fstrcpy(pjob.user, lp_printjob_username(snum));
2487 standard_sub_advanced(sharename, server_info->sanitized_username,
2488 path, server_info->utok.gid,
2489 server_info->sanitized_username,
2490 pdb_get_domain(server_info->sam_account),
2491 pjob.user, sizeof(pjob.user)-1);
2492 /* ensure NULL termination */
2493 pjob.user[sizeof(pjob.user)-1] = '\0';
2495 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2497 /* we have a job entry - now create the spool file */
2498 slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX",
2499 path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2500 pjob.fd = mkstemp(pjob.filename);
2502 if (pjob.fd == -1) {
2503 if (errno == EACCES) {
2504 /* Common setup error, force a report. */
2505 DEBUG(0, ("print_job_start: insufficient permissions \
2506 to open spool file %s.\n", pjob.filename));
2507 } else {
2508 /* Normal case, report at level 3 and above. */
2509 DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
2510 DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
2512 goto fail;
2515 pjob_store(sharename, jobid, &pjob);
2517 /* Update the 'jobs changed' entry used by print_queue_status. */
2518 add_to_jobs_changed(pdb, jobid);
2520 /* Ensure we keep a rough count of the number of total jobs... */
2521 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2523 release_print_db(pdb);
2525 return jobid;
2527 fail:
2528 if (jobid != -1)
2529 pjob_delete(sharename, jobid);
2531 release_print_db(pdb);
2533 DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
2534 return (uint32)-1;
2537 /****************************************************************************
2538 Update the number of pages spooled to jobid
2539 ****************************************************************************/
2541 void print_job_endpage(int snum, uint32 jobid)
2543 const char* sharename = lp_const_servicename(snum);
2544 struct printjob *pjob;
2546 pjob = print_job_find(sharename, jobid);
2547 if (!pjob)
2548 return;
2549 /* don't allow another process to get this info - it is meaningless */
2550 if (pjob->pid != sys_getpid())
2551 return;
2553 pjob->page_count++;
2554 pjob_store(sharename, jobid, pjob);
2557 /****************************************************************************
2558 Print a file - called on closing the file. This spools the job.
2559 If normal close is false then we're tearing down the jobs - treat as an
2560 error.
2561 ****************************************************************************/
2563 bool print_job_end(int snum, uint32 jobid, enum file_close_type close_type)
2565 const char* sharename = lp_const_servicename(snum);
2566 struct printjob *pjob;
2567 int ret;
2568 SMB_STRUCT_STAT sbuf;
2569 struct printif *current_printif = get_printer_fns( snum );
2571 pjob = print_job_find(sharename, jobid);
2573 if (!pjob)
2574 return False;
2576 if (pjob->spooled || pjob->pid != sys_getpid())
2577 return False;
2579 if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
2580 (sys_fstat(pjob->fd, &sbuf, false) == 0)) {
2581 pjob->size = sbuf.st_ex_size;
2582 close(pjob->fd);
2583 pjob->fd = -1;
2584 } else {
2587 * Not a normal close or we couldn't stat the job file,
2588 * so something has gone wrong. Cleanup.
2590 close(pjob->fd);
2591 pjob->fd = -1;
2592 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
2593 goto fail;
2596 /* Technically, this is not quite right. If the printer has a separator
2597 * page turned on, the NT spooler prints the separator page even if the
2598 * print job is 0 bytes. 010215 JRR */
2599 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
2600 /* don't bother spooling empty files or something being deleted. */
2601 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
2602 pjob->filename, pjob->size ? "deleted" : "zero length" ));
2603 unlink(pjob->filename);
2604 pjob_delete(sharename, jobid);
2605 return True;
2608 ret = (*(current_printif->job_submit))(snum, pjob);
2610 if (ret)
2611 goto fail;
2613 /* The print job has been successfully handed over to the back-end */
2615 pjob->spooled = True;
2616 pjob->status = LPQ_QUEUED;
2617 pjob_store(sharename, jobid, pjob);
2619 /* make sure the database is up to date */
2620 if (print_cache_expired(lp_const_servicename(snum), True))
2621 print_queue_update(snum, False);
2623 return True;
2625 fail:
2627 /* The print job was not successfully started. Cleanup */
2628 /* Still need to add proper error return propagation! 010122:JRR */
2629 unlink(pjob->filename);
2630 pjob_delete(sharename, jobid);
2631 return False;
2634 /****************************************************************************
2635 Get a snapshot of jobs in the system without traversing.
2636 ****************************************************************************/
2638 static bool get_stored_queue_info(struct tdb_print_db *pdb, int snum, int *pcount, print_queue_struct **ppqueue)
2640 TDB_DATA data, cgdata;
2641 print_queue_struct *queue = NULL;
2642 uint32 qcount = 0;
2643 uint32 extra_count = 0;
2644 int total_count = 0;
2645 size_t len = 0;
2646 uint32 i;
2647 int max_reported_jobs = lp_max_reported_jobs(snum);
2648 bool ret = False;
2649 const char* sharename = lp_servicename(snum);
2651 /* make sure the database is up to date */
2652 if (print_cache_expired(lp_const_servicename(snum), True))
2653 print_queue_update(snum, False);
2655 *pcount = 0;
2656 *ppqueue = NULL;
2658 ZERO_STRUCT(data);
2659 ZERO_STRUCT(cgdata);
2661 /* Get the stored queue data. */
2662 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
2664 if (data.dptr && data.dsize >= sizeof(qcount))
2665 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
2667 /* Get the changed jobs list. */
2668 cgdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
2669 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
2670 extra_count = cgdata.dsize/4;
2672 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
2674 /* Allocate the queue size. */
2675 if (qcount == 0 && extra_count == 0)
2676 goto out;
2678 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
2679 goto out;
2681 /* Retrieve the linearised queue data. */
2683 for( i = 0; i < qcount; i++) {
2684 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
2685 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
2686 &qjob,
2687 &qsize,
2688 &qpage_count,
2689 &qstatus,
2690 &qpriority,
2691 &qtime,
2692 queue[i].fs_user,
2693 queue[i].fs_file);
2694 queue[i].job = qjob;
2695 queue[i].size = qsize;
2696 queue[i].page_count = qpage_count;
2697 queue[i].status = qstatus;
2698 queue[i].priority = qpriority;
2699 queue[i].time = qtime;
2702 total_count = qcount;
2704 /* Add in the changed jobids. */
2705 for( i = 0; i < extra_count; i++) {
2706 uint32 jobid;
2707 struct printjob *pjob;
2709 jobid = IVAL(cgdata.dptr, i*4);
2710 DEBUG(5,("get_stored_queue_info: changed job = %u\n", (unsigned int)jobid));
2711 pjob = print_job_find(lp_const_servicename(snum), jobid);
2712 if (!pjob) {
2713 DEBUG(5,("get_stored_queue_info: failed to find changed job = %u\n", (unsigned int)jobid));
2714 remove_from_jobs_changed(sharename, jobid);
2715 continue;
2718 queue[total_count].job = jobid;
2719 queue[total_count].size = pjob->size;
2720 queue[total_count].page_count = pjob->page_count;
2721 queue[total_count].status = pjob->status;
2722 queue[total_count].priority = 1;
2723 queue[total_count].time = pjob->starttime;
2724 fstrcpy(queue[total_count].fs_user, pjob->user);
2725 fstrcpy(queue[total_count].fs_file, pjob->jobname);
2726 total_count++;
2729 /* Sort the queue by submission time otherwise they are displayed
2730 in hash order. */
2732 TYPESAFE_QSORT(queue, total_count, printjob_comp);
2734 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
2736 if (max_reported_jobs && total_count > max_reported_jobs)
2737 total_count = max_reported_jobs;
2739 *ppqueue = queue;
2740 *pcount = total_count;
2742 ret = True;
2744 out:
2746 SAFE_FREE(data.dptr);
2747 SAFE_FREE(cgdata.dptr);
2748 return ret;
2751 /****************************************************************************
2752 Get a printer queue listing.
2753 set queue = NULL and status = NULL if you just want to update the cache
2754 ****************************************************************************/
2756 int print_queue_status(int snum,
2757 print_queue_struct **ppqueue,
2758 print_status_struct *status)
2760 fstring keystr;
2761 TDB_DATA data, key;
2762 const char *sharename;
2763 struct tdb_print_db *pdb;
2764 int count = 0;
2766 /* make sure the database is up to date */
2768 if (print_cache_expired(lp_const_servicename(snum), True))
2769 print_queue_update(snum, False);
2771 /* return if we are done */
2772 if ( !ppqueue || !status )
2773 return 0;
2775 *ppqueue = NULL;
2776 sharename = lp_const_servicename(snum);
2777 pdb = get_print_db_byname(sharename);
2779 if (!pdb)
2780 return 0;
2783 * Fetch the queue status. We must do this first, as there may
2784 * be no jobs in the queue.
2787 ZERO_STRUCTP(status);
2788 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
2789 key = string_tdb_data(keystr);
2791 data = tdb_fetch(pdb->tdb, key);
2792 if (data.dptr) {
2793 if (data.dsize == sizeof(*status)) {
2794 /* this memcpy is ok since the status struct was
2795 not packed before storing it in the tdb */
2796 memcpy(status, data.dptr, sizeof(*status));
2798 SAFE_FREE(data.dptr);
2802 * Now, fetch the print queue information. We first count the number
2803 * of entries, and then only retrieve the queue if necessary.
2806 if (!get_stored_queue_info(pdb, snum, &count, ppqueue)) {
2807 release_print_db(pdb);
2808 return 0;
2811 release_print_db(pdb);
2812 return count;
2815 /****************************************************************************
2816 Pause a queue.
2817 ****************************************************************************/
2819 WERROR print_queue_pause(struct auth_serversupplied_info *server_info, int snum)
2821 int ret;
2822 struct printif *current_printif = get_printer_fns( snum );
2824 if (!print_access_check(server_info, snum,
2825 PRINTER_ACCESS_ADMINISTER)) {
2826 return WERR_ACCESS_DENIED;
2830 become_root();
2832 ret = (*(current_printif->queue_pause))(snum);
2834 unbecome_root();
2836 if (ret != 0) {
2837 return WERR_INVALID_PARAM;
2840 /* force update the database */
2841 print_cache_flush(lp_const_servicename(snum));
2843 /* Send a printer notify message */
2845 notify_printer_status(snum, PRINTER_STATUS_PAUSED);
2847 return WERR_OK;
2850 /****************************************************************************
2851 Resume a queue.
2852 ****************************************************************************/
2854 WERROR print_queue_resume(struct auth_serversupplied_info *server_info, int snum)
2856 int ret;
2857 struct printif *current_printif = get_printer_fns( snum );
2859 if (!print_access_check(server_info, snum,
2860 PRINTER_ACCESS_ADMINISTER)) {
2861 return WERR_ACCESS_DENIED;
2864 become_root();
2866 ret = (*(current_printif->queue_resume))(snum);
2868 unbecome_root();
2870 if (ret != 0) {
2871 return WERR_INVALID_PARAM;
2874 /* make sure the database is up to date */
2875 if (print_cache_expired(lp_const_servicename(snum), True))
2876 print_queue_update(snum, True);
2878 /* Send a printer notify message */
2880 notify_printer_status(snum, PRINTER_STATUS_OK);
2882 return WERR_OK;
2885 /****************************************************************************
2886 Purge a queue - implemented by deleting all jobs that we can delete.
2887 ****************************************************************************/
2889 WERROR print_queue_purge(struct auth_serversupplied_info *server_info, int snum)
2891 print_queue_struct *queue;
2892 print_status_struct status;
2893 int njobs, i;
2894 bool can_job_admin;
2896 /* Force and update so the count is accurate (i.e. not a cached count) */
2897 print_queue_update(snum, True);
2899 can_job_admin = print_access_check(server_info, snum,
2900 JOB_ACCESS_ADMINISTER);
2901 njobs = print_queue_status(snum, &queue, &status);
2903 if ( can_job_admin )
2904 become_root();
2906 for (i=0;i<njobs;i++) {
2907 bool owner = is_owner(server_info, lp_const_servicename(snum),
2908 queue[i].job);
2910 if (owner || can_job_admin) {
2911 print_job_delete1(snum, queue[i].job);
2915 if ( can_job_admin )
2916 unbecome_root();
2918 /* update the cache */
2919 print_queue_update( snum, True );
2921 SAFE_FREE(queue);
2923 return WERR_OK;