first public release of samba4 code
[gd/samba-autobuild/.git] / source4 / printing / printing.c
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
7    
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.
12    
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.
17    
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.
21 */
22
23 #include "printing.h"
24
25 /* Current printer interface */
26 static struct printif *current_printif = &generic_printif;
27
28 /* 
29    the printing backend revolves around a tdb database that stores the
30    SMB view of the print queue 
31    
32    The key for this database is a jobid - a internally generated number that
33    uniquely identifies a print job
34
35    reading the print queue involves two steps:
36      - possibly running lpq and updating the internal database from that
37      - reading entries from the database
38
39    jobids are assigned when a job starts spooling. 
40 */
41
42 /***************************************************************************
43  Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
44  bit RPC jobids.... JRA.
45 ***************************************************************************/
46
47 static TDB_CONTEXT *rap_tdb;
48 static uint16 next_rap_jobid;
49
50 uint16 pjobid_to_rap(int snum, uint32 jobid)
51 {
52         uint16 rap_jobid;
53         TDB_DATA data, key;
54         char jinfo[8];
55
56         DEBUG(10,("pjobid_to_rap: called.\n"));
57
58         if (!rap_tdb) {
59                 /* Create the in-memory tdb. */
60                 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
61                 if (!rap_tdb)
62                         return 0;
63         }
64
65         SIVAL(&jinfo,0,(int32)snum);
66         SIVAL(&jinfo,4,jobid);
67
68         key.dptr = (char *)&jinfo;
69         key.dsize = sizeof(jinfo);
70         data = tdb_fetch(rap_tdb, key);
71         if (data.dptr && data.dsize == sizeof(uint16)) {
72                 memcpy(&rap_jobid, data.dptr, sizeof(uint16));
73                 SAFE_FREE(data.dptr);
74                 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
75                                 (unsigned int)jobid,
76                                 (unsigned int)rap_jobid));
77                 return rap_jobid;
78         }
79         SAFE_FREE(data.dptr);
80         /* Not found - create and store mapping. */
81         rap_jobid = ++next_rap_jobid;
82         if (rap_jobid == 0)
83                 rap_jobid = ++next_rap_jobid;
84         data.dptr = (char *)&rap_jobid;
85         data.dsize = sizeof(rap_jobid);
86         tdb_store(rap_tdb, key, data, TDB_REPLACE);
87         tdb_store(rap_tdb, data, key, TDB_REPLACE);
88
89         DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
90                                 (unsigned int)jobid,
91                                 (unsigned int)rap_jobid));
92         return rap_jobid;
93 }
94
95 BOOL rap_to_pjobid(uint16 rap_jobid, int *psnum, uint32 *pjobid)
96 {
97         TDB_DATA data, key;
98
99         DEBUG(10,("rap_to_pjobid called.\n"));
100
101         if (!rap_tdb)
102                 return False;
103
104         key.dptr = (char *)&rap_jobid;
105         key.dsize = sizeof(rap_jobid);
106         data = tdb_fetch(rap_tdb, key);
107         if (data.dptr && data.dsize == 8) {
108                 *psnum = IVAL(data.dptr,0);
109                 *pjobid = IVAL(data.dptr,4);
110                 DEBUG(10,("rap_to_pjobid: jobid %u maps to RAP jobid %u\n",
111                                 (unsigned int)*pjobid,
112                                 (unsigned int)rap_jobid));
113                 SAFE_FREE(data.dptr);
114                 return True;
115         }
116
117         DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
118                                 (unsigned int)rap_jobid));
119         SAFE_FREE(data.dptr);
120         return False;
121 }
122
123 static void rap_jobid_delete(int snum, uint32 jobid)
124 {
125         TDB_DATA key, data;
126         uint16 rap_jobid;
127         char jinfo[8];
128
129         DEBUG(10,("rap_jobid_delete: called.\n"));
130
131         if (!rap_tdb)
132                 return;
133
134         SIVAL(&jinfo,0,(int32)snum);
135         SIVAL(&jinfo,4,jobid);
136
137         key.dptr = (char *)&jinfo;
138         key.dsize = sizeof(jinfo);
139         data = tdb_fetch(rap_tdb, key);
140         if (!data.dptr || (data.dsize != sizeof(uint16))) {
141                 DEBUG(10,("rap_jobid_delete: cannot find jobid %u\n",
142                                         (unsigned int)jobid ));
143                 SAFE_FREE(data.dptr);
144                 return;
145         }
146
147         DEBUG(10,("rap_jobid_delete: deleting jobid %u\n",
148                                 (unsigned int)jobid ));
149
150         memcpy(&rap_jobid, data.dptr, sizeof(uint16));
151         SAFE_FREE(data.dptr);
152         data.dptr = (char *)&rap_jobid;
153         data.dsize = sizeof(rap_jobid);
154         tdb_delete(rap_tdb, key);
155         tdb_delete(rap_tdb, data);
156 }
157
158 static pid_t local_pid;
159
160 static int get_queue_status(int, print_status_struct *);
161
162 /****************************************************************************
163  Initialise the printing backend. Called once at startup before the fork().
164 ****************************************************************************/
165
166 BOOL print_backend_init(void)
167 {
168         const char *sversion = "INFO/version";
169         pstring printing_path;
170         int services = lp_numservices();
171         int snum;
172
173         if (local_pid == sys_getpid())
174                 return True;
175
176         unlink(lock_path("printing.tdb"));
177         pstrcpy(printing_path,lock_path("printing"));
178         mkdir(printing_path,0755);
179
180         local_pid = sys_getpid();
181
182         /* handle a Samba upgrade */
183
184         for (snum = 0; snum < services; snum++) {
185                 struct tdb_print_db *pdb;
186                 if (!lp_print_ok(snum))
187                         continue;
188
189                 pdb = get_print_db_byname(lp_const_servicename(snum));
190                 if (!pdb)
191                         continue;
192                 if (tdb_lock_bystring(pdb->tdb, sversion, 0) == -1) {
193                         DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
194                         release_print_db(pdb);
195                         return False;
196                 }
197                 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
198                         tdb_traverse(pdb->tdb, tdb_traverse_delete_fn, NULL);
199                         tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
200                 }
201                 tdb_unlock_bystring(pdb->tdb, sversion);
202                 release_print_db(pdb);
203         }
204
205         close_all_print_db(); /* Don't leave any open. */
206
207         /* select the appropriate printing interface... */
208 #ifdef HAVE_CUPS
209         if (strcmp(lp_printcapname(), "cups") == 0)
210                 current_printif = &cups_printif;
211 #endif /* HAVE_CUPS */
212
213         /* do NT print initialization... */
214         return nt_printing_init();
215 }
216
217 /****************************************************************************
218  Shut down printing backend. Called once at shutdown to close the tdb.
219 ****************************************************************************/
220
221 void printing_end(void)
222 {
223         close_all_print_db(); /* Don't leave any open. */
224 }
225
226 /****************************************************************************
227  Useful function to generate a tdb key.
228 ****************************************************************************/
229
230 static TDB_DATA print_key(uint32 jobid)
231 {
232         static uint32 j;
233         TDB_DATA ret;
234
235         j = jobid;
236         ret.dptr = (void *)&j;
237         ret.dsize = sizeof(j);
238         return ret;
239 }
240
241 /***********************************************************************
242  unpack a pjob from a tdb buffer 
243 ***********************************************************************/
244  
245 int unpack_pjob( char* buf, int buflen, struct printjob *pjob )
246 {
247         int     len = 0;
248         int     used;
249         
250         if ( !buf || !pjob )
251                 return -1;
252                 
253         len += tdb_unpack(buf+len, buflen-len, "dddddddddffff",
254                                 &pjob->pid,
255                                 &pjob->sysjob,
256                                 &pjob->fd,
257                                 &pjob->starttime,
258                                 &pjob->status,
259                                 &pjob->size,
260                                 &pjob->page_count,
261                                 &pjob->spooled,
262                                 &pjob->smbjob,
263                                 pjob->filename,
264                                 pjob->jobname,
265                                 pjob->user,
266                                 pjob->queuename);
267                                 
268         if ( len == -1 )
269                 return -1;
270                 
271         if ( (used = unpack_devicemode(&pjob->nt_devmode, buf+len, buflen-len)) == -1 )
272                 return -1;
273         
274         len += used;
275         
276         return len;
277
278 }
279
280 /****************************************************************************
281  Useful function to find a print job in the database.
282 ****************************************************************************/
283
284 static struct printjob *print_job_find(int snum, uint32 jobid)
285 {
286         static struct printjob  pjob;
287         TDB_DATA                ret;
288         struct tdb_print_db     *pdb = get_print_db_byname(lp_const_servicename(snum));
289         
290
291         if (!pdb)
292                 return NULL;
293
294         ret = tdb_fetch(pdb->tdb, print_key(jobid));
295         release_print_db(pdb);
296
297         if (!ret.dptr)
298                 return NULL;
299         
300         if ( pjob.nt_devmode )
301                 free_nt_devicemode( &pjob.nt_devmode );
302                 
303         ZERO_STRUCT( pjob );
304         
305         if ( unpack_pjob( ret.dptr, ret.dsize, &pjob ) == -1 ) {
306                 SAFE_FREE(ret.dptr);
307                 return NULL;
308         }
309         
310         SAFE_FREE(ret.dptr);    
311         return &pjob;
312 }
313
314 /* Convert a unix jobid to a smb jobid */
315
316 static uint32 sysjob_to_jobid_value;
317
318 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
319                                TDB_DATA data, void *state)
320 {
321         struct printjob *pjob;
322         int *sysjob = (int *)state;
323
324         if (!data.dptr || data.dsize == 0)
325                 return 0;
326
327         pjob = (struct printjob *)data.dptr;
328         if (key.dsize != sizeof(uint32))
329                 return 0;
330
331         if (*sysjob == pjob->sysjob) {
332                 uint32 *jobid = (uint32 *)key.dptr;
333
334                 sysjob_to_jobid_value = *jobid;
335                 return 1;
336         }
337
338         return 0;
339 }
340
341 /****************************************************************************
342  This is a *horribly expensive call as we have to iterate through all the
343  current printer tdb's. Don't do this often ! JRA.
344 ****************************************************************************/
345
346 uint32 sysjob_to_jobid(int unix_jobid)
347 {
348         int services = lp_numservices();
349         int snum;
350
351         sysjob_to_jobid_value = (uint32)-1;
352
353         for (snum = 0; snum < services; snum++) {
354                 struct tdb_print_db *pdb;
355                 if (!lp_print_ok(snum))
356                         continue;
357                 pdb = get_print_db_byname(lp_const_servicename(snum));
358                 if (pdb)
359                         tdb_traverse(pdb->tdb, unixjob_traverse_fn, &unix_jobid);
360                 release_print_db(pdb);
361                 if (sysjob_to_jobid_value != (uint32)-1)
362                         return sysjob_to_jobid_value;
363         }
364         return (uint32)-1;
365 }
366
367 /****************************************************************************
368  Send notifications based on what has changed after a pjob_store.
369 ****************************************************************************/
370
371 static struct {
372         uint32 lpq_status;
373         uint32 spoolss_status;
374 } lpq_to_spoolss_status_map[] = {
375         { LPQ_QUEUED, JOB_STATUS_QUEUED },
376         { LPQ_PAUSED, JOB_STATUS_PAUSED },
377         { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
378         { LPQ_PRINTING, JOB_STATUS_PRINTING },
379         { LPQ_DELETING, JOB_STATUS_DELETING },
380         { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
381         { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
382         { LPQ_PRINTED, JOB_STATUS_PRINTED },
383         { LPQ_DELETED, JOB_STATUS_DELETED },
384         { LPQ_BLOCKED, JOB_STATUS_BLOCKED },
385         { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
386         { -1, 0 }
387 };
388
389 /* Convert a lpq status value stored in printing.tdb into the
390    appropriate win32 API constant. */
391
392 static uint32 map_to_spoolss_status(uint32 lpq_status)
393 {
394         int i = 0;
395
396         while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
397                 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
398                         return lpq_to_spoolss_status_map[i].spoolss_status;
399                 i++;
400         }
401
402         return 0;
403 }
404
405 static void pjob_store_notify(int snum, uint32 jobid, struct printjob *old_data,
406                               struct printjob *new_data)
407 {
408         BOOL new_job = False;
409
410         if (!old_data)
411                 new_job = True;
412
413         /* Notify the job name first */
414
415         if (new_job || !strequal(old_data->jobname, new_data->jobname))
416                 notify_job_name(snum, jobid, new_data->jobname);
417
418         /* Job attributes that can't be changed.  We only send
419            notification for these on a new job. */
420
421         if (new_job) {
422                 notify_job_submitted(snum, jobid, new_data->starttime);
423                 notify_job_username(snum, jobid, new_data->user);
424         }
425
426         /* Job attributes of a new job or attributes that can be
427            modified. */
428
429         if (new_job || old_data->status != new_data->status)
430                 notify_job_status(snum, jobid, map_to_spoolss_status(new_data->status));
431
432         if (new_job || old_data->size != new_data->size)
433                 notify_job_total_bytes(snum, jobid, new_data->size);
434
435         if (new_job || old_data->page_count != new_data->page_count)
436                 notify_job_total_pages(snum, jobid, new_data->page_count);
437 }
438
439 /****************************************************************************
440  Store a job structure back to the database.
441 ****************************************************************************/
442
443 static BOOL pjob_store(int snum, uint32 jobid, struct printjob *pjob)
444 {
445         TDB_DATA                old_data, new_data;
446         BOOL                    ret = False;
447         struct tdb_print_db     *pdb = get_print_db_byname(lp_const_servicename(snum));
448         char                    *buf = NULL;
449         int                     len, newlen, buflen;
450         
451
452         if (!pdb)
453                 return False;
454
455         /* Get old data */
456
457         old_data = tdb_fetch(pdb->tdb, print_key(jobid));
458
459         /* Doh!  Now we have to pack/unpack data since the NT_DEVICEMODE was added */
460
461         newlen = 0;
462         
463         do {
464                 len = 0;
465                 buflen = newlen;
466                 len += tdb_pack(buf+len, buflen-len, "dddddddddffff",
467                                 pjob->pid,
468                                 pjob->sysjob,
469                                 pjob->fd,
470                                 pjob->starttime,
471                                 pjob->status,
472                                 pjob->size,
473                                 pjob->page_count,
474                                 pjob->spooled,
475                                 pjob->smbjob,
476                                 pjob->filename,
477                                 pjob->jobname,
478                                 pjob->user,
479                                 pjob->queuename);
480
481                 len += pack_devicemode(pjob->nt_devmode, buf+len, buflen-len);
482         
483                 if (buflen != len) {
484                         char *tb;
485
486                         tb = (char *)Realloc(buf, len);
487                         if (!tb) {
488                                 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
489                                 goto done;
490                         }
491                         else 
492                                 buf = tb;
493                         newlen = len;
494                 }
495         } while ( buflen != len );
496                 
497         
498         /* Store new data */
499
500         new_data.dptr = buf;
501         new_data.dsize = len;
502         ret = (tdb_store(pdb->tdb, print_key(jobid), new_data, TDB_REPLACE) == 0);
503
504         release_print_db(pdb);
505
506         /* Send notify updates for what has changed */
507
508         if ( ret && (old_data.dsize == 0 || old_data.dsize == sizeof(*pjob)) )
509                 pjob_store_notify( snum, jobid, (struct printjob *)old_data.dptr, pjob );
510
511 done:
512         SAFE_FREE( old_data.dptr );
513         SAFE_FREE( buf );
514
515         return ret;
516 }
517
518 /****************************************************************************
519  Remove a job structure from the database.
520 ****************************************************************************/
521
522 void pjob_delete(int snum, uint32 jobid)
523 {
524         struct printjob *pjob = print_job_find(snum, jobid);
525         uint32 job_status = 0;
526         struct tdb_print_db *pdb = get_print_db_byname(lp_const_servicename(snum));
527
528         if (!pdb)
529                 return;
530
531         if (!pjob) {
532                 DEBUG(5, ("pjob_delete(): we were asked to delete nonexistent job %u\n",
533                                         (unsigned int)jobid));
534                 release_print_db(pdb);
535                 return;
536         }
537
538         /* Send a notification that a job has been deleted */
539
540         job_status = map_to_spoolss_status(pjob->status);
541
542         /* We must cycle through JOB_STATUS_DELETING and
543            JOB_STATUS_DELETED for the port monitor to delete the job
544            properly. */
545         
546         job_status |= JOB_STATUS_DELETING;
547         notify_job_status(snum, jobid, job_status);
548         
549         job_status |= JOB_STATUS_DELETED;
550         notify_job_status(snum, jobid, job_status);
551
552         /* Remove from printing.tdb */
553
554         tdb_delete(pdb->tdb, print_key(jobid));
555         release_print_db(pdb);
556         rap_jobid_delete(snum, jobid);
557 }
558
559 /****************************************************************************
560  Parse a file name from the system spooler to generate a jobid.
561 ****************************************************************************/
562
563 static uint32 print_parse_jobid(char *fname)
564 {
565         int jobid;
566
567         if (strncmp(fname,PRINT_SPOOL_PREFIX,strlen(PRINT_SPOOL_PREFIX)) != 0)
568                 return (uint32)-1;
569         fname += strlen(PRINT_SPOOL_PREFIX);
570
571         jobid = atoi(fname);
572         if (jobid <= 0)
573                 return (uint32)-1;
574
575         return (uint32)jobid;
576 }
577
578 /****************************************************************************
579  List a unix job in the print database.
580 ****************************************************************************/
581
582 static void print_unix_job(int snum, print_queue_struct *q, uint32 jobid)
583 {
584         struct printjob pj, *old_pj;
585
586         if (jobid == (uint32)-1)
587                 jobid = q->job + UNIX_JOB_START;
588
589         /* Preserve the timestamp on an existing unix print job */
590
591         old_pj = print_job_find(snum, jobid);
592
593         ZERO_STRUCT(pj);
594
595         pj.pid = (pid_t)-1;
596         pj.sysjob = q->job;
597         pj.fd = -1;
598         pj.starttime = old_pj ? old_pj->starttime : q->time;
599         pj.status = q->status;
600         pj.size = q->size;
601         pj.spooled = True;
602         pj.smbjob = (old_pj != NULL ? True : False);
603         fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
604         if (jobid < UNIX_JOB_START)
605                 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
606         else
607                 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
608         fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
609         fstrcpy(pj.queuename, old_pj ? old_pj->queuename : lp_const_servicename(snum));
610
611         pjob_store(snum, jobid, &pj);
612 }
613
614
615 struct traverse_struct {
616         print_queue_struct *queue;
617         int qcount, snum, maxcount, total_jobs;
618         time_t lpq_time;
619 };
620
621 /****************************************************************************
622  Utility fn to delete any jobs that are no longer active.
623 ****************************************************************************/
624
625 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
626 {
627         struct traverse_struct *ts = (struct traverse_struct *)state;
628         struct printjob pjob;
629         uint32 jobid;
630         int i;
631
632         if (  key.dsize != sizeof(jobid) )
633                 return 0;
634                 
635         memcpy(&jobid, key.dptr, sizeof(jobid));
636         if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
637                 return 0;
638         free_nt_devicemode( &pjob.nt_devmode );
639
640
641         if (ts->snum != lp_servicenumber(pjob.queuename)) {
642                 /* this isn't for the queue we are looking at - this cannot happen with the split tdb's. JRA */
643                 return 0;
644         }
645
646         if (!pjob.smbjob) {
647                 /* remove a unix job if it isn't in the system queue any more */
648
649                 for (i=0;i<ts->qcount;i++) {
650                         uint32 u_jobid = (ts->queue[i].job + UNIX_JOB_START);
651                         if (jobid == u_jobid)
652                                 break;
653                 }
654                 if (i == ts->qcount)
655                         pjob_delete(ts->snum, jobid);
656                 else
657                         ts->total_jobs++;
658                 return 0;
659         }
660
661         /* maybe it hasn't been spooled yet */
662         if (!pjob.spooled) {
663                 /* if a job is not spooled and the process doesn't
664                    exist then kill it. This cleans up after smbd
665                    deaths */
666                 if (!process_exists(pjob.pid))
667                         pjob_delete(ts->snum, jobid);
668                 else
669                         ts->total_jobs++;
670                 return 0;
671         }
672
673         for (i=0;i<ts->qcount;i++) {
674                 uint32 curr_jobid = print_parse_jobid(ts->queue[i].fs_file);
675                 if (jobid == curr_jobid)
676                         break;
677         }
678         
679         /* The job isn't in the system queue - we have to assume it has
680            completed, so delete the database entry. */
681
682         if (i == ts->qcount) {
683
684                 /* A race can occur between the time a job is spooled and
685                    when it appears in the lpq output.  This happens when
686                    the job is added to printing.tdb when another smbd
687                    running print_queue_update() has completed a lpq and
688                    is currently traversing the printing tdb and deleting jobs.
689                    Don't delete the job if it was submitted after the lpq_time. */
690
691                 if (pjob.starttime < ts->lpq_time)
692                         pjob_delete(ts->snum, jobid);
693                 else
694                         ts->total_jobs++;
695         }
696         else
697                 ts->total_jobs++;
698
699         return 0;
700 }
701
702 /****************************************************************************
703  Check if the print queue has been updated recently enough.
704 ****************************************************************************/
705
706 static void print_cache_flush(int snum)
707 {
708         fstring key;
709         const char *printername = lp_const_servicename(snum);
710         struct tdb_print_db *pdb = get_print_db_byname(printername);
711
712         if (!pdb)
713                 return;
714         slprintf(key, sizeof(key)-1, "CACHE/%s", printername);
715         tdb_store_int32(pdb->tdb, key, -1);
716         release_print_db(pdb);
717 }
718
719 /****************************************************************************
720  Check if someone already thinks they are doing the update.
721 ****************************************************************************/
722
723 static pid_t get_updating_pid(fstring printer_name)
724 {
725         fstring keystr;
726         TDB_DATA data, key;
727         pid_t updating_pid;
728         struct tdb_print_db *pdb = get_print_db_byname(printer_name);
729
730         if (!pdb)
731                 return (pid_t)-1;
732         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
733         key.dptr = keystr;
734         key.dsize = strlen(keystr);
735
736         data = tdb_fetch(pdb->tdb, key);
737         release_print_db(pdb);
738         if (!data.dptr || data.dsize != sizeof(pid_t)) {
739                 SAFE_FREE(data.dptr);
740                 return (pid_t)-1;
741         }
742
743         memcpy(&updating_pid, data.dptr, sizeof(pid_t));
744         SAFE_FREE(data.dptr);
745
746         if (process_exists(updating_pid))
747                 return updating_pid;
748
749         return (pid_t)-1;
750 }
751
752 /****************************************************************************
753  Set the fact that we're doing the update, or have finished doing the update
754  in the tdb.
755 ****************************************************************************/
756
757 static void set_updating_pid(const fstring printer_name, BOOL delete)
758 {
759         fstring keystr;
760         TDB_DATA key;
761         TDB_DATA data;
762         pid_t updating_pid = sys_getpid();
763         struct tdb_print_db *pdb = get_print_db_byname(printer_name);
764
765         if (!pdb)
766                 return;
767
768         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", printer_name);
769         key.dptr = keystr;
770         key.dsize = strlen(keystr);
771
772         if (delete) {
773                 tdb_delete(pdb->tdb, key);
774                 release_print_db(pdb);
775                 return;
776         }
777         
778         data.dptr = (void *)&updating_pid;
779         data.dsize = sizeof(pid_t);
780
781         tdb_store(pdb->tdb, key, data, TDB_REPLACE);    
782         release_print_db(pdb);
783 }
784
785 /****************************************************************************
786  Update the internal database from the system print queue for a queue.
787 ****************************************************************************/
788
789 static void print_queue_update(int snum)
790 {
791         int i, qcount;
792         print_queue_struct *queue = NULL;
793         print_status_struct status;
794         print_status_struct old_status;
795         struct printjob *pjob;
796         struct traverse_struct tstruct;
797         fstring keystr, printer_name, cachestr;
798         TDB_DATA data, key;
799         struct tdb_print_db *pdb;
800
801         fstrcpy(printer_name, lp_const_servicename(snum));
802         pdb = get_print_db_byname(printer_name);
803         if (!pdb)
804                 return;
805
806         /*
807          * Check to see if someone else is doing this update.
808          * This is essentially a mutex on the update.
809          */
810
811         if (get_updating_pid(printer_name) != -1) {
812                 release_print_db(pdb);
813                 return;
814         }
815
816         /* Lock the queue for the database update */
817
818         slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", printer_name);
819         /* Only wait 10 seconds for this. */
820         if (tdb_lock_bystring(pdb->tdb, keystr, 10) == -1) {
821                 DEBUG(0,("print_queue_update: Failed to lock printer %s database\n", printer_name));
822                 release_print_db(pdb);
823                 return;
824         }
825
826         /*
827          * Ensure that no one else got in here.
828          * If the updating pid is still -1 then we are
829          * the winner.
830          */
831
832         if (get_updating_pid(printer_name) != -1) {
833                 /*
834                  * Someone else is doing the update, exit.
835                  */
836                 tdb_unlock_bystring(pdb->tdb, keystr);
837                 release_print_db(pdb);
838                 return;
839         }
840
841         /*
842          * We're going to do the update ourselves.
843          */
844
845         /* Tell others we're doing the update. */
846         set_updating_pid(printer_name, False);
847
848         /*
849          * Allow others to enter and notice we're doing
850          * the update.
851          */
852
853         tdb_unlock_bystring(pdb->tdb, keystr);
854
855         /*
856          * Update the cache time FIRST ! Stops others even
857          * attempting to get the lock and doing this
858          * if the lpq takes a long time.
859          */
860
861         slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", printer_name);
862         tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
863
864         /* get the current queue using the appropriate interface */
865         ZERO_STRUCT(status);
866
867         qcount = (*(current_printif->queue_get))(snum, &queue, &status);
868
869         DEBUG(3, ("%d job%s in queue for %s\n", qcount, (qcount != 1) ?
870                 "s" : "", printer_name));
871
872         /*
873           any job in the internal database that is marked as spooled
874           and doesn't exist in the system queue is considered finished
875           and removed from the database
876
877           any job in the system database but not in the internal database 
878           is added as a unix job
879
880           fill in any system job numbers as we go
881         */
882         for (i=0; i<qcount; i++) {
883                 uint32 jobid = print_parse_jobid(queue[i].fs_file);
884
885                 if (jobid == (uint32)-1) {
886                         /* assume its a unix print job */
887                         print_unix_job(snum, &queue[i], jobid);
888                         continue;
889                 }
890
891                 /* we have an active SMB print job - update its status */
892                 pjob = print_job_find(snum, jobid);
893                 if (!pjob) {
894                         /* err, somethings wrong. Probably smbd was restarted
895                            with jobs in the queue. All we can do is treat them
896                            like unix jobs. Pity. */
897                         print_unix_job(snum, &queue[i], jobid);
898                         continue;
899                 }
900
901                 pjob->sysjob = queue[i].job;
902                 pjob->status = queue[i].status;
903
904                 pjob_store(snum, jobid, pjob);
905         }
906
907         /* now delete any queued entries that don't appear in the
908            system queue */
909         tstruct.queue = queue;
910         tstruct.qcount = qcount;
911         tstruct.snum = snum;
912         tstruct.total_jobs = 0;
913         tstruct.lpq_time = time(NULL);
914
915         tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
916
917         SAFE_FREE(tstruct.queue);
918
919         DEBUG(10,("print_queue_update: printer %s INFO/total_jobs = %d\n",
920                                 printer_name, tstruct.total_jobs ));
921
922         tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
923
924         get_queue_status(snum, &old_status);
925         if (old_status.qcount != qcount)
926                 DEBUG(10,("print_queue_update: queue status change %d jobs -> %d jobs for printer %s\n",
927                                         old_status.qcount, qcount, printer_name ));
928
929         /* store the new queue status structure */
930         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printer_name);
931         key.dptr = keystr;
932         key.dsize = strlen(keystr);
933
934         status.qcount = qcount;
935         data.dptr = (void *)&status;
936         data.dsize = sizeof(status);
937         tdb_store(pdb->tdb, key, data, TDB_REPLACE);    
938
939         /*
940          * Update the cache time again. We want to do this call
941          * as little as possible...
942          */
943
944         slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", printer_name);
945         tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
946
947         /* Delete our pid from the db. */
948         set_updating_pid(printer_name, True);
949         release_print_db(pdb);
950 }
951
952 /****************************************************************************
953  Create/Update an entry in the print tdb that will allow us to send notify
954  updates only to interested smbd's. 
955 ****************************************************************************/
956
957 BOOL print_notify_register_pid(int snum)
958 {
959         TDB_DATA data;
960         struct tdb_print_db *pdb = NULL;
961         TDB_CONTEXT *tdb = NULL;
962         const char *printername;
963         uint32 mypid = (uint32)sys_getpid();
964         BOOL ret = False;
965         size_t i;
966
967         /* if (snum == -1), then the change notify request was
968            on a print server handle and we need to register on
969            all print queus */
970            
971         if (snum == -1) 
972         {
973                 int num_services = lp_numservices();
974                 int idx;
975                 
976                 for ( idx=0; idx<num_services; idx++ ) {
977                         if (lp_snum_ok(idx) && lp_print_ok(idx) )
978                                 print_notify_register_pid(idx);
979                 }
980                 
981                 return True;
982         }
983         else /* register for a specific printer */
984         {
985                 printername = lp_const_servicename(snum);
986                 pdb = get_print_db_byname(printername);
987                 if (!pdb)
988                         return False;
989                 tdb = pdb->tdb;
990         }
991
992         if (tdb_lock_bystring(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
993                 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
994                                         printername));
995                 if (pdb)
996                         release_print_db(pdb);
997                 return False;
998         }
999
1000         data = get_printer_notify_pid_list( tdb, printername, True );
1001
1002         /* Add ourselves and increase the refcount. */
1003
1004         for (i = 0; i < data.dsize; i += 8) {
1005                 if (IVAL(data.dptr,i) == mypid) {
1006                         uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1007                         SIVAL(data.dptr, i+4, new_refcount);
1008                         break;
1009                 }
1010         }
1011
1012         if (i == data.dsize) {
1013                 /* We weren't in the list. Realloc. */
1014                 data.dptr = Realloc(data.dptr, data.dsize + 8);
1015                 if (!data.dptr) {
1016                         DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1017                                                 printername));
1018                         goto done;
1019                 }
1020                 data.dsize += 8;
1021                 SIVAL(data.dptr,data.dsize - 8,mypid);
1022                 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1023         }
1024
1025         /* Store back the record. */
1026         if (tdb_store_by_string(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1027                 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1028 list for printer %s\n", printername));
1029                 goto done;
1030         }
1031
1032         ret = True;
1033
1034  done:
1035
1036         tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1037         if (pdb)
1038                 release_print_db(pdb);
1039         SAFE_FREE(data.dptr);
1040         return ret;
1041 }
1042
1043 /****************************************************************************
1044  Update an entry in the print tdb that will allow us to send notify
1045  updates only to interested smbd's. 
1046 ****************************************************************************/
1047
1048 BOOL print_notify_deregister_pid(int snum)
1049 {
1050         TDB_DATA data;
1051         struct tdb_print_db *pdb = NULL;
1052         TDB_CONTEXT *tdb = NULL;
1053         const char *printername;
1054         uint32 mypid = (uint32)sys_getpid();
1055         size_t i;
1056         BOOL ret = False;
1057
1058         /* if ( snum == -1 ), we are deregister a print server handle
1059            which means to deregister on all print queues */
1060            
1061         if (snum == -1) 
1062         {
1063                 int num_services = lp_numservices();
1064                 int idx;
1065                 
1066                 for ( idx=0; idx<num_services; idx++ ) {
1067                         if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1068                                 print_notify_deregister_pid(idx);
1069                 }
1070                 
1071                 return True;
1072         }
1073         else /* deregister a specific printer */
1074         {
1075                 printername = lp_const_servicename(snum);
1076                 pdb = get_print_db_byname(printername);
1077                 if (!pdb)
1078                         return False;
1079                 tdb = pdb->tdb;
1080         }
1081
1082         if (tdb_lock_bystring(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1083                 DEBUG(0,("print_notify_register_pid: Failed to lock \
1084 printer %s database\n", printername));
1085                 if (pdb)
1086                         release_print_db(pdb);
1087                 return False;
1088         }
1089
1090         data = get_printer_notify_pid_list( tdb, printername, True );
1091
1092         /* Reduce refcount. Remove ourselves if zero. */
1093
1094         for (i = 0; i < data.dsize; ) {
1095                 if (IVAL(data.dptr,i) == mypid) {
1096                         uint32 refcount = IVAL(data.dptr, i+4);
1097
1098                         refcount--;
1099
1100                         if (refcount == 0) {
1101                                 if (data.dsize - i > 8)
1102                                         memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
1103                                 data.dsize -= 8;
1104                                 continue;
1105                         }
1106                         SIVAL(data.dptr, i+4, refcount);
1107                 }
1108
1109                 i += 8;
1110         }
1111
1112         if (data.dsize == 0)
1113                 SAFE_FREE(data.dptr);
1114
1115         /* Store back the record. */
1116         if (tdb_store_by_string(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1117                 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1118 list for printer %s\n", printername));
1119                 goto done;
1120         }
1121
1122         ret = True;
1123
1124   done:
1125
1126         tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1127         if (pdb)
1128                 release_print_db(pdb);
1129         SAFE_FREE(data.dptr);
1130         return ret;
1131 }
1132
1133 /****************************************************************************
1134  Check if a jobid is valid. It is valid if it exists in the database.
1135 ****************************************************************************/
1136
1137 BOOL print_job_exists(int snum, uint32 jobid)
1138 {
1139         struct tdb_print_db *pdb = get_print_db_byname(lp_const_servicename(snum));
1140         BOOL ret;
1141
1142         if (!pdb)
1143                 return False;
1144         ret = tdb_exists(pdb->tdb, print_key(jobid));
1145         release_print_db(pdb);
1146         return ret;
1147 }
1148
1149 /****************************************************************************
1150  Give the fd used for a jobid.
1151 ****************************************************************************/
1152
1153 int print_job_fd(int snum, uint32 jobid)
1154 {
1155         struct printjob *pjob = print_job_find(snum, jobid);
1156         if (!pjob)
1157                 return -1;
1158         /* don't allow another process to get this info - it is meaningless */
1159         if (pjob->pid != local_pid)
1160                 return -1;
1161         return pjob->fd;
1162 }
1163
1164 /****************************************************************************
1165  Give the filename used for a jobid.
1166  Only valid for the process doing the spooling and when the job
1167  has not been spooled.
1168 ****************************************************************************/
1169
1170 char *print_job_fname(int snum, uint32 jobid)
1171 {
1172         struct printjob *pjob = print_job_find(snum, jobid);
1173         if (!pjob || pjob->spooled || pjob->pid != local_pid)
1174                 return NULL;
1175         return pjob->filename;
1176 }
1177
1178
1179 /****************************************************************************
1180  Give the filename used for a jobid.
1181  Only valid for the process doing the spooling and when the job
1182  has not been spooled.
1183 ****************************************************************************/
1184
1185 NT_DEVICEMODE *print_job_devmode(int snum, uint32 jobid)
1186 {
1187         struct printjob *pjob = print_job_find(snum, jobid);
1188         
1189         if ( !pjob )
1190                 return NULL;
1191                 
1192         return pjob->nt_devmode;
1193 }
1194
1195 /****************************************************************************
1196  Set the place in the queue for a job.
1197 ****************************************************************************/
1198
1199 BOOL print_job_set_place(int snum, uint32 jobid, int place)
1200 {
1201         DEBUG(2,("print_job_set_place not implemented yet\n"));
1202         return False;
1203 }
1204
1205 /****************************************************************************
1206  Set the name of a job. Only possible for owner.
1207 ****************************************************************************/
1208
1209 BOOL print_job_set_name(int snum, uint32 jobid, char *name)
1210 {
1211         struct printjob *pjob = print_job_find(snum, jobid);
1212         if (!pjob || pjob->pid != local_pid)
1213                 return False;
1214
1215         fstrcpy(pjob->jobname, name);
1216         return pjob_store(snum, jobid, pjob);
1217 }
1218
1219 /****************************************************************************
1220  Delete a print job - don't update queue.
1221 ****************************************************************************/
1222
1223 static BOOL print_job_delete1(int snum, uint32 jobid)
1224 {
1225         struct printjob *pjob = print_job_find(snum, jobid);
1226         int result = 0;
1227
1228         if (!pjob)
1229                 return False;
1230
1231         /*
1232          * If already deleting just return.
1233          */
1234
1235         if (pjob->status == LPQ_DELETING)
1236                 return True;
1237
1238         /* Hrm - we need to be able to cope with deleting a job before it
1239            has reached the spooler. */
1240
1241         if (pjob->sysjob == -1) {
1242                 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
1243         }
1244
1245         /* Set the tdb entry to be deleting. */
1246
1247         pjob->status = LPQ_DELETING;
1248         pjob_store(snum, jobid, pjob);
1249
1250         if (pjob->spooled && pjob->sysjob != -1)
1251                 result = (*(current_printif->job_delete))(snum, pjob);
1252
1253         /* Delete the tdb entry if the delete suceeded or the job hasn't
1254            been spooled. */
1255
1256         if (result == 0)
1257                 pjob_delete(snum, jobid);
1258
1259         return (result == 0);
1260 }
1261
1262 /****************************************************************************
1263  Return true if the current user owns the print job.
1264 ****************************************************************************/
1265
1266 static BOOL is_owner(struct current_user *user, int snum, uint32 jobid)
1267 {
1268         struct printjob *pjob = print_job_find(snum, jobid);
1269         user_struct *vuser;
1270
1271         if (!pjob || !user)
1272                 return False;
1273
1274         if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
1275                 return strequal(pjob->user, vuser->user.smb_name);
1276         } else {
1277                 return strequal(pjob->user, uidtoname(user->uid));
1278         }
1279 }
1280
1281 /****************************************************************************
1282  Delete a print job.
1283 ****************************************************************************/
1284
1285 BOOL print_job_delete(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1286 {
1287         BOOL    owner, deleted;
1288         char    *fname;
1289
1290         *errcode = WERR_OK;
1291                 
1292         owner = is_owner(user, snum, jobid);
1293         
1294         /* Check access against security descriptor or whether the user
1295            owns their job. */
1296
1297         if (!owner && 
1298             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1299                 DEBUG(3, ("delete denied by security descriptor\n"));
1300                 *errcode = WERR_ACCESS_DENIED;
1301
1302                 /* BEGIN_ADMIN_LOG */
1303                 sys_adminlog( LOG_ERR, 
1304                               "Permission denied-- user not allowed to delete, \
1305 pause, or resume print job. User name: %s. Printer name: %s.",
1306                               uidtoname(user->uid), PRINTERNAME(snum) );
1307                 /* END_ADMIN_LOG */
1308
1309                 return False;
1310         }
1311
1312         /* 
1313          * get the spooled filename of the print job
1314          * if this works, then the file has not been spooled
1315          * to the underlying print system.  Just delete the 
1316          * spool file & return.
1317          */
1318          
1319         if ( (fname = print_job_fname( snum, jobid )) != NULL )
1320         {
1321                 /* remove the spool file */
1322                 DEBUG(10,("print_job_delete: Removing spool file [%s]\n", fname ));
1323                 if ( unlink( fname ) == -1 ) {
1324                         *errcode = map_werror_from_unix(errno);
1325                         return False;
1326                 }
1327                 
1328                 return True;
1329         }
1330         
1331         if (!print_job_delete1(snum, jobid)) {
1332                 *errcode = WERR_ACCESS_DENIED;
1333                 return False;
1334         }
1335
1336         /* force update the database and say the delete failed if the
1337            job still exists */
1338
1339         print_queue_update(snum);
1340         
1341         deleted = !print_job_exists(snum, jobid);
1342         if ( !deleted )
1343                 *errcode = WERR_ACCESS_DENIED;
1344
1345         return deleted;
1346 }
1347
1348 /****************************************************************************
1349  Pause a job.
1350 ****************************************************************************/
1351
1352 BOOL print_job_pause(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1353 {
1354         struct printjob *pjob = print_job_find(snum, jobid);
1355         int ret = -1;
1356         
1357         if (!pjob || !user) 
1358                 return False;
1359
1360         if (!pjob->spooled || pjob->sysjob == -1) 
1361                 return False;
1362
1363         if (!is_owner(user, snum, jobid) &&
1364             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1365                 DEBUG(3, ("pause denied by security descriptor\n"));
1366
1367                 /* BEGIN_ADMIN_LOG */
1368                 sys_adminlog( LOG_ERR, 
1369                         "Permission denied-- user not allowed to delete, \
1370 pause, or resume print job. User name: %s. Printer name: %s.",
1371                                 uidtoname(user->uid), PRINTERNAME(snum) );
1372                 /* END_ADMIN_LOG */
1373
1374                 *errcode = WERR_ACCESS_DENIED;
1375                 return False;
1376         }
1377
1378         /* need to pause the spooled entry */
1379         ret = (*(current_printif->job_pause))(snum, pjob);
1380
1381         if (ret != 0) {
1382                 *errcode = WERR_INVALID_PARAM;
1383                 return False;
1384         }
1385
1386         /* force update the database */
1387         print_cache_flush(snum);
1388
1389         /* Send a printer notify message */
1390
1391         notify_job_status(snum, jobid, JOB_STATUS_PAUSED);
1392
1393         /* how do we tell if this succeeded? */
1394
1395         return True;
1396 }
1397
1398 /****************************************************************************
1399  Resume a job.
1400 ****************************************************************************/
1401
1402 BOOL print_job_resume(struct current_user *user, int snum, uint32 jobid, WERROR *errcode)
1403 {
1404         struct printjob *pjob = print_job_find(snum, jobid);
1405         int ret;
1406         
1407         if (!pjob || !user)
1408                 return False;
1409
1410         if (!pjob->spooled || pjob->sysjob == -1)
1411                 return False;
1412
1413         if (!is_owner(user, snum, jobid) &&
1414             !print_access_check(user, snum, JOB_ACCESS_ADMINISTER)) {
1415                 DEBUG(3, ("resume denied by security descriptor\n"));
1416                 *errcode = WERR_ACCESS_DENIED;
1417
1418                 /* BEGIN_ADMIN_LOG */
1419                 sys_adminlog( LOG_ERR, 
1420                          "Permission denied-- user not allowed to delete, \
1421 pause, or resume print job. User name: %s. Printer name: %s.",
1422                         uidtoname(user->uid), PRINTERNAME(snum) );
1423                 /* END_ADMIN_LOG */
1424                 return False;
1425         }
1426
1427         ret = (*(current_printif->job_resume))(snum, pjob);
1428
1429         if (ret != 0) {
1430                 *errcode = WERR_INVALID_PARAM;
1431                 return False;
1432         }
1433
1434         /* force update the database */
1435         print_cache_flush(snum);
1436
1437         /* Send a printer notify message */
1438
1439         notify_job_status(snum, jobid, JOB_STATUS_QUEUED);
1440
1441         return True;
1442 }
1443
1444 /****************************************************************************
1445  Write to a print file.
1446 ****************************************************************************/
1447
1448 int print_job_write(int snum, uint32 jobid, const char *buf, int size)
1449 {
1450         int return_code;
1451         struct printjob *pjob = print_job_find(snum, jobid);
1452
1453         if (!pjob)
1454                 return -1;
1455         /* don't allow another process to get this info - it is meaningless */
1456         if (pjob->pid != local_pid)
1457                 return -1;
1458
1459         return_code = write(pjob->fd, buf, size);
1460         if (return_code>0) {
1461                 pjob->size += size;
1462                 pjob_store(snum, jobid, pjob);
1463         }
1464         return return_code;
1465 }
1466
1467 /****************************************************************************
1468  Check if the print queue has been updated recently enough.
1469 ****************************************************************************/
1470
1471 static BOOL print_cache_expired(int snum)
1472 {
1473         fstring key;
1474         time_t last_qscan_time, time_now = time(NULL);
1475         const char *printername = lp_const_servicename(snum);
1476         struct tdb_print_db *pdb = get_print_db_byname(printername);
1477
1478         if (!pdb)
1479                 return False;
1480
1481         slprintf(key, sizeof(key), "CACHE/%s", printername);
1482         last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1483
1484         /*
1485          * Invalidate the queue for 3 reasons.
1486          * (1). last queue scan time == -1.
1487          * (2). Current time - last queue scan time > allowed cache time.
1488          * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1489          * This last test picks up machines for which the clock has been moved
1490          * forward, an lpq scan done and then the clock moved back. Otherwise
1491          * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1492          */
1493
1494         if (last_qscan_time == ((time_t)-1) || (time_now - last_qscan_time) >= lp_lpqcachetime() ||
1495                         last_qscan_time > (time_now + MAX_CACHE_VALID_TIME)) {
1496                 DEBUG(3, ("print cache expired for queue %s \
1497 (last_qscan_time = %d, time now = %d, qcachetime = %d)\n", printername,
1498                         (int)last_qscan_time, (int)time_now, (int)lp_lpqcachetime() ));
1499                 release_print_db(pdb);
1500                 return True;
1501         }
1502         release_print_db(pdb);
1503         return False;
1504 }
1505
1506 /****************************************************************************
1507  Get the queue status - do not update if db is out of date.
1508 ****************************************************************************/
1509
1510 static int get_queue_status(int snum, print_status_struct *status)
1511 {
1512         fstring keystr;
1513         TDB_DATA data, key;
1514         const char *printername = lp_const_servicename(snum);
1515         struct tdb_print_db *pdb = get_print_db_byname(printername);
1516         int len;
1517
1518         if (!pdb)
1519                 return 0;
1520
1521         if (status) {
1522                 ZERO_STRUCTP(status);
1523                 slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printername);
1524                 key.dptr = keystr;
1525                 key.dsize = strlen(keystr);
1526                 data = tdb_fetch(pdb->tdb, key);
1527                 if (data.dptr) {
1528                         if (data.dsize == sizeof(print_status_struct))
1529                                 memcpy(status, data.dptr, sizeof(print_status_struct));
1530                         SAFE_FREE(data.dptr);
1531                 }
1532         }
1533         len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
1534         release_print_db(pdb);
1535         return (len == -1 ? 0 : len);
1536 }
1537
1538 /****************************************************************************
1539  Determine the number of jobs in a queue.
1540 ****************************************************************************/
1541
1542 int print_queue_length(int snum, print_status_struct *pstatus)
1543 {
1544         print_status_struct status;
1545         int len;
1546  
1547         /* make sure the database is up to date */
1548         if (print_cache_expired(snum))
1549                 print_queue_update(snum);
1550  
1551         /* also fetch the queue status */
1552         memset(&status, 0, sizeof(status));
1553         len = get_queue_status(snum, &status);
1554
1555         if (pstatus)
1556                 *pstatus = status;
1557
1558         return len;
1559 }
1560
1561 /***************************************************************************
1562  Allocate a jobid. Hold the lock for as short a time as possible.
1563 ***************************************************************************/
1564
1565 static BOOL allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char *printername, uint32 *pjobid)
1566 {
1567         int i;
1568         uint32 jobid;
1569
1570         *pjobid = (uint32)-1;
1571
1572         for (i = 0; i < 3; i++) {
1573                 /* Lock the database - only wait 20 seconds. */
1574                 if (tdb_lock_bystring(pdb->tdb, "INFO/nextjob", 20) == -1) {
1575                         DEBUG(0,("allocate_print_jobid: failed to lock printing database %s\n", printername ));
1576                         return False;
1577                 }
1578
1579                 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
1580                         if (tdb_error(pdb->tdb) != TDB_ERR_NOEXIST) {
1581                                 DEBUG(0, ("allocate_print_jobid: failed to fetch INFO/nextjob for print queue %s\n",
1582                                                 printername ));
1583                                 return False;
1584                         }
1585                         jobid = 0;
1586                 }
1587
1588                 jobid = NEXT_JOBID(jobid);
1589
1590                 if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
1591                         DEBUG(3, ("allocate_print_jobid: failed to store INFO/nextjob.\n"));
1592                         tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
1593                         return False;
1594                 }
1595
1596                 /* We've finished with the INFO/nextjob lock. */
1597                 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
1598                                 
1599                 if (!print_job_exists(snum, jobid))
1600                         break;
1601         }
1602
1603         if (i > 2) {
1604                 DEBUG(0, ("allocate_print_jobid: failed to allocate a print job for queue %s\n",
1605                                 printername ));
1606                 /* Probably full... */
1607                 errno = ENOSPC;
1608                 return False;
1609         }
1610
1611         /* Store a dummy placeholder. */
1612         {
1613                 TDB_DATA dum;
1614                 dum.dptr = NULL;
1615                 dum.dsize = 0;
1616                 if (tdb_store(pdb->tdb, print_key(jobid), dum, TDB_INSERT) == -1) {
1617                         DEBUG(3, ("allocate_print_jobid: jobid (%d) failed to store placeholder.\n",
1618                                 jobid ));
1619                         return False;
1620                 }
1621         }
1622
1623         *pjobid = jobid;
1624         return True;
1625 }
1626
1627 /***************************************************************************
1628  Start spooling a job - return the jobid.
1629 ***************************************************************************/
1630
1631 uint32 print_job_start(struct current_user *user, int snum, char *jobname, NT_DEVICEMODE *nt_devmode )
1632 {
1633         uint32 jobid;
1634         char *path;
1635         struct printjob pjob;
1636         user_struct *vuser;
1637         const char *printername = lp_const_servicename(snum);
1638         struct tdb_print_db *pdb = get_print_db_byname(printername);
1639         int njobs;
1640
1641         errno = 0;
1642
1643         if (!pdb)
1644                 return (uint32)-1;
1645
1646         if (!print_access_check(user, snum, PRINTER_ACCESS_USE)) {
1647                 DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
1648                 release_print_db(pdb);
1649                 return (uint32)-1;
1650         }
1651
1652         if (!print_time_access_check(snum)) {
1653                 DEBUG(3, ("print_job_start: job start denied by time check\n"));
1654                 release_print_db(pdb);
1655                 return (uint32)-1;
1656         }
1657
1658         path = lp_pathname(snum);
1659
1660         /* see if we have sufficient disk space */
1661         if (lp_minprintspace(snum)) {
1662                 SMB_BIG_UINT dspace, dsize;
1663                 if (sys_fsusage(path, &dspace, &dsize) == 0 &&
1664                     dspace < 2*(SMB_BIG_UINT)lp_minprintspace(snum)) {
1665                         DEBUG(3, ("print_job_start: disk space check failed.\n"));
1666                         release_print_db(pdb);
1667                         errno = ENOSPC;
1668                         return (uint32)-1;
1669                 }
1670         }
1671
1672         /* for autoloaded printers, check that the printcap entry still exists */
1673         if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum), NULL)) {
1674                 DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
1675                 release_print_db(pdb);
1676                 errno = ENOENT;
1677                 return (uint32)-1;
1678         }
1679
1680         /* Insure the maximum queue size is not violated */
1681         if ((njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
1682                 DEBUG(3, ("print_job_start: Queue %s number of jobs (%d) larger than max printjobs per queue (%d).\n",
1683                         printername, njobs, lp_maxprintjobs(snum) ));
1684                 release_print_db(pdb);
1685                 errno = ENOSPC;
1686                 return (uint32)-1;
1687         }
1688
1689         DEBUG(10,("print_job_start: Queue %s number of jobs (%d), max printjobs = %d\n",
1690                         printername, njobs, lp_maxprintjobs(snum) ));
1691
1692         if (!allocate_print_jobid(pdb, snum, printername, &jobid))
1693                 goto fail;
1694
1695         /* create the database entry */
1696         
1697         ZERO_STRUCT(pjob);
1698         
1699         pjob.pid = local_pid;
1700         pjob.sysjob = -1;
1701         pjob.fd = -1;
1702         pjob.starttime = time(NULL);
1703         pjob.status = LPQ_SPOOLING;
1704         pjob.size = 0;
1705         pjob.spooled = False;
1706         pjob.smbjob = True;
1707         pjob.nt_devmode = nt_devmode;
1708         
1709         fstrcpy(pjob.jobname, jobname);
1710
1711         if ((vuser = get_valid_user_struct(user->vuid)) != NULL) {
1712                 fstrcpy(pjob.user, vuser->user.smb_name);
1713         } else {
1714                 fstrcpy(pjob.user, uidtoname(user->uid));
1715         }
1716
1717         fstrcpy(pjob.queuename, lp_const_servicename(snum));
1718
1719         /* we have a job entry - now create the spool file */
1720         slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX", 
1721                  path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
1722         pjob.fd = smb_mkstemp(pjob.filename);
1723
1724         if (pjob.fd == -1) {
1725                 if (errno == EACCES) {
1726                         /* Common setup error, force a report. */
1727                         DEBUG(0, ("print_job_start: insufficient permissions \
1728 to open spool file %s.\n", pjob.filename));
1729                 } else {
1730                         /* Normal case, report at level 3 and above. */
1731                         DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
1732                         DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
1733                 }
1734                 goto fail;
1735         }
1736
1737         pjob_store(snum, jobid, &pjob);
1738
1739         /* Ensure we keep a rough count of the number of total jobs... */
1740         tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
1741
1742         release_print_db(pdb);
1743
1744         return jobid;
1745
1746  fail:
1747         if (jobid != -1)
1748                 pjob_delete(snum, jobid);
1749
1750         release_print_db(pdb);
1751
1752         DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
1753         return (uint32)-1;
1754 }
1755
1756 /****************************************************************************
1757  Update the number of pages spooled to jobid
1758 ****************************************************************************/
1759
1760 void print_job_endpage(int snum, uint32 jobid)
1761 {
1762         struct printjob *pjob = print_job_find(snum, jobid);
1763         if (!pjob)
1764                 return;
1765         /* don't allow another process to get this info - it is meaningless */
1766         if (pjob->pid != local_pid)
1767                 return;
1768
1769         pjob->page_count++;
1770         pjob_store(snum, jobid, pjob);
1771 }
1772
1773 /****************************************************************************
1774  Print a file - called on closing the file. This spools the job.
1775  If normal close is false then we're tearing down the jobs - treat as an
1776  error.
1777 ****************************************************************************/
1778
1779 BOOL print_job_end(int snum, uint32 jobid, BOOL normal_close)
1780 {
1781         struct printjob *pjob = print_job_find(snum, jobid);
1782         int ret;
1783         SMB_STRUCT_STAT sbuf;
1784
1785         if (!pjob)
1786                 return False;
1787
1788         if (pjob->spooled || pjob->pid != local_pid)
1789                 return False;
1790
1791         if (normal_close && (sys_fstat(pjob->fd, &sbuf) == 0)) {
1792                 pjob->size = sbuf.st_size;
1793                 close(pjob->fd);
1794                 pjob->fd = -1;
1795         } else {
1796
1797                 /* 
1798                  * Not a normal close or we couldn't stat the job file,
1799                  * so something has gone wrong. Cleanup.
1800                  */
1801                 close(pjob->fd);
1802                 pjob->fd = -1;
1803                 DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
1804                 goto fail;
1805         }
1806
1807         /* Technically, this is not quite right. If the printer has a separator
1808          * page turned on, the NT spooler prints the separator page even if the
1809          * print job is 0 bytes. 010215 JRR */
1810         if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
1811                 /* don't bother spooling empty files or something being deleted. */
1812                 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
1813                         pjob->filename, pjob->size ? "deleted" : "zero length" ));
1814                 unlink(pjob->filename);
1815                 pjob_delete(snum, jobid);
1816                 return True;
1817         }
1818
1819         ret = (*(current_printif->job_submit))(snum, pjob);
1820
1821         if (ret)
1822                 goto fail;
1823
1824         /* The print job has been sucessfully handed over to the back-end */
1825         
1826         pjob->spooled = True;
1827         pjob->status = LPQ_QUEUED;
1828         pjob_store(snum, jobid, pjob);
1829         
1830         /* make sure the database is up to date */
1831         if (print_cache_expired(snum))
1832                 print_queue_update(snum);
1833         
1834         return True;
1835
1836 fail:
1837
1838         /* The print job was not succesfully started. Cleanup */
1839         /* Still need to add proper error return propagation! 010122:JRR */
1840         unlink(pjob->filename);
1841         pjob_delete(snum, jobid);
1842         return False;
1843 }
1844
1845 /****************************************************************************
1846  Utility fn to enumerate the print queue.
1847 ****************************************************************************/
1848
1849 static int traverse_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1850 {
1851         struct traverse_struct *ts = (struct traverse_struct *)state;
1852         struct printjob pjob;
1853         int i;
1854         uint32 jobid;
1855
1856         /* sanity checks */
1857         
1858         if ( key.dsize != sizeof(jobid) )
1859                 return 0;
1860                 
1861         memcpy(&jobid, key.dptr, sizeof(jobid));
1862         
1863         if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
1864                 return 0;
1865         free_nt_devicemode( &pjob.nt_devmode );
1866
1867         /* maybe it isn't for this queue */
1868         if (ts->snum != lp_servicenumber(pjob.queuename))
1869                 return 0;
1870
1871         if (ts->qcount >= ts->maxcount)
1872                 return 0;
1873
1874         i = ts->qcount;
1875
1876         ts->queue[i].job = jobid;
1877         ts->queue[i].size = pjob.size;
1878         ts->queue[i].page_count = pjob.page_count;
1879         ts->queue[i].status = pjob.status;
1880         ts->queue[i].priority = 1;
1881         ts->queue[i].time = pjob.starttime;
1882         fstrcpy(ts->queue[i].fs_user, pjob.user);
1883         fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1884
1885         ts->qcount++;
1886
1887         return 0;
1888 }
1889
1890 struct traverse_count_struct {
1891         int snum, count;
1892 };
1893
1894 /****************************************************************************
1895  Utility fn to count the number of entries in the print queue.
1896 ****************************************************************************/
1897
1898 static int traverse_count_fn_queue(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
1899 {
1900         struct traverse_count_struct *ts = (struct traverse_count_struct *)state;
1901         struct printjob pjob;
1902         uint32 jobid;
1903
1904         /* sanity checks */
1905         
1906         if (  key.dsize != sizeof(jobid) )
1907                 return 0;
1908                 
1909         memcpy(&jobid, key.dptr, sizeof(jobid));
1910         
1911         if ( unpack_pjob( data.dptr, data.dsize, &pjob ) == -1 )
1912                 return 0;
1913                 
1914         free_nt_devicemode( &pjob.nt_devmode );
1915
1916         /* maybe it isn't for this queue - this cannot happen with the tdb/printer code. JRA */
1917         if (ts->snum != lp_servicenumber(pjob.queuename))
1918                 return 0;
1919
1920         ts->count++;
1921
1922         return 0;
1923 }
1924
1925 /****************************************************************************
1926  Sort print jobs by submittal time.
1927 ****************************************************************************/
1928
1929 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1930 {
1931         /* Silly cases */
1932
1933         if (!j1 && !j2)
1934                 return 0;
1935         if (!j1)
1936                 return -1;
1937         if (!j2)
1938                 return 1;
1939
1940         /* Sort on job start time */
1941
1942         if (j1->time == j2->time)
1943                 return 0;
1944         return (j1->time > j2->time) ? 1 : -1;
1945 }
1946
1947 /****************************************************************************
1948  Get a printer queue listing.
1949  set queue = NULL and status = NULL if you just want to update the cache
1950 ****************************************************************************/
1951
1952 int print_queue_status(int snum, 
1953                        print_queue_struct **queue,
1954                        print_status_struct *status)
1955 {
1956         struct traverse_struct tstruct;
1957         struct traverse_count_struct tsc;
1958         fstring keystr;
1959         TDB_DATA data, key;
1960         const char *printername;
1961         struct tdb_print_db *pdb;
1962
1963         /* make sure the database is up to date */
1964
1965         if (print_cache_expired(snum))
1966                 print_queue_update(snum);
1967
1968         /* return if we are done */
1969
1970         if ( !queue || !status )
1971                 return 0;
1972
1973         *queue = NULL;
1974         printername = lp_const_servicename(snum);
1975         pdb = get_print_db_byname(printername);
1976
1977         if (!pdb)
1978                 return 0;
1979
1980         /*
1981          * Fetch the queue status.  We must do this first, as there may
1982          * be no jobs in the queue.
1983          */
1984         ZERO_STRUCTP(status);
1985         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", printername);
1986         key.dptr = keystr;
1987         key.dsize = strlen(keystr);
1988         data = tdb_fetch(pdb->tdb, key);
1989         if (data.dptr) {
1990                 if (data.dsize == sizeof(*status)) {
1991                         memcpy(status, data.dptr, sizeof(*status));
1992                 }
1993                 SAFE_FREE(data.dptr);
1994         }
1995
1996         /*
1997          * Now, fetch the print queue information.  We first count the number
1998          * of entries, and then only retrieve the queue if necessary.
1999          */
2000         tsc.count = 0;
2001         tsc.snum = snum;
2002         
2003         tdb_traverse(pdb->tdb, traverse_count_fn_queue, (void *)&tsc);
2004
2005         if (tsc.count == 0) {
2006                 release_print_db(pdb);
2007                 return 0;
2008         }
2009
2010         /* Allocate the queue size. */
2011         if ((tstruct.queue = (print_queue_struct *)
2012              malloc(sizeof(print_queue_struct)*tsc.count)) == NULL) {
2013                 release_print_db(pdb);
2014                 return 0;
2015         }
2016
2017         /*
2018          * Fill in the queue.
2019          * We need maxcount as the queue size may have changed between
2020          * the two calls to tdb_traverse.
2021          */
2022         tstruct.qcount = 0;
2023         tstruct.maxcount = tsc.count;
2024         tstruct.snum = snum;
2025
2026         tdb_traverse(pdb->tdb, traverse_fn_queue, (void *)&tstruct);
2027         release_print_db(pdb);
2028
2029         /* Sort the queue by submission time otherwise they are displayed
2030            in hash order. */
2031
2032         qsort(tstruct.queue, tstruct.qcount, sizeof(print_queue_struct),
2033               QSORT_CAST(printjob_comp));
2034
2035         *queue = tstruct.queue;
2036         return tstruct.qcount;
2037 }
2038
2039 /****************************************************************************
2040  Pause a queue.
2041 ****************************************************************************/
2042
2043 BOOL print_queue_pause(struct current_user *user, int snum, WERROR *errcode)
2044 {
2045         int ret;
2046         
2047         if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
2048                 *errcode = WERR_ACCESS_DENIED;
2049                 return False;
2050         }
2051
2052         ret = (*(current_printif->queue_pause))(snum);
2053
2054         if (ret != 0) {
2055                 *errcode = WERR_INVALID_PARAM;
2056                 return False;
2057         }
2058
2059         /* force update the database */
2060         print_cache_flush(snum);
2061
2062         /* Send a printer notify message */
2063
2064         notify_printer_status(snum, PRINTER_STATUS_PAUSED);
2065
2066         return True;
2067 }
2068
2069 /****************************************************************************
2070  Resume a queue.
2071 ****************************************************************************/
2072
2073 BOOL print_queue_resume(struct current_user *user, int snum, WERROR *errcode)
2074 {
2075         int ret;
2076
2077         if (!print_access_check(user, snum, PRINTER_ACCESS_ADMINISTER)) {
2078                 *errcode = WERR_ACCESS_DENIED;
2079                 return False;
2080         }
2081
2082         ret = (*(current_printif->queue_resume))(snum);
2083
2084         if (ret != 0) {
2085                 *errcode = WERR_INVALID_PARAM;
2086                 return False;
2087         }
2088
2089         /* make sure the database is up to date */
2090         if (print_cache_expired(snum))
2091                 print_queue_update(snum);
2092
2093         /* Send a printer notify message */
2094
2095         notify_printer_status(snum, PRINTER_STATUS_OK);
2096
2097         return True;
2098 }
2099
2100 /****************************************************************************
2101  Purge a queue - implemented by deleting all jobs that we can delete.
2102 ****************************************************************************/
2103
2104 BOOL print_queue_purge(struct current_user *user, int snum, WERROR *errcode)
2105 {
2106         print_queue_struct *queue;
2107         print_status_struct status;
2108         int njobs, i;
2109         BOOL can_job_admin;
2110
2111         /* Force and update so the count is accurate (i.e. not a cached count) */
2112         print_queue_update(snum);
2113         
2114         can_job_admin = print_access_check(user, snum, JOB_ACCESS_ADMINISTER);
2115         njobs = print_queue_status(snum, &queue, &status);
2116
2117         for (i=0;i<njobs;i++) {
2118                 BOOL owner = is_owner(user, snum, queue[i].job);
2119
2120                 if (owner || can_job_admin) {
2121                         print_job_delete1(snum, queue[i].job);
2122                 }
2123         }
2124
2125         SAFE_FREE(queue);
2126
2127         return True;
2128 }