r20124: clean up nested extern declaration warnings
[Samba/gebeck_regimport.git] / source3 / printing / printing.c
blob2f1d123a2001ea94bcfcef4982e8a5070b9cdc6f
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 2 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, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 #include "includes.h"
24 #include "printing.h"
26 extern SIG_ATOMIC_T got_sig_term;
27 extern SIG_ATOMIC_T reload_after_sighup;
28 extern struct current_user current_user;
29 extern userdom_struct current_user_info;
31 /* Current printer interface */
32 static BOOL remove_from_jobs_changed(const char* sharename, uint32 jobid);
34 /*
35 the printing backend revolves around a tdb database that stores the
36 SMB view of the print queue
38 The key for this database is a jobid - a internally generated number that
39 uniquely identifies a print job
41 reading the print queue involves two steps:
42 - possibly running lpq and updating the internal database from that
43 - reading entries from the database
45 jobids are assigned when a job starts spooling.
48 static TDB_CONTEXT *rap_tdb;
49 static uint16 next_rap_jobid;
50 struct rap_jobid_key {
51 fstring sharename;
52 uint32 jobid;
55 /***************************************************************************
56 Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
57 bit RPC jobids.... JRA.
58 ***************************************************************************/
60 uint16 pjobid_to_rap(const char* sharename, uint32 jobid)
62 uint16 rap_jobid;
63 TDB_DATA data, key;
64 struct rap_jobid_key jinfo;
65 uint8 buf[2];
67 DEBUG(10,("pjobid_to_rap: called.\n"));
69 if (!rap_tdb) {
70 /* Create the in-memory tdb. */
71 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
72 if (!rap_tdb)
73 return 0;
76 ZERO_STRUCT( jinfo );
77 fstrcpy( jinfo.sharename, sharename );
78 jinfo.jobid = jobid;
79 key.dptr = (char*)&jinfo;
80 key.dsize = sizeof(jinfo);
82 data = tdb_fetch(rap_tdb, key);
83 if (data.dptr && data.dsize == sizeof(uint16)) {
84 rap_jobid = SVAL(data.dptr, 0);
85 SAFE_FREE(data.dptr);
86 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
87 (unsigned int)jobid, (unsigned int)rap_jobid));
88 return rap_jobid;
90 SAFE_FREE(data.dptr);
91 /* Not found - create and store mapping. */
92 rap_jobid = ++next_rap_jobid;
93 if (rap_jobid == 0)
94 rap_jobid = ++next_rap_jobid;
95 SSVAL(buf,0,rap_jobid);
96 data.dptr = (char*)buf;
97 data.dsize = sizeof(rap_jobid);
98 tdb_store(rap_tdb, key, data, TDB_REPLACE);
99 tdb_store(rap_tdb, data, key, TDB_REPLACE);
101 DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
102 (unsigned int)jobid, (unsigned int)rap_jobid));
103 return rap_jobid;
106 BOOL rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
108 TDB_DATA data, key;
109 uint8 buf[2];
111 DEBUG(10,("rap_to_pjobid called.\n"));
113 if (!rap_tdb)
114 return False;
116 SSVAL(buf,0,rap_jobid);
117 key.dptr = (char*)buf;
118 key.dsize = sizeof(rap_jobid);
119 data = tdb_fetch(rap_tdb, key);
120 if ( data.dptr && data.dsize == sizeof(struct rap_jobid_key) )
122 struct rap_jobid_key *jinfo = (struct rap_jobid_key*)data.dptr;
123 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 = (char*)&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 = (char*)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(void)
183 const char *sversion = "INFO/version";
184 pstring printing_path;
185 int services = lp_numservices();
186 int snum;
188 unlink(lock_path("printing.tdb"));
189 pstrcpy(printing_path,lock_path("printing"));
190 mkdir(printing_path,0755);
192 /* handle a Samba upgrade */
194 for (snum = 0; snum < services; snum++) {
195 struct tdb_print_db *pdb;
196 if (!lp_print_ok(snum))
197 continue;
199 pdb = get_print_db_byname(lp_const_servicename(snum));
200 if (!pdb)
201 continue;
202 if (tdb_lock_bystring(pdb->tdb, sversion) == -1) {
203 DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
204 release_print_db(pdb);
205 return False;
207 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
208 tdb_traverse(pdb->tdb, tdb_traverse_delete_fn, NULL);
209 tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
211 tdb_unlock_bystring(pdb->tdb, sversion);
212 release_print_db(pdb);
215 close_all_print_db(); /* Don't leave any open. */
217 /* do NT print initialization... */
218 return nt_printing_init();
221 /****************************************************************************
222 Shut down printing backend. Called once at shutdown to close the tdb.
223 ****************************************************************************/
225 void printing_end(void)
227 close_all_print_db(); /* Don't leave any open. */
230 /****************************************************************************
231 Retrieve the set of printing functions for a given service. This allows
232 us to set the printer function table based on the value of the 'printing'
233 service parameter.
235 Use the generic interface as the default and only use cups interface only
236 when asked for (and only when supported)
237 ****************************************************************************/
239 static struct printif *get_printer_fns_from_type( enum printing_types type )
241 struct printif *printer_fns = &generic_printif;
243 #ifdef HAVE_CUPS
244 if ( type == PRINT_CUPS ) {
245 printer_fns = &cups_printif;
247 #endif /* HAVE_CUPS */
249 #ifdef HAVE_IPRINT
250 if ( type == PRINT_IPRINT ) {
251 printer_fns = &iprint_printif;
253 #endif /* HAVE_IPRINT */
255 printer_fns->type = type;
257 return printer_fns;
260 static struct printif *get_printer_fns( int snum )
262 return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
266 /****************************************************************************
267 Useful function to generate a tdb key.
268 ****************************************************************************/
270 static TDB_DATA print_key(uint32 jobid)
272 static uint32 j;
273 TDB_DATA ret;
275 SIVAL(&j, 0, jobid);
276 ret.dptr = (char *)&j;
277 ret.dsize = sizeof(j);
278 return ret;
281 /***********************************************************************
282 unpack a pjob from a tdb buffer
283 ***********************************************************************/
285 int unpack_pjob( char* buf, int buflen, struct printjob *pjob )
287 int len = 0;
288 int used;
289 uint32 pjpid, pjsysjob, pjfd, pjstarttime, pjstatus;
290 uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
292 if ( !buf || !pjob )
293 return -1;
295 len += tdb_unpack(buf+len, buflen-len, "dddddddddffff",
296 &pjpid,
297 &pjsysjob,
298 &pjfd,
299 &pjstarttime,
300 &pjstatus,
301 &pjsize,
302 &pjpage_count,
303 &pjspooled,
304 &pjsmbjob,
305 pjob->filename,
306 pjob->jobname,
307 pjob->user,
308 pjob->queuename);
310 if ( len == -1 )
311 return -1;
313 if ( (used = unpack_devicemode(&pjob->nt_devmode, buf+len, buflen-len)) == -1 )
314 return -1;
316 len += used;
318 pjob->pid = pjpid;
319 pjob->sysjob = pjsysjob;
320 pjob->fd = pjfd;
321 pjob->starttime = pjstarttime;
322 pjob->status = pjstatus;
323 pjob->size = pjsize;
324 pjob->page_count = pjpage_count;
325 pjob->spooled = pjspooled;
326 pjob->smbjob = pjsmbjob;
328 return len;
332 /****************************************************************************
333 Useful function to find a print job in the database.
334 ****************************************************************************/
336 static struct printjob *print_job_find(const char *sharename, uint32 jobid)
338 static struct printjob pjob;
339 TDB_DATA ret;
340 struct tdb_print_db *pdb = get_print_db_byname(sharename);
342 DEBUG(10,("print_job_find: looking up job %u for share %s\n",
343 (unsigned int)jobid, sharename ));
345 if (!pdb) {
346 return NULL;
349 ret = tdb_fetch(pdb->tdb, print_key(jobid));
350 release_print_db(pdb);
352 if (!ret.dptr) {
353 DEBUG(10,("print_job_find: failed to find jobid %u.\n", (unsigned int)jobid ));
354 return NULL;
357 if ( pjob.nt_devmode ) {
358 free_nt_devicemode( &pjob.nt_devmode );
361 ZERO_STRUCT( pjob );
363 if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
364 DEBUG(10,("print_job_find: failed to unpack jobid %u.\n", (unsigned int)jobid ));
365 SAFE_FREE(ret.dptr);
366 return NULL;
369 SAFE_FREE(ret.dptr);
371 DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
372 (int)pjob.sysjob, (unsigned int)jobid ));
374 return &pjob;
377 /* Convert a unix jobid to a smb jobid */
379 static uint32 sysjob_to_jobid_value;
381 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
382 TDB_DATA data, void *state)
384 struct printjob *pjob;
385 int *sysjob = (int *)state;
387 if (!data.dptr || data.dsize == 0)
388 return 0;
390 pjob = (struct printjob *)data.dptr;
391 if (key.dsize != sizeof(uint32))
392 return 0;
394 if (*sysjob == pjob->sysjob) {
395 uint32 jobid = IVAL(key.dptr,0);
397 sysjob_to_jobid_value = jobid;
398 return 1;
401 return 0;
404 /****************************************************************************
405 This is a *horribly expensive call as we have to iterate through all the
406 current printer tdb's. Don't do this often ! JRA.
407 ****************************************************************************/
409 uint32 sysjob_to_jobid(int unix_jobid)
411 int services = lp_numservices();
412 int snum;
414 sysjob_to_jobid_value = (uint32)-1;
416 for (snum = 0; snum < services; snum++) {
417 struct tdb_print_db *pdb;
418 if (!lp_print_ok(snum))
419 continue;
420 pdb = get_print_db_byname(lp_const_servicename(snum));
421 if (!pdb) {
422 continue;
424 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &unix_jobid);
425 release_print_db(pdb);
426 if (sysjob_to_jobid_value != (uint32)-1)
427 return sysjob_to_jobid_value;
429 return (uint32)-1;
432 /****************************************************************************
433 Send notifications based on what has changed after a pjob_store.
434 ****************************************************************************/
436 static struct {
437 uint32 lpq_status;
438 uint32 spoolss_status;
439 } lpq_to_spoolss_status_map[] = {
440 { LPQ_QUEUED, JOB_STATUS_QUEUED },
441 { LPQ_PAUSED, JOB_STATUS_PAUSED },
442 { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
443 { LPQ_PRINTING, JOB_STATUS_PRINTING },
444 { LPQ_DELETING, JOB_STATUS_DELETING },
445 { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
446 { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
447 { LPQ_PRINTED, JOB_STATUS_PRINTED },
448 { LPQ_DELETED, JOB_STATUS_DELETED },
449 { LPQ_BLOCKED, JOB_STATUS_BLOCKED },
450 { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
451 { -1, 0 }
454 /* Convert a lpq status value stored in printing.tdb into the
455 appropriate win32 API constant. */
457 static uint32 map_to_spoolss_status(uint32 lpq_status)
459 int i = 0;
461 while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
462 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
463 return lpq_to_spoolss_status_map[i].spoolss_status;
464 i++;
467 return 0;
470 static void pjob_store_notify(const char* sharename, uint32 jobid, struct printjob *old_data,
471 struct printjob *new_data)
473 BOOL new_job = False;
475 if (!old_data)
476 new_job = True;
478 /* Job attributes that can't be changed. We only send
479 notification for these on a new job. */
481 /* ACHTUNG! Due to a bug in Samba's spoolss parsing of the
482 NOTIFY_INFO_DATA buffer, we *have* to send the job submission
483 time first or else we'll end up with potential alignment
484 errors. I don't think the systemtime should be spooled as
485 a string, but this gets us around that error.
486 --jerry (i'll feel dirty for this) */
488 if (new_job) {
489 notify_job_submitted(sharename, jobid, new_data->starttime);
490 notify_job_username(sharename, jobid, new_data->user);
493 if (new_job || !strequal(old_data->jobname, new_data->jobname))
494 notify_job_name(sharename, jobid, new_data->jobname);
496 /* Job attributes of a new job or attributes that can be
497 modified. */
499 if (new_job || !strequal(old_data->jobname, new_data->jobname))
500 notify_job_name(sharename, jobid, new_data->jobname);
502 if (new_job || old_data->status != new_data->status)
503 notify_job_status(sharename, jobid, map_to_spoolss_status(new_data->status));
505 if (new_job || old_data->size != new_data->size)
506 notify_job_total_bytes(sharename, jobid, new_data->size);
508 if (new_job || old_data->page_count != new_data->page_count)
509 notify_job_total_pages(sharename, jobid, new_data->page_count);
512 /****************************************************************************
513 Store a job structure back to the database.
514 ****************************************************************************/
516 static BOOL pjob_store(const char* sharename, uint32 jobid, struct printjob *pjob)
518 TDB_DATA old_data, new_data;
519 BOOL ret = False;
520 struct tdb_print_db *pdb = get_print_db_byname(sharename);
521 char *buf = NULL;
522 int len, newlen, buflen;
525 if (!pdb)
526 return False;
528 /* Get old data */
530 old_data = tdb_fetch(pdb->tdb, print_key(jobid));
532 /* Doh! Now we have to pack/unpack data since the NT_DEVICEMODE was added */
534 newlen = 0;
536 do {
537 len = 0;
538 buflen = newlen;
539 len += tdb_pack(buf+len, buflen-len, "dddddddddffff",
540 (uint32)pjob->pid,
541 (uint32)pjob->sysjob,
542 (uint32)pjob->fd,
543 (uint32)pjob->starttime,
544 (uint32)pjob->status,
545 (uint32)pjob->size,
546 (uint32)pjob->page_count,
547 (uint32)pjob->spooled,
548 (uint32)pjob->smbjob,
549 pjob->filename,
550 pjob->jobname,
551 pjob->user,
552 pjob->queuename);
554 len += pack_devicemode(pjob->nt_devmode, buf+len, buflen-len);
556 if (buflen != len) {
557 buf = (char *)SMB_REALLOC(buf, len);
558 if (!buf) {
559 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
560 goto done;
562 newlen = len;
564 } while ( buflen != len );
567 /* Store new data */
569 new_data.dptr = buf;
570 new_data.dsize = len;
571 ret = (tdb_store(pdb->tdb, print_key(jobid), new_data, TDB_REPLACE) == 0);
573 release_print_db(pdb);
575 /* Send notify updates for what has changed */
577 if ( ret ) {
578 struct printjob old_pjob;
580 if ( old_data.dsize )
582 if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
584 pjob_store_notify( sharename, jobid, &old_pjob , pjob );
585 free_nt_devicemode( &old_pjob.nt_devmode );
588 else {
589 /* new job */
590 pjob_store_notify( sharename, jobid, NULL, pjob );
594 done:
595 SAFE_FREE( old_data.dptr );
596 SAFE_FREE( buf );
598 return ret;
601 /****************************************************************************
602 Remove a job structure from the database.
603 ****************************************************************************/
605 void pjob_delete(const char* sharename, uint32 jobid)
607 struct printjob *pjob;
608 uint32 job_status = 0;
609 struct tdb_print_db *pdb;
611 pdb = get_print_db_byname( sharename );
613 if (!pdb)
614 return;
616 pjob = print_job_find( sharename, jobid );
618 if (!pjob) {
619 DEBUG(5, ("pjob_delete: we were asked to delete nonexistent job %u\n",
620 (unsigned int)jobid));
621 release_print_db(pdb);
622 return;
625 /* We must cycle through JOB_STATUS_DELETING and
626 JOB_STATUS_DELETED for the port monitor to delete the job
627 properly. */
629 job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
630 notify_job_status(sharename, jobid, job_status);
632 /* Remove from printing.tdb */
634 tdb_delete(pdb->tdb, print_key(jobid));
635 remove_from_jobs_changed(sharename, jobid);
636 release_print_db( pdb );
637 rap_jobid_delete(sharename, jobid);
640 /****************************************************************************
641 Parse a file name from the system spooler to generate a jobid.
642 ****************************************************************************/
644 static uint32 print_parse_jobid(char *fname)
646 int jobid;
648 if (strncmp(fname,PRINT_SPOOL_PREFIX,strlen(PRINT_SPOOL_PREFIX)) != 0)
649 return (uint32)-1;
650 fname += strlen(PRINT_SPOOL_PREFIX);
652 jobid = atoi(fname);
653 if (jobid <= 0)
654 return (uint32)-1;
656 return (uint32)jobid;
659 /****************************************************************************
660 List a unix job in the print database.
661 ****************************************************************************/
663 static void print_unix_job(const char *sharename, print_queue_struct *q, uint32 jobid)
665 struct printjob pj, *old_pj;
667 if (jobid == (uint32)-1)
668 jobid = q->job + UNIX_JOB_START;
670 /* Preserve the timestamp on an existing unix print job */
672 old_pj = print_job_find(sharename, jobid);
674 ZERO_STRUCT(pj);
676 pj.pid = (pid_t)-1;
677 pj.sysjob = q->job;
678 pj.fd = -1;
679 pj.starttime = old_pj ? old_pj->starttime : q->time;
680 pj.status = q->status;
681 pj.size = q->size;
682 pj.spooled = True;
683 fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
684 if (jobid < UNIX_JOB_START) {
685 pj.smbjob = True;
686 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
687 } else {
688 pj.smbjob = False;
689 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
691 fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
692 fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
694 pjob_store(sharename, jobid, &pj);
698 struct traverse_struct {
699 print_queue_struct *queue;
700 int qcount, snum, maxcount, total_jobs;
701 const char *sharename;
702 time_t lpq_time;
703 const char *lprm_command;
704 struct printif *print_if;
707 /****************************************************************************
708 Utility fn to delete any jobs that are no longer active.
709 ****************************************************************************/
711 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
713 struct traverse_struct *ts = (struct traverse_struct *)state;
714 struct printjob pjob;
715 uint32 jobid;
716 int i = 0;
718 if ( key.dsize != sizeof(jobid) )
719 return 0;
721 jobid = IVAL(key.dptr, 0);
722 if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
723 return 0;
724 free_nt_devicemode( &pjob.nt_devmode );
727 if (!pjob.smbjob) {
728 /* remove a unix job if it isn't in the system queue any more */
730 for (i=0;i<ts->qcount;i++) {
731 uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
732 if (jobid == u_jobid)
733 break;
735 if (i == ts->qcount) {
736 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
737 (unsigned int)jobid ));
738 pjob_delete(ts->sharename, jobid);
739 return 0;
742 /* need to continue the the bottom of the function to
743 save the correct attributes */
746 /* maybe it hasn't been spooled yet */
747 if (!pjob.spooled) {
748 /* if a job is not spooled and the process doesn't
749 exist then kill it. This cleans up after smbd
750 deaths */
751 if (!process_exists_by_pid(pjob.pid)) {
752 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
753 (unsigned int)jobid, (unsigned int)pjob.pid ));
754 pjob_delete(ts->sharename, jobid);
755 } else
756 ts->total_jobs++;
757 return 0;
760 /* this check only makes sense for jobs submitted from Windows clients */
762 if ( pjob.smbjob ) {
763 for (i=0;i<ts->qcount;i++) {
764 uint32 curr_jobid;
766 if ( pjob.status == LPQ_DELETED )
767 continue;
769 curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
771 if (jobid == curr_jobid) {
773 /* try to clean up any jobs that need to be deleted */
775 if ( pjob.status == LPQ_DELETING ) {
776 int result;
778 result = (*(ts->print_if->job_delete))(
779 ts->sharename, ts->lprm_command, &pjob );
781 if ( result != 0 ) {
782 /* if we can't delete, then reset the job status */
783 pjob.status = LPQ_QUEUED;
784 pjob_store(ts->sharename, jobid, &pjob);
786 else {
787 /* if we deleted the job, the remove the tdb record */
788 pjob_delete(ts->sharename, jobid);
789 pjob.status = LPQ_DELETED;
794 break;
799 /* The job isn't in the system queue - we have to assume it has
800 completed, so delete the database entry. */
802 if (i == ts->qcount) {
804 /* A race can occur between the time a job is spooled and
805 when it appears in the lpq output. This happens when
806 the job is added to printing.tdb when another smbd
807 running print_queue_update() has completed a lpq and
808 is currently traversing the printing tdb and deleting jobs.
809 Don't delete the job if it was submitted after the lpq_time. */
811 if (pjob.starttime < ts->lpq_time) {
812 DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
813 (unsigned int)jobid,
814 (unsigned int)pjob.starttime,
815 (unsigned int)ts->lpq_time ));
816 pjob_delete(ts->sharename, jobid);
817 } else
818 ts->total_jobs++;
819 return 0;
822 /* Save the pjob attributes we will store.
823 FIXME!!! This is the only place where queue->job
824 represents the SMB jobid --jerry */
826 ts->queue[i].job = jobid;
827 ts->queue[i].size = pjob.size;
828 ts->queue[i].page_count = pjob.page_count;
829 ts->queue[i].status = pjob.status;
830 ts->queue[i].priority = 1;
831 ts->queue[i].time = pjob.starttime;
832 fstrcpy(ts->queue[i].fs_user, pjob.user);
833 fstrcpy(ts->queue[i].fs_file, pjob.jobname);
835 ts->total_jobs++;
837 return 0;
840 /****************************************************************************
841 Check if the print queue has been updated recently enough.
842 ****************************************************************************/
844 static void print_cache_flush(const char *sharename)
846 fstring key;
847 struct tdb_print_db *pdb = get_print_db_byname(sharename);
849 if (!pdb)
850 return;
851 slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
852 tdb_store_int32(pdb->tdb, key, -1);
853 release_print_db(pdb);
856 /****************************************************************************
857 Check if someone already thinks they are doing the update.
858 ****************************************************************************/
860 static pid_t get_updating_pid(const char *sharename)
862 fstring keystr;
863 TDB_DATA data, key;
864 pid_t updating_pid;
865 struct tdb_print_db *pdb = get_print_db_byname(sharename);
867 if (!pdb)
868 return (pid_t)-1;
869 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
870 key.dptr = keystr;
871 key.dsize = strlen(keystr);
873 data = tdb_fetch(pdb->tdb, key);
874 release_print_db(pdb);
875 if (!data.dptr || data.dsize != sizeof(pid_t)) {
876 SAFE_FREE(data.dptr);
877 return (pid_t)-1;
880 updating_pid = IVAL(data.dptr, 0);
881 SAFE_FREE(data.dptr);
883 if (process_exists_by_pid(updating_pid))
884 return updating_pid;
886 return (pid_t)-1;
889 /****************************************************************************
890 Set the fact that we're doing the update, or have finished doing the update
891 in the tdb.
892 ****************************************************************************/
894 static void set_updating_pid(const fstring sharename, BOOL updating)
896 fstring keystr;
897 TDB_DATA key;
898 TDB_DATA data;
899 pid_t updating_pid = sys_getpid();
900 uint8 buffer[4];
902 struct tdb_print_db *pdb = get_print_db_byname(sharename);
904 if (!pdb)
905 return;
907 slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
908 key.dptr = keystr;
909 key.dsize = strlen(keystr);
911 DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
912 updating ? "" : "not ",
913 sharename ));
915 if ( !updating ) {
916 tdb_delete(pdb->tdb, key);
917 release_print_db(pdb);
918 return;
921 SIVAL( buffer, 0, updating_pid);
922 data.dptr = (char *)buffer;
923 data.dsize = 4; /* we always assume this is a 4 byte value */
925 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
926 release_print_db(pdb);
929 /****************************************************************************
930 Sort print jobs by submittal time.
931 ****************************************************************************/
933 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
935 /* Silly cases */
937 if (!j1 && !j2)
938 return 0;
939 if (!j1)
940 return -1;
941 if (!j2)
942 return 1;
944 /* Sort on job start time */
946 if (j1->time == j2->time)
947 return 0;
948 return (j1->time > j2->time) ? 1 : -1;
951 /****************************************************************************
952 Store the sorted queue representation for later portmon retrieval.
953 Skip deleted jobs
954 ****************************************************************************/
956 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
958 TDB_DATA data;
959 int max_reported_jobs = lp_max_reported_jobs(pts->snum);
960 print_queue_struct *queue = pts->queue;
961 size_t len;
962 size_t i;
963 uint qcount;
965 if (max_reported_jobs && (max_reported_jobs < pts->qcount))
966 pts->qcount = max_reported_jobs;
967 qcount = 0;
969 /* Work out the size. */
970 data.dsize = 0;
971 data.dsize += tdb_pack(NULL, 0, "d", qcount);
973 for (i = 0; i < pts->qcount; i++) {
974 if ( queue[i].status == LPQ_DELETED )
975 continue;
977 qcount++;
978 data.dsize += tdb_pack(NULL, 0, "ddddddff",
979 (uint32)queue[i].job,
980 (uint32)queue[i].size,
981 (uint32)queue[i].page_count,
982 (uint32)queue[i].status,
983 (uint32)queue[i].priority,
984 (uint32)queue[i].time,
985 queue[i].fs_user,
986 queue[i].fs_file);
989 if ((data.dptr = (char *)SMB_MALLOC(data.dsize)) == NULL)
990 return;
992 len = 0;
993 len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
994 for (i = 0; i < pts->qcount; i++) {
995 if ( queue[i].status == LPQ_DELETED )
996 continue;
998 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
999 (uint32)queue[i].job,
1000 (uint32)queue[i].size,
1001 (uint32)queue[i].page_count,
1002 (uint32)queue[i].status,
1003 (uint32)queue[i].priority,
1004 (uint32)queue[i].time,
1005 queue[i].fs_user,
1006 queue[i].fs_file);
1009 tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
1010 TDB_REPLACE);
1011 SAFE_FREE(data.dptr);
1012 return;
1015 static TDB_DATA get_jobs_changed_data(struct tdb_print_db *pdb)
1017 TDB_DATA data;
1019 ZERO_STRUCT(data);
1021 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
1022 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1023 SAFE_FREE(data.dptr);
1024 ZERO_STRUCT(data);
1027 return data;
1030 static void check_job_changed(const char *sharename, TDB_DATA data, uint32 jobid)
1032 unsigned int i;
1033 unsigned int job_count = data.dsize / 4;
1035 for (i = 0; i < job_count; i++) {
1036 uint32 ch_jobid;
1038 ch_jobid = IVAL(data.dptr, i*4);
1039 if (ch_jobid == jobid)
1040 remove_from_jobs_changed(sharename, jobid);
1044 /****************************************************************************
1045 Check if the print queue has been updated recently enough.
1046 ****************************************************************************/
1048 static BOOL print_cache_expired(const char *sharename, BOOL check_pending)
1050 fstring key;
1051 time_t last_qscan_time, time_now = time(NULL);
1052 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1053 BOOL result = False;
1055 if (!pdb)
1056 return False;
1058 snprintf(key, sizeof(key), "CACHE/%s", sharename);
1059 last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1062 * Invalidate the queue for 3 reasons.
1063 * (1). last queue scan time == -1.
1064 * (2). Current time - last queue scan time > allowed cache time.
1065 * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1066 * This last test picks up machines for which the clock has been moved
1067 * forward, an lpq scan done and then the clock moved back. Otherwise
1068 * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1071 if (last_qscan_time == ((time_t)-1)
1072 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1073 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1075 uint32 u;
1076 time_t msg_pending_time;
1078 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1079 "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1080 sharename, (int)last_qscan_time, (int)time_now,
1081 (int)lp_lpqcachetime() ));
1083 /* check if another smbd has already sent a message to update the
1084 queue. Give the pending message one minute to clear and
1085 then send another message anyways. Make sure to check for
1086 clocks that have been run forward and then back again. */
1088 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1090 if ( check_pending
1091 && tdb_fetch_uint32( pdb->tdb, key, &u )
1092 && (msg_pending_time=u) > 0
1093 && msg_pending_time <= time_now
1094 && (time_now - msg_pending_time) < 60 )
1096 DEBUG(4,("print_cache_expired: message already pending for %s. Accepting cache\n",
1097 sharename));
1098 goto done;
1101 result = True;
1104 done:
1105 release_print_db(pdb);
1106 return result;
1109 /****************************************************************************
1110 main work for updating the lpq cahe for a printer queue
1111 ****************************************************************************/
1113 static void print_queue_update_internal( const char *sharename,
1114 struct printif *current_printif,
1115 char *lpq_command, char *lprm_command )
1117 int i, qcount;
1118 print_queue_struct *queue = NULL;
1119 print_status_struct status;
1120 print_status_struct old_status;
1121 struct printjob *pjob;
1122 struct traverse_struct tstruct;
1123 TDB_DATA data, key;
1124 TDB_DATA jcdata;
1125 fstring keystr, cachestr;
1126 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1128 if (!pdb) {
1129 return;
1132 DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1133 sharename, current_printif->type, lpq_command));
1136 * Update the cache time FIRST ! Stops others even
1137 * attempting to get the lock and doing this
1138 * if the lpq takes a long time.
1141 slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1142 tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1144 /* get the current queue using the appropriate interface */
1145 ZERO_STRUCT(status);
1147 qcount = (*(current_printif->queue_get))(sharename,
1148 current_printif->type,
1149 lpq_command, &queue, &status);
1151 DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1152 qcount, (qcount != 1) ? "s" : "", sharename));
1154 /* Sort the queue by submission time otherwise they are displayed
1155 in hash order. */
1157 qsort(queue, qcount, sizeof(print_queue_struct),
1158 QSORT_CAST(printjob_comp));
1161 any job in the internal database that is marked as spooled
1162 and doesn't exist in the system queue is considered finished
1163 and removed from the database
1165 any job in the system database but not in the internal database
1166 is added as a unix job
1168 fill in any system job numbers as we go
1171 jcdata = get_jobs_changed_data(pdb);
1173 for (i=0; i<qcount; i++) {
1174 uint32 jobid = print_parse_jobid(queue[i].fs_file);
1176 if (jobid == (uint32)-1) {
1177 /* assume its a unix print job */
1178 print_unix_job(sharename, &queue[i], jobid);
1179 continue;
1182 /* we have an active SMB print job - update its status */
1183 pjob = print_job_find(sharename, jobid);
1184 if (!pjob) {
1185 /* err, somethings wrong. Probably smbd was restarted
1186 with jobs in the queue. All we can do is treat them
1187 like unix jobs. Pity. */
1188 print_unix_job(sharename, &queue[i], jobid);
1189 continue;
1192 pjob->sysjob = queue[i].job;
1194 /* don't reset the status on jobs to be deleted */
1196 if ( pjob->status != LPQ_DELETING )
1197 pjob->status = queue[i].status;
1199 pjob_store(sharename, jobid, pjob);
1201 check_job_changed(sharename, jcdata, jobid);
1204 SAFE_FREE(jcdata.dptr);
1206 /* now delete any queued entries that don't appear in the
1207 system queue */
1208 tstruct.queue = queue;
1209 tstruct.qcount = qcount;
1210 tstruct.snum = -1;
1211 tstruct.total_jobs = 0;
1212 tstruct.lpq_time = time(NULL);
1213 tstruct.sharename = sharename;
1214 tstruct.lprm_command = lprm_command;
1215 tstruct.print_if = current_printif;
1217 tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1219 /* Store the linearised queue, max jobs only. */
1220 store_queue_struct(pdb, &tstruct);
1222 SAFE_FREE(tstruct.queue);
1224 DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1225 sharename, tstruct.total_jobs ));
1227 tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1229 get_queue_status(sharename, &old_status);
1230 if (old_status.qcount != qcount)
1231 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1232 old_status.qcount, qcount, sharename));
1234 /* store the new queue status structure */
1235 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1236 key.dptr = keystr;
1237 key.dsize = strlen(keystr);
1239 status.qcount = qcount;
1240 data.dptr = (char *)&status;
1241 data.dsize = sizeof(status);
1242 tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1245 * Update the cache time again. We want to do this call
1246 * as little as possible...
1249 slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1250 tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1252 /* clear the msg pending record for this queue */
1254 snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1256 if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1257 /* log a message but continue on */
1259 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1260 sharename));
1263 release_print_db( pdb );
1265 return;
1268 /****************************************************************************
1269 Update the internal database from the system print queue for a queue.
1270 obtain a lock on the print queue before proceeding (needed when mutiple
1271 smbd processes maytry to update the lpq cache concurrently).
1272 ****************************************************************************/
1274 static void print_queue_update_with_lock( const char *sharename,
1275 struct printif *current_printif,
1276 char *lpq_command, char *lprm_command )
1278 fstring keystr;
1279 struct tdb_print_db *pdb;
1281 DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1282 pdb = get_print_db_byname(sharename);
1283 if (!pdb)
1284 return;
1286 if ( !print_cache_expired(sharename, False) ) {
1287 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1288 release_print_db(pdb);
1289 return;
1293 * Check to see if someone else is doing this update.
1294 * This is essentially a mutex on the update.
1297 if (get_updating_pid(sharename) != -1) {
1298 release_print_db(pdb);
1299 return;
1302 /* Lock the queue for the database update */
1304 slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1305 /* Only wait 10 seconds for this. */
1306 if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) == -1) {
1307 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1308 release_print_db(pdb);
1309 return;
1313 * Ensure that no one else got in here.
1314 * If the updating pid is still -1 then we are
1315 * the winner.
1318 if (get_updating_pid(sharename) != -1) {
1320 * Someone else is doing the update, exit.
1322 tdb_unlock_bystring(pdb->tdb, keystr);
1323 release_print_db(pdb);
1324 return;
1328 * We're going to do the update ourselves.
1331 /* Tell others we're doing the update. */
1332 set_updating_pid(sharename, True);
1335 * Allow others to enter and notice we're doing
1336 * the update.
1339 tdb_unlock_bystring(pdb->tdb, keystr);
1341 /* do the main work now */
1343 print_queue_update_internal( sharename, current_printif,
1344 lpq_command, lprm_command );
1346 /* Delete our pid from the db. */
1347 set_updating_pid(sharename, False);
1348 release_print_db(pdb);
1351 /****************************************************************************
1352 this is the receive function of the background lpq updater
1353 ****************************************************************************/
1354 static void print_queue_receive(int msg_type, struct process_id src,
1355 void *buf, size_t msglen)
1357 fstring sharename;
1358 pstring lpqcommand, lprmcommand;
1359 int printing_type;
1360 size_t len;
1362 len = tdb_unpack( (char *)buf, msglen, "fdPP",
1363 sharename,
1364 &printing_type,
1365 lpqcommand,
1366 lprmcommand );
1368 if ( len == -1 ) {
1369 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1370 return;
1373 print_queue_update_with_lock(sharename,
1374 get_printer_fns_from_type((enum printing_types)printing_type),
1375 lpqcommand, lprmcommand );
1377 return;
1380 static pid_t background_lpq_updater_pid = -1;
1382 /****************************************************************************
1383 main thread of the background lpq updater
1384 ****************************************************************************/
1385 void start_background_queue(void)
1387 DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
1388 background_lpq_updater_pid = sys_fork();
1390 if (background_lpq_updater_pid == -1) {
1391 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
1392 exit(1);
1395 if(background_lpq_updater_pid == 0) {
1396 /* Child. */
1397 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
1399 claim_connection( NULL, "smbd lpq backend", 0, False,
1400 FLAG_MSG_GENERAL|FLAG_MSG_SMBD|FLAG_MSG_PRINT_GENERAL);
1402 if (!locking_init(0)) {
1403 exit(1);
1406 message_register(MSG_PRINTER_UPDATE, print_queue_receive);
1408 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
1409 while (1) {
1410 pause();
1412 /* check for some essential signals first */
1414 if (got_sig_term) {
1415 exit_server_cleanly(NULL);
1418 if (reload_after_sighup) {
1419 change_to_root_user();
1420 DEBUG(1,("Reloading services after SIGHUP\n"));
1421 reload_services(False);
1422 reload_after_sighup = 0;
1425 /* now check for messages */
1427 DEBUG(10,("start_background_queue: background LPQ thread got a message\n"));
1428 message_dispatch();
1430 /* process any pending print change notify messages */
1432 print_notify_send_messages(0);
1437 /****************************************************************************
1438 update the internal database from the system print queue for a queue
1439 ****************************************************************************/
1441 static void print_queue_update(int snum, BOOL force)
1443 fstring key;
1444 fstring sharename;
1445 pstring lpqcommand, lprmcommand;
1446 char *buffer = NULL;
1447 size_t len = 0;
1448 size_t newlen;
1449 struct tdb_print_db *pdb;
1450 int type;
1451 struct printif *current_printif;
1453 fstrcpy( sharename, lp_const_servicename(snum));
1455 /* don't strip out characters like '$' from the printername */
1457 pstrcpy( lpqcommand, lp_lpqcommand(snum));
1458 string_sub2( lpqcommand, "%p", PRINTERNAME(snum), sizeof(lpqcommand),
1459 False, False, False );
1460 standard_sub_advanced(lp_servicename(snum),
1461 current_user_info.unix_name, "",
1462 current_user.ut.gid,
1463 get_current_username(),
1464 current_user_info.domain,
1465 lpqcommand, sizeof(lpqcommand) );
1467 pstrcpy( lprmcommand, lp_lprmcommand(snum));
1468 string_sub2( lprmcommand, "%p", PRINTERNAME(snum), sizeof(lprmcommand),
1469 False, False, False );
1470 standard_sub_advanced(lp_servicename(snum),
1471 current_user_info.unix_name, "",
1472 current_user.ut.gid,
1473 get_current_username(),
1474 current_user_info.domain,
1475 lprmcommand, sizeof(lprmcommand) );
1478 * Make sure that the background queue process exists.
1479 * Otherwise just do the update ourselves
1482 if ( force || background_lpq_updater_pid == -1 ) {
1483 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1484 current_printif = get_printer_fns( snum );
1485 print_queue_update_with_lock( sharename, current_printif, lpqcommand, lprmcommand );
1487 return;
1490 type = lp_printing(snum);
1492 /* get the length */
1494 len = tdb_pack( NULL, 0, "fdPP",
1495 sharename,
1496 type,
1497 lpqcommand,
1498 lprmcommand );
1500 buffer = SMB_XMALLOC_ARRAY( char, len );
1502 /* now pack the buffer */
1503 newlen = tdb_pack( buffer, len, "fdPP",
1504 sharename,
1505 type,
1506 lpqcommand,
1507 lprmcommand );
1509 SMB_ASSERT( newlen == len );
1511 DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1512 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1513 sharename, type, lpqcommand, lprmcommand ));
1515 /* here we set a msg pending record for other smbd processes
1516 to throttle the number of duplicate print_queue_update msgs
1517 sent. */
1519 pdb = get_print_db_byname(sharename);
1520 if (!pdb) {
1521 SAFE_FREE(buffer);
1522 return;
1525 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1527 if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1528 /* log a message but continue on */
1530 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1531 sharename));
1534 release_print_db( pdb );
1536 /* finally send the message */
1538 message_send_pid(pid_to_procid(background_lpq_updater_pid),
1539 MSG_PRINTER_UPDATE, buffer, len, False);
1541 SAFE_FREE( buffer );
1543 return;
1546 /****************************************************************************
1547 Create/Update an entry in the print tdb that will allow us to send notify
1548 updates only to interested smbd's.
1549 ****************************************************************************/
1551 BOOL print_notify_register_pid(int snum)
1553 TDB_DATA data;
1554 struct tdb_print_db *pdb = NULL;
1555 TDB_CONTEXT *tdb = NULL;
1556 const char *printername;
1557 uint32 mypid = (uint32)sys_getpid();
1558 BOOL ret = False;
1559 size_t i;
1561 /* if (snum == -1), then the change notify request was
1562 on a print server handle and we need to register on
1563 all print queus */
1565 if (snum == -1)
1567 int num_services = lp_numservices();
1568 int idx;
1570 for ( idx=0; idx<num_services; idx++ ) {
1571 if (lp_snum_ok(idx) && lp_print_ok(idx) )
1572 print_notify_register_pid(idx);
1575 return True;
1577 else /* register for a specific printer */
1579 printername = lp_const_servicename(snum);
1580 pdb = get_print_db_byname(printername);
1581 if (!pdb)
1582 return False;
1583 tdb = pdb->tdb;
1586 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1587 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1588 printername));
1589 if (pdb)
1590 release_print_db(pdb);
1591 return False;
1594 data = get_printer_notify_pid_list( tdb, printername, True );
1596 /* Add ourselves and increase the refcount. */
1598 for (i = 0; i < data.dsize; i += 8) {
1599 if (IVAL(data.dptr,i) == mypid) {
1600 uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1601 SIVAL(data.dptr, i+4, new_refcount);
1602 break;
1606 if (i == data.dsize) {
1607 /* We weren't in the list. Realloc. */
1608 data.dptr = (char *)SMB_REALLOC(data.dptr, data.dsize + 8);
1609 if (!data.dptr) {
1610 DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1611 printername));
1612 goto done;
1614 data.dsize += 8;
1615 SIVAL(data.dptr,data.dsize - 8,mypid);
1616 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1619 /* Store back the record. */
1620 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1621 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1622 list for printer %s\n", printername));
1623 goto done;
1626 ret = True;
1628 done:
1630 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1631 if (pdb)
1632 release_print_db(pdb);
1633 SAFE_FREE(data.dptr);
1634 return ret;
1637 /****************************************************************************
1638 Update an entry in the print tdb that will allow us to send notify
1639 updates only to interested smbd's.
1640 ****************************************************************************/
1642 BOOL print_notify_deregister_pid(int snum)
1644 TDB_DATA data;
1645 struct tdb_print_db *pdb = NULL;
1646 TDB_CONTEXT *tdb = NULL;
1647 const char *printername;
1648 uint32 mypid = (uint32)sys_getpid();
1649 size_t i;
1650 BOOL ret = False;
1652 /* if ( snum == -1 ), we are deregister a print server handle
1653 which means to deregister on all print queues */
1655 if (snum == -1)
1657 int num_services = lp_numservices();
1658 int idx;
1660 for ( idx=0; idx<num_services; idx++ ) {
1661 if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1662 print_notify_deregister_pid(idx);
1665 return True;
1667 else /* deregister a specific printer */
1669 printername = lp_const_servicename(snum);
1670 pdb = get_print_db_byname(printername);
1671 if (!pdb)
1672 return False;
1673 tdb = pdb->tdb;
1676 if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1677 DEBUG(0,("print_notify_register_pid: Failed to lock \
1678 printer %s database\n", printername));
1679 if (pdb)
1680 release_print_db(pdb);
1681 return False;
1684 data = get_printer_notify_pid_list( tdb, printername, True );
1686 /* Reduce refcount. Remove ourselves if zero. */
1688 for (i = 0; i < data.dsize; ) {
1689 if (IVAL(data.dptr,i) == mypid) {
1690 uint32 refcount = IVAL(data.dptr, i+4);
1692 refcount--;
1694 if (refcount == 0) {
1695 if (data.dsize - i > 8)
1696 memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1697 data.dsize -= 8;
1698 continue;
1700 SIVAL(data.dptr, i+4, refcount);
1703 i += 8;
1706 if (data.dsize == 0)
1707 SAFE_FREE(data.dptr);
1709 /* Store back the record. */
1710 if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1711 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1712 list for printer %s\n", printername));
1713 goto done;
1716 ret = True;
1718 done:
1720 tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1721 if (pdb)
1722 release_print_db(pdb);
1723 SAFE_FREE(data.dptr);
1724 return ret;
1727 /****************************************************************************
1728 Check if a jobid is valid. It is valid if it exists in the database.
1729 ****************************************************************************/
1731 BOOL print_job_exists(const char* sharename, uint32 jobid)
1733 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1734 BOOL ret;
1736 if (!pdb)
1737 return False;
1738 ret = tdb_exists(pdb->tdb, print_key(jobid));
1739 release_print_db(pdb);
1740 return ret;
1743 /****************************************************************************
1744 Give the fd used for a jobid.
1745 ****************************************************************************/
1747 int print_job_fd(const char* sharename, uint32 jobid)
1749 struct printjob *pjob = print_job_find(sharename, jobid);
1750 if (!pjob)
1751 return -1;
1752 /* don't allow another process to get this info - it is meaningless */
1753 if (pjob->pid != sys_getpid())
1754 return -1;
1755 return pjob->fd;
1758 /****************************************************************************
1759 Give the filename used for a jobid.
1760 Only valid for the process doing the spooling and when the job
1761 has not been spooled.
1762 ****************************************************************************/
1764 char *print_job_fname(const char* sharename, uint32 jobid)
1766 struct printjob *pjob = print_job_find(sharename, jobid);
1767 if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
1768 return NULL;
1769 return pjob->filename;
1773 /****************************************************************************
1774 Give the filename used for a jobid.
1775 Only valid for the process doing the spooling and when the job
1776 has not been spooled.
1777 ****************************************************************************/
1779 NT_DEVICEMODE *print_job_devmode(const char* sharename, uint32 jobid)
1781 struct printjob *pjob = print_job_find(sharename, jobid);
1783 if ( !pjob )
1784 return NULL;
1786 return pjob->nt_devmode;
1789 /****************************************************************************
1790 Set the place in the queue for a job.
1791 ****************************************************************************/
1793 BOOL print_job_set_place(const char *sharename, uint32 jobid, int place)
1795 DEBUG(2,("print_job_set_place not implemented yet\n"));
1796 return False;
1799 /****************************************************************************
1800 Set the name of a job. Only possible for owner.
1801 ****************************************************************************/
1803 BOOL print_job_set_name(const char *sharename, uint32 jobid, char *name)
1805 struct printjob *pjob;
1807 pjob = print_job_find(sharename, jobid);
1808 if (!pjob || pjob->pid != sys_getpid())
1809 return False;
1811 fstrcpy(pjob->jobname, name);
1812 return pjob_store(sharename, jobid, pjob);
1815 /***************************************************************************
1816 Remove a jobid from the 'jobs changed' list.
1817 ***************************************************************************/
1819 static BOOL remove_from_jobs_changed(const char* sharename, uint32 jobid)
1821 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1822 TDB_DATA data, key;
1823 size_t job_count, i;
1824 BOOL ret = False;
1825 BOOL gotlock = False;
1827 if (!pdb) {
1828 return False;
1831 ZERO_STRUCT(data);
1833 key = string_tdb_data("INFO/jobs_changed");
1835 if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
1836 goto out;
1838 gotlock = True;
1840 data = tdb_fetch(pdb->tdb, key);
1842 if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
1843 goto out;
1845 job_count = data.dsize / 4;
1846 for (i = 0; i < job_count; i++) {
1847 uint32 ch_jobid;
1849 ch_jobid = IVAL(data.dptr, i*4);
1850 if (ch_jobid == jobid) {
1851 if (i < job_count -1 )
1852 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
1853 data.dsize -= 4;
1854 if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
1855 goto out;
1856 break;
1860 ret = True;
1861 out:
1863 if (gotlock)
1864 tdb_chainunlock(pdb->tdb, key);
1865 SAFE_FREE(data.dptr);
1866 release_print_db(pdb);
1867 if (ret)
1868 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
1869 else
1870 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
1871 return ret;
1874 /****************************************************************************
1875 Delete a print job - don't update queue.
1876 ****************************************************************************/
1878 static BOOL print_job_delete1(int snum, uint32 jobid)
1880 const char* sharename = lp_const_servicename(snum);
1881 struct printjob *pjob = print_job_find(sharename, jobid);
1882 int result = 0;
1883 struct printif *current_printif = get_printer_fns( snum );
1885 if (!pjob)
1886 return False;
1889 * If already deleting just return.
1892 if (pjob->status == LPQ_DELETING)
1893 return True;
1895 /* Hrm - we need to be able to cope with deleting a job before it
1896 has reached the spooler. Just mark it as LPQ_DELETING and
1897 let the print_queue_update() code rmeove the record */
1900 if (pjob->sysjob == -1) {
1901 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
1904 /* Set the tdb entry to be deleting. */
1906 pjob->status = LPQ_DELETING;
1907 pjob_store(sharename, jobid, pjob);
1909 if (pjob->spooled && pjob->sysjob != -1)
1911 result = (*(current_printif->job_delete))(
1912 PRINTERNAME(snum),
1913 lp_lprmcommand(snum),
1914 pjob);
1916 /* Delete the tdb entry if the delete succeeded or the job hasn't
1917 been spooled. */
1919 if (result == 0) {
1920 struct tdb_print_db *pdb = get_print_db_byname(sharename);
1921 int njobs = 1;
1923 if (!pdb)
1924 return False;
1925 pjob_delete(sharename, jobid);
1926 /* Ensure we keep a rough count of the number of total jobs... */
1927 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
1928 release_print_db(pdb);
1932 remove_from_jobs_changed( sharename, jobid );
1934 return (result == 0);
1937 /****************************************************************************
1938 Return true if the current user owns the print job.
1939 ****************************************************************************/
1941 static BOOL is_owner(struct current_user *user, const char *servicename,
1942 uint32 jobid)
1944 struct printjob *pjob = print_job_find(servicename, jobid);
1945 user_struct *vuser;
1947 if (!pjob || !user)
1948 return False;
1950 if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
1951 return strequal(pjob->user, vuser->user.smb_name);
1952 } else {
1953 return strequal(pjob->user, uidtoname(user->ut.uid));
1957 /****************************************************************************
1958 Delete a print job.
1959 ****************************************************************************/
1961 BOOL print_job_delete(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1963 const char* sharename = lp_const_servicename( snum );
1964 struct printjob *pjob;
1965 BOOL owner;
1966 char *fname;
1968 *errcode = WERR_OK;
1970 owner = is_owner(user, lp_const_servicename(snum), jobid);
1972 /* Check access against security descriptor or whether the user
1973 owns their job. */
1975 if (!owner &&
1976 !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1977 DEBUG(3, ("delete denied by security descriptor\n"));
1978 *errcode = WERR_ACCESS_DENIED;
1980 /* BEGIN_ADMIN_LOG */
1981 sys_adminlog( LOG_ERR,
1982 "Permission denied-- user not allowed to delete, \
1983 pause, or resume print job. User name: %s. Printer name: %s.",
1984 uidtoname(user->ut.uid), PRINTERNAME(snum) );
1985 /* END_ADMIN_LOG */
1987 return False;
1991 * get the spooled filename of the print job
1992 * if this works, then the file has not been spooled
1993 * to the underlying print system. Just delete the
1994 * spool file & return.
1997 if ( (fname = print_job_fname( sharename, jobid )) != NULL )
1999 /* remove the spool file */
2000 DEBUG(10,("print_job_delete: Removing spool file [%s]\n", fname ));
2001 if ( unlink( fname ) == -1 ) {
2002 *errcode = map_werror_from_unix(errno);
2003 return False;
2007 if (!print_job_delete1(snum, jobid)) {
2008 *errcode = WERR_ACCESS_DENIED;
2009 return False;
2012 /* force update the database and say the delete failed if the
2013 job still exists */
2015 print_queue_update(snum, True);
2017 pjob = print_job_find(sharename, jobid);
2018 if ( pjob && (pjob->status != LPQ_DELETING) )
2019 *errcode = WERR_ACCESS_DENIED;
2021 return (pjob == NULL );
2024 /****************************************************************************
2025 Pause a job.
2026 ****************************************************************************/
2028 BOOL print_job_pause(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
2030 const char* sharename = lp_const_servicename(snum);
2031 struct printjob *pjob;
2032 int ret = -1;
2033 struct printif *current_printif = get_printer_fns( snum );
2035 pjob = print_job_find(sharename, jobid);
2037 if (!pjob || !user) {
2038 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2039 (unsigned int)jobid ));
2040 return False;
2043 if (!pjob->spooled || pjob->sysjob == -1) {
2044 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2045 (int)pjob->sysjob, (unsigned int)jobid ));
2046 return False;
2049 if (!is_owner(user, lp_const_servicename(snum), jobid) &&
2050 !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
2051 DEBUG(3, ("pause denied by security descriptor\n"));
2053 /* BEGIN_ADMIN_LOG */
2054 sys_adminlog( LOG_ERR,
2055 "Permission denied-- user not allowed to delete, \
2056 pause, or resume print job. User name: %s. Printer name: %s.",
2057 uidtoname(user->ut.uid), PRINTERNAME(snum) );
2058 /* END_ADMIN_LOG */
2060 *errcode = WERR_ACCESS_DENIED;
2061 return False;
2064 /* need to pause the spooled entry */
2065 ret = (*(current_printif->job_pause))(snum, pjob);
2067 if (ret != 0) {
2068 *errcode = WERR_INVALID_PARAM;
2069 return False;
2072 /* force update the database */
2073 print_cache_flush(lp_const_servicename(snum));
2075 /* Send a printer notify message */
2077 notify_job_status(sharename, jobid, JOB_STATUS_PAUSED);
2079 /* how do we tell if this succeeded? */
2081 return True;
2084 /****************************************************************************
2085 Resume a job.
2086 ****************************************************************************/
2088 BOOL print_job_resume(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
2090 const char *sharename = lp_const_servicename(snum);
2091 struct printjob *pjob;
2092 int ret;
2093 struct printif *current_printif = get_printer_fns( snum );
2095 pjob = print_job_find(sharename, jobid);
2097 if (!pjob || !user) {
2098 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2099 (unsigned int)jobid ));
2100 return False;
2103 if (!pjob->spooled || pjob->sysjob == -1) {
2104 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2105 (int)pjob->sysjob, (unsigned int)jobid ));
2106 return False;
2109 if (!is_owner(user, lp_const_servicename(snum), jobid) &&
2110 !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
2111 DEBUG(3, ("resume denied by security descriptor\n"));
2112 *errcode = WERR_ACCESS_DENIED;
2114 /* BEGIN_ADMIN_LOG */
2115 sys_adminlog( LOG_ERR,
2116 "Permission denied-- user not allowed to delete, \
2117 pause, or resume print job. User name: %s. Printer name: %s.",
2118 uidtoname(user->ut.uid), PRINTERNAME(snum) );
2119 /* END_ADMIN_LOG */
2120 return False;
2123 ret = (*(current_printif->job_resume))(snum, pjob);
2125 if (ret != 0) {
2126 *errcode = WERR_INVALID_PARAM;
2127 return False;
2130 /* force update the database */
2131 print_cache_flush(lp_const_servicename(snum));
2133 /* Send a printer notify message */
2135 notify_job_status(sharename, jobid, JOB_STATUS_QUEUED);
2137 return True;
2140 /****************************************************************************
2141 Write to a print file.
2142 ****************************************************************************/
2144 ssize_t print_job_write(int snum, uint32 jobid, const char *buf, SMB_OFF_T pos, size_t size)
2146 const char* sharename = lp_const_servicename(snum);
2147 int return_code;
2148 struct printjob *pjob;
2150 pjob = print_job_find(sharename, jobid);
2152 if (!pjob)
2153 return -1;
2154 /* don't allow another process to get this info - it is meaningless */
2155 if (pjob->pid != sys_getpid())
2156 return -1;
2158 return_code = write_data_at_offset(pjob->fd, buf, size, pos);
2160 if (return_code>0) {
2161 pjob->size += size;
2162 pjob_store(sharename, jobid, pjob);
2164 return return_code;
2167 /****************************************************************************
2168 Get the queue status - do not update if db is out of date.
2169 ****************************************************************************/
2171 static int get_queue_status(const char* sharename, print_status_struct *status)
2173 fstring keystr;
2174 TDB_DATA data;
2175 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2176 int len;
2178 if (status) {
2179 ZERO_STRUCTP(status);
2182 if (!pdb)
2183 return 0;
2185 if (status) {
2186 fstr_sprintf(keystr, "STATUS/%s", sharename);
2187 data = tdb_fetch(pdb->tdb, string_tdb_data(keystr));
2188 if (data.dptr) {
2189 if (data.dsize == sizeof(print_status_struct))
2190 /* this memcpy is ok since the status struct was
2191 not packed before storing it in the tdb */
2192 memcpy(status, data.dptr, sizeof(print_status_struct));
2193 SAFE_FREE(data.dptr);
2196 len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2197 release_print_db(pdb);
2198 return (len == -1 ? 0 : len);
2201 /****************************************************************************
2202 Determine the number of jobs in a queue.
2203 ****************************************************************************/
2205 int print_queue_length(int snum, print_status_struct *pstatus)
2207 const char* sharename = lp_const_servicename( snum );
2208 print_status_struct status;
2209 int len;
2211 ZERO_STRUCT( status );
2213 /* make sure the database is up to date */
2214 if (print_cache_expired(lp_const_servicename(snum), True))
2215 print_queue_update(snum, False);
2217 /* also fetch the queue status */
2218 memset(&status, 0, sizeof(status));
2219 len = get_queue_status(sharename, &status);
2221 if (pstatus)
2222 *pstatus = status;
2224 return len;
2227 /***************************************************************************
2228 Allocate a jobid. Hold the lock for as short a time as possible.
2229 ***************************************************************************/
2231 static BOOL allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char *sharename, uint32 *pjobid)
2233 int i;
2234 uint32 jobid;
2236 *pjobid = (uint32)-1;
2238 for (i = 0; i < 3; i++) {
2239 /* Lock the database - only wait 20 seconds. */
2240 if (tdb_lock_bystring_with_timeout(pdb->tdb, "INFO/nextjob", 20) == -1) {
2241 DEBUG(0,("allocate_print_jobid: failed to lock printing database %s\n", sharename));
2242 return False;
2245 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2246 if (tdb_error(pdb->tdb) != TDB_ERR_NOEXIST) {
2247 DEBUG(0, ("allocate_print_jobid: failed to fetch INFO/nextjob for print queue %s\n",
2248 sharename));
2249 return False;
2251 jobid = 0;
2254 jobid = NEXT_JOBID(jobid);
2256 if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
2257 DEBUG(3, ("allocate_print_jobid: failed to store INFO/nextjob.\n"));
2258 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2259 return False;
2262 /* We've finished with the INFO/nextjob lock. */
2263 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2265 if (!print_job_exists(sharename, jobid))
2266 break;
2269 if (i > 2) {
2270 DEBUG(0, ("allocate_print_jobid: failed to allocate a print job for queue %s\n",
2271 sharename));
2272 /* Probably full... */
2273 errno = ENOSPC;
2274 return False;
2277 /* Store a dummy placeholder. */
2279 TDB_DATA dum;
2280 dum.dptr = NULL;
2281 dum.dsize = 0;
2282 if (tdb_store(pdb->tdb, print_key(jobid), dum, TDB_INSERT) == -1) {
2283 DEBUG(3, ("allocate_print_jobid: jobid (%d) failed to store placeholder.\n",
2284 jobid ));
2285 return False;
2289 *pjobid = jobid;
2290 return True;
2293 /***************************************************************************
2294 Append a jobid to the 'jobs changed' list.
2295 ***************************************************************************/
2297 static BOOL add_to_jobs_changed(struct tdb_print_db *pdb, uint32 jobid)
2299 TDB_DATA data;
2300 uint32 store_jobid;
2302 SIVAL(&store_jobid, 0, jobid);
2303 data.dptr = (char *)&store_jobid;
2304 data.dsize = 4;
2306 DEBUG(10,("add_to_jobs_changed: Added jobid %u\n", (unsigned int)jobid ));
2308 return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
2309 data) == 0);
2312 /***************************************************************************
2313 Start spooling a job - return the jobid.
2314 ***************************************************************************/
2316 uint32 print_job_start(struct current_user *user, int snum, char *jobname, NT_DEVICEMODE *nt_devmode )
2318 uint32 jobid;
2319 char *path;
2320 struct printjob pjob;
2321 user_struct *vuser;
2322 const char *sharename = lp_const_servicename(snum);
2323 struct tdb_print_db *pdb = get_print_db_byname(sharename);
2324 int njobs;
2326 errno = 0;
2328 if (!pdb)
2329 return (uint32)-1;
2331 if (!print_access_check(user, snum, PRINTER_ACCESS_USE)) {
2332 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
2333 release_print_db(pdb);
2334 return (uint32)-1;
2337 if (!print_time_access_check(lp_servicename(snum))) {
2338 DEBUG(3, ("print_job_start: job start denied by time check\n"));
2339 release_print_db(pdb);
2340 return (uint32)-1;
2343 path = lp_pathname(snum);
2345 /* see if we have sufficient disk space */
2346 if (lp_minprintspace(snum)) {
2347 SMB_BIG_UINT dspace, dsize;
2348 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
2349 dspace < 2*(SMB_BIG_UINT)lp_minprintspace(snum)) {
2350 DEBUG(3, ("print_job_start: disk space check failed.\n"));
2351 release_print_db(pdb);
2352 errno = ENOSPC;
2353 return (uint32)-1;
2357 /* for autoloaded printers, check that the printcap entry still exists */
2358 if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum))) {
2359 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
2360 release_print_db(pdb);
2361 errno = ENOENT;
2362 return (uint32)-1;
2365 /* Insure the maximum queue size is not violated */
2366 if ((njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
2367 DEBUG(3, ("print_job_start: Queue %s number of jobs (%d) larger than max printjobs per queue (%d).\n",
2368 sharename, njobs, lp_maxprintjobs(snum) ));
2369 release_print_db(pdb);
2370 errno = ENOSPC;
2371 return (uint32)-1;
2374 DEBUG(10,("print_job_start: Queue %s number of jobs (%d), max printjobs = %d\n",
2375 sharename, njobs, lp_maxprintjobs(snum) ));
2377 if (!allocate_print_jobid(pdb, snum, sharename, &jobid))
2378 goto fail;
2380 /* create the database entry */
2382 ZERO_STRUCT(pjob);
2384 pjob.pid = sys_getpid();
2385 pjob.sysjob = -1;
2386 pjob.fd = -1;
2387 pjob.starttime = time(NULL);
2388 pjob.status = LPQ_SPOOLING;
2389 pjob.size = 0;
2390 pjob.spooled = False;
2391 pjob.smbjob = True;
2392 pjob.nt_devmode = nt_devmode;
2394 fstrcpy(pjob.jobname, jobname);
2396 if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
2397 fstrcpy(pjob.user, vuser->user.smb_name);
2398 } else {
2399 fstrcpy(pjob.user, uidtoname(user->ut.uid));
2402 fstrcpy(pjob.queuename, lp_const_servicename(snum));
2404 /* we have a job entry - now create the spool file */
2405 slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX",
2406 path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2407 pjob.fd = smb_mkstemp(pjob.filename);
2409 if (pjob.fd == -1) {
2410 if (errno == EACCES) {
2411 /* Common setup error, force a report. */
2412 DEBUG(0, ("print_job_start: insufficient permissions \
2413 to open spool file %s.\n", pjob.filename));
2414 } else {
2415 /* Normal case, report at level 3 and above. */
2416 DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
2417 DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
2419 goto fail;
2422 pjob_store(sharename, jobid, &pjob);
2424 /* Update the 'jobs changed' entry used by print_queue_status. */
2425 add_to_jobs_changed(pdb, jobid);
2427 /* Ensure we keep a rough count of the number of total jobs... */
2428 tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2430 release_print_db(pdb);
2432 return jobid;
2434 fail:
2435 if (jobid != -1)
2436 pjob_delete(sharename, jobid);
2438 release_print_db(pdb);
2440 DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
2441 return (uint32)-1;
2444 /****************************************************************************
2445 Update the number of pages spooled to jobid
2446 ****************************************************************************/
2448 void print_job_endpage(int snum, uint32 jobid)
2450 const char* sharename = lp_const_servicename(snum);
2451 struct printjob *pjob;
2453 pjob = print_job_find(sharename, jobid);
2454 if (!pjob)
2455 return;
2456 /* don't allow another process to get this info - it is meaningless */
2457 if (pjob->pid != sys_getpid())
2458 return;
2460 pjob->page_count++;
2461 pjob_store(sharename, jobid, pjob);
2464 /****************************************************************************
2465 Print a file - called on closing the file. This spools the job.
2466 If normal close is false then we're tearing down the jobs - treat as an
2467 error.
2468 ****************************************************************************/
2470 BOOL print_job_end(int snum, uint32 jobid, enum file_close_type close_type)
2472 const char* sharename = lp_const_servicename(snum);
2473 struct printjob *pjob;
2474 int ret;
2475 SMB_STRUCT_STAT sbuf;
2476 struct printif *current_printif = get_printer_fns( snum );
2478 pjob = print_job_find(sharename, jobid);
2480 if (!pjob)
2481 return False;
2483 if (pjob->spooled || pjob->pid != sys_getpid())
2484 return False;
2486 if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
2487 (sys_fstat(pjob->fd, &sbuf) == 0)) {
2488 pjob->size = sbuf.st_size;
2489 close(pjob->fd);
2490 pjob->fd = -1;
2491 } else {
2494 * Not a normal close or we couldn't stat the job file,
2495 * so something has gone wrong. Cleanup.
2497 close(pjob->fd);
2498 pjob->fd = -1;
2499 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
2500 goto fail;
2503 /* Technically, this is not quite right. If the printer has a separator
2504 * page turned on, the NT spooler prints the separator page even if the
2505 * print job is 0 bytes. 010215 JRR */
2506 if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
2507 /* don't bother spooling empty files or something being deleted. */
2508 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
2509 pjob->filename, pjob->size ? "deleted" : "zero length" ));
2510 unlink(pjob->filename);
2511 pjob_delete(sharename, jobid);
2512 return True;
2515 pjob->smbjob = jobid;
2517 ret = (*(current_printif->job_submit))(snum, pjob);
2519 if (ret)
2520 goto fail;
2522 /* The print job has been sucessfully handed over to the back-end */
2524 pjob->spooled = True;
2525 pjob->status = LPQ_QUEUED;
2526 pjob_store(sharename, jobid, pjob);
2528 /* make sure the database is up to date */
2529 if (print_cache_expired(lp_const_servicename(snum), True))
2530 print_queue_update(snum, False);
2532 return True;
2534 fail:
2536 /* The print job was not succesfully started. Cleanup */
2537 /* Still need to add proper error return propagation! 010122:JRR */
2538 unlink(pjob->filename);
2539 pjob_delete(sharename, jobid);
2540 return False;
2543 /****************************************************************************
2544 Get a snapshot of jobs in the system without traversing.
2545 ****************************************************************************/
2547 static BOOL get_stored_queue_info(struct tdb_print_db *pdb, int snum, int *pcount, print_queue_struct **ppqueue)
2549 TDB_DATA data, cgdata;
2550 print_queue_struct *queue = NULL;
2551 uint32 qcount = 0;
2552 uint32 extra_count = 0;
2553 int total_count = 0;
2554 size_t len = 0;
2555 uint32 i;
2556 int max_reported_jobs = lp_max_reported_jobs(snum);
2557 BOOL ret = False;
2558 const char* sharename = lp_servicename(snum);
2560 /* make sure the database is up to date */
2561 if (print_cache_expired(lp_const_servicename(snum), True))
2562 print_queue_update(snum, False);
2564 *pcount = 0;
2565 *ppqueue = NULL;
2567 ZERO_STRUCT(data);
2568 ZERO_STRUCT(cgdata);
2570 /* Get the stored queue data. */
2571 data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
2573 if (data.dptr && data.dsize >= sizeof(qcount))
2574 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
2576 /* Get the changed jobs list. */
2577 cgdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
2578 if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
2579 extra_count = cgdata.dsize/4;
2581 DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
2583 /* Allocate the queue size. */
2584 if (qcount == 0 && extra_count == 0)
2585 goto out;
2587 if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
2588 goto out;
2590 /* Retrieve the linearised queue data. */
2592 for( i = 0; i < qcount; i++) {
2593 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
2594 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
2595 &qjob,
2596 &qsize,
2597 &qpage_count,
2598 &qstatus,
2599 &qpriority,
2600 &qtime,
2601 queue[i].fs_user,
2602 queue[i].fs_file);
2603 queue[i].job = qjob;
2604 queue[i].size = qsize;
2605 queue[i].page_count = qpage_count;
2606 queue[i].status = qstatus;
2607 queue[i].priority = qpriority;
2608 queue[i].time = qtime;
2611 total_count = qcount;
2613 /* Add in the changed jobids. */
2614 for( i = 0; i < extra_count; i++) {
2615 uint32 jobid;
2616 struct printjob *pjob;
2618 jobid = IVAL(cgdata.dptr, i*4);
2619 DEBUG(5,("get_stored_queue_info: changed job = %u\n", (unsigned int)jobid));
2620 pjob = print_job_find(lp_const_servicename(snum), jobid);
2621 if (!pjob) {
2622 DEBUG(5,("get_stored_queue_info: failed to find changed job = %u\n", (unsigned int)jobid));
2623 remove_from_jobs_changed(sharename, jobid);
2624 continue;
2627 queue[total_count].job = jobid;
2628 queue[total_count].size = pjob->size;
2629 queue[total_count].page_count = pjob->page_count;
2630 queue[total_count].status = pjob->status;
2631 queue[total_count].priority = 1;
2632 queue[total_count].time = pjob->starttime;
2633 fstrcpy(queue[total_count].fs_user, pjob->user);
2634 fstrcpy(queue[total_count].fs_file, pjob->jobname);
2635 total_count++;
2638 /* Sort the queue by submission time otherwise they are displayed
2639 in hash order. */
2641 qsort(queue, total_count, sizeof(print_queue_struct), QSORT_CAST(printjob_comp));
2643 DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
2645 if (max_reported_jobs && total_count > max_reported_jobs)
2646 total_count = max_reported_jobs;
2648 *ppqueue = queue;
2649 *pcount = total_count;
2651 ret = True;
2653 out:
2655 SAFE_FREE(data.dptr);
2656 SAFE_FREE(cgdata.dptr);
2657 return ret;
2660 /****************************************************************************
2661 Get a printer queue listing.
2662 set queue = NULL and status = NULL if you just want to update the cache
2663 ****************************************************************************/
2665 int print_queue_status(int snum,
2666 print_queue_struct **ppqueue,
2667 print_status_struct *status)
2669 fstring keystr;
2670 TDB_DATA data, key;
2671 const char *sharename;
2672 struct tdb_print_db *pdb;
2673 int count = 0;
2675 /* make sure the database is up to date */
2677 if (print_cache_expired(lp_const_servicename(snum), True))
2678 print_queue_update(snum, False);
2680 /* return if we are done */
2681 if ( !ppqueue || !status )
2682 return 0;
2684 *ppqueue = NULL;
2685 sharename = lp_const_servicename(snum);
2686 pdb = get_print_db_byname(sharename);
2688 if (!pdb)
2689 return 0;
2692 * Fetch the queue status. We must do this first, as there may
2693 * be no jobs in the queue.
2696 ZERO_STRUCTP(status);
2697 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
2698 key.dptr = keystr;
2699 key.dsize = strlen(keystr);
2700 data = tdb_fetch(pdb->tdb, key);
2701 if (data.dptr) {
2702 if (data.dsize == sizeof(*status)) {
2703 /* this memcpy is ok since the status struct was
2704 not packed before storing it in the tdb */
2705 memcpy(status, data.dptr, sizeof(*status));
2707 SAFE_FREE(data.dptr);
2711 * Now, fetch the print queue information. We first count the number
2712 * of entries, and then only retrieve the queue if necessary.
2715 if (!get_stored_queue_info(pdb, snum, &count, ppqueue)) {
2716 release_print_db(pdb);
2717 return 0;
2720 release_print_db(pdb);
2721 return count;
2724 /****************************************************************************
2725 Pause a queue.
2726 ****************************************************************************/
2728 BOOL print_queue_pause(struct current_user *user, int snum, WERROR *errcode)
2730 int ret;
2731 struct printif *current_printif = get_printer_fns( snum );
2733 if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
2734 *errcode = WERR_ACCESS_DENIED;
2735 return False;
2739 become_root();
2741 ret = (*(current_printif->queue_pause))(snum);
2743 unbecome_root();
2745 if (ret != 0) {
2746 *errcode = WERR_INVALID_PARAM;
2747 return False;
2750 /* force update the database */
2751 print_cache_flush(lp_const_servicename(snum));
2753 /* Send a printer notify message */
2755 notify_printer_status(snum, PRINTER_STATUS_PAUSED);
2757 return True;
2760 /****************************************************************************
2761 Resume a queue.
2762 ****************************************************************************/
2764 BOOL print_queue_resume(struct current_user *user, int snum, WERROR *errcode)
2766 int ret;
2767 struct printif *current_printif = get_printer_fns( snum );
2769 if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
2770 *errcode = WERR_ACCESS_DENIED;
2771 return False;
2774 become_root();
2776 ret = (*(current_printif->queue_resume))(snum);
2778 unbecome_root();
2780 if (ret != 0) {
2781 *errcode = WERR_INVALID_PARAM;
2782 return False;
2785 /* make sure the database is up to date */
2786 if (print_cache_expired(lp_const_servicename(snum), True))
2787 print_queue_update(snum, True);
2789 /* Send a printer notify message */
2791 notify_printer_status(snum, PRINTER_STATUS_OK);
2793 return True;
2796 /****************************************************************************
2797 Purge a queue - implemented by deleting all jobs that we can delete.
2798 ****************************************************************************/
2800 BOOL print_queue_purge(struct current_user *user, int snum, WERROR *errcode)
2802 print_queue_struct *queue;
2803 print_status_struct status;
2804 int njobs, i;
2805 BOOL can_job_admin;
2807 /* Force and update so the count is accurate (i.e. not a cached count) */
2808 print_queue_update(snum, True);
2810 can_job_admin = print_access_check(user, snum, JOB_ACCESS_ADMINISTER);
2811 njobs = print_queue_status(snum, &queue, &status);
2813 if ( can_job_admin )
2814 become_root();
2816 for (i=0;i<njobs;i++) {
2817 BOOL owner = is_owner(user, lp_const_servicename(snum), queue[i].job);
2819 if (owner || can_job_admin) {
2820 print_job_delete1(snum, queue[i].job);
2824 if ( can_job_admin )
2825 unbecome_root();
2827 /* update the cache */
2828 print_queue_update( snum, True );
2830 SAFE_FREE(queue);
2832 return True;