c300c8be7b9692d71321b80301df1ecafe76e860
[ddiss/samba.git] / source3 / 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 3 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, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "system/syslog.h"
24 #include "system/filesys.h"
25 #include "printing.h"
26 #include "../librpc/gen_ndr/ndr_spoolss.h"
27 #include "nt_printing.h"
28 #include "../librpc/gen_ndr/netlogon.h"
29 #include "printing/notify.h"
30 #include "printing/pcap.h"
31 #include "serverid.h"
32 #include "smbd/smbd.h"
33 #include "auth.h"
34 #include "messages.h"
35 #include "util_tdb.h"
36
37 extern struct current_user current_user;
38 extern userdom_struct current_user_info;
39
40 /* Current printer interface */
41 static bool remove_from_jobs_added(const char* sharename, uint32 jobid);
42
43 /*
44    the printing backend revolves around a tdb database that stores the
45    SMB view of the print queue
46
47    The key for this database is a jobid - a internally generated number that
48    uniquely identifies a print job
49
50    reading the print queue involves two steps:
51      - possibly running lpq and updating the internal database from that
52      - reading entries from the database
53
54    jobids are assigned when a job starts spooling.
55 */
56
57 static TDB_CONTEXT *rap_tdb;
58 static uint16 next_rap_jobid;
59 struct rap_jobid_key {
60         fstring sharename;
61         uint32  jobid;
62 };
63
64 /***************************************************************************
65  Nightmare. LANMAN jobid's are 16 bit numbers..... We must map them to 32
66  bit RPC jobids.... JRA.
67 ***************************************************************************/
68
69 uint16 pjobid_to_rap(const char* sharename, uint32 jobid)
70 {
71         uint16 rap_jobid;
72         TDB_DATA data, key;
73         struct rap_jobid_key jinfo;
74         uint8 buf[2];
75
76         DEBUG(10,("pjobid_to_rap: called.\n"));
77
78         if (!rap_tdb) {
79                 /* Create the in-memory tdb. */
80                 rap_tdb = tdb_open_log(NULL, 0, TDB_INTERNAL, (O_RDWR|O_CREAT), 0644);
81                 if (!rap_tdb)
82                         return 0;
83         }
84
85         ZERO_STRUCT( jinfo );
86         fstrcpy( jinfo.sharename, sharename );
87         jinfo.jobid = jobid;
88         key.dptr = (uint8 *)&jinfo;
89         key.dsize = sizeof(jinfo);
90
91         data = tdb_fetch(rap_tdb, key);
92         if (data.dptr && data.dsize == sizeof(uint16)) {
93                 rap_jobid = SVAL(data.dptr, 0);
94                 SAFE_FREE(data.dptr);
95                 DEBUG(10,("pjobid_to_rap: jobid %u maps to RAP jobid %u\n",
96                         (unsigned int)jobid, (unsigned int)rap_jobid));
97                 return rap_jobid;
98         }
99         SAFE_FREE(data.dptr);
100         /* Not found - create and store mapping. */
101         rap_jobid = ++next_rap_jobid;
102         if (rap_jobid == 0)
103                 rap_jobid = ++next_rap_jobid;
104         SSVAL(buf,0,rap_jobid);
105         data.dptr = buf;
106         data.dsize = sizeof(rap_jobid);
107         tdb_store(rap_tdb, key, data, TDB_REPLACE);
108         tdb_store(rap_tdb, data, key, TDB_REPLACE);
109
110         DEBUG(10,("pjobid_to_rap: created jobid %u maps to RAP jobid %u\n",
111                 (unsigned int)jobid, (unsigned int)rap_jobid));
112         return rap_jobid;
113 }
114
115 bool rap_to_pjobid(uint16 rap_jobid, fstring sharename, uint32 *pjobid)
116 {
117         TDB_DATA data, key;
118         uint8 buf[2];
119
120         DEBUG(10,("rap_to_pjobid called.\n"));
121
122         if (!rap_tdb)
123                 return False;
124
125         SSVAL(buf,0,rap_jobid);
126         key.dptr = buf;
127         key.dsize = sizeof(rap_jobid);
128         data = tdb_fetch(rap_tdb, key);
129         if ( data.dptr && data.dsize == sizeof(struct rap_jobid_key) )
130         {
131                 struct rap_jobid_key *jinfo = (struct rap_jobid_key*)data.dptr;
132                 if (sharename != NULL) {
133                         fstrcpy( sharename, jinfo->sharename );
134                 }
135                 *pjobid = jinfo->jobid;
136                 DEBUG(10,("rap_to_pjobid: jobid %u maps to RAP jobid %u\n",
137                         (unsigned int)*pjobid, (unsigned int)rap_jobid));
138                 SAFE_FREE(data.dptr);
139                 return True;
140         }
141
142         DEBUG(10,("rap_to_pjobid: Failed to lookup RAP jobid %u\n",
143                 (unsigned int)rap_jobid));
144         SAFE_FREE(data.dptr);
145         return False;
146 }
147
148 void rap_jobid_delete(const char* sharename, uint32 jobid)
149 {
150         TDB_DATA key, data;
151         uint16 rap_jobid;
152         struct rap_jobid_key jinfo;
153         uint8 buf[2];
154
155         DEBUG(10,("rap_jobid_delete: called.\n"));
156
157         if (!rap_tdb)
158                 return;
159
160         ZERO_STRUCT( jinfo );
161         fstrcpy( jinfo.sharename, sharename );
162         jinfo.jobid = jobid;
163         key.dptr = (uint8 *)&jinfo;
164         key.dsize = sizeof(jinfo);
165
166         data = tdb_fetch(rap_tdb, key);
167         if (!data.dptr || (data.dsize != sizeof(uint16))) {
168                 DEBUG(10,("rap_jobid_delete: cannot find jobid %u\n",
169                         (unsigned int)jobid ));
170                 SAFE_FREE(data.dptr);
171                 return;
172         }
173
174         DEBUG(10,("rap_jobid_delete: deleting jobid %u\n",
175                 (unsigned int)jobid ));
176
177         rap_jobid = SVAL(data.dptr, 0);
178         SAFE_FREE(data.dptr);
179         SSVAL(buf,0,rap_jobid);
180         data.dptr = buf;
181         data.dsize = sizeof(rap_jobid);
182         tdb_delete(rap_tdb, key);
183         tdb_delete(rap_tdb, data);
184 }
185
186 static int get_queue_status(const char* sharename, print_status_struct *);
187
188 /****************************************************************************
189  Initialise the printing backend. Called once at startup before the fork().
190 ****************************************************************************/
191
192 bool print_backend_init(struct messaging_context *msg_ctx)
193 {
194         const char *sversion = "INFO/version";
195         int services = lp_numservices();
196         int snum;
197
198         unlink(cache_path("printing.tdb"));
199         mkdir(cache_path("printing"),0755);
200
201         /* handle a Samba upgrade */
202
203         for (snum = 0; snum < services; snum++) {
204                 struct tdb_print_db *pdb;
205                 if (!lp_print_ok(snum))
206                         continue;
207
208                 pdb = get_print_db_byname(lp_const_servicename(snum));
209                 if (!pdb)
210                         continue;
211                 if (tdb_lock_bystring(pdb->tdb, sversion) == -1) {
212                         DEBUG(0,("print_backend_init: Failed to open printer %s database\n", lp_const_servicename(snum) ));
213                         release_print_db(pdb);
214                         return False;
215                 }
216                 if (tdb_fetch_int32(pdb->tdb, sversion) != PRINT_DATABASE_VERSION) {
217                         tdb_wipe_all(pdb->tdb);
218                         tdb_store_int32(pdb->tdb, sversion, PRINT_DATABASE_VERSION);
219                 }
220                 tdb_unlock_bystring(pdb->tdb, sversion);
221                 release_print_db(pdb);
222         }
223
224         close_all_print_db(); /* Don't leave any open. */
225
226         /* do NT print initialization... */
227         return nt_printing_init(msg_ctx);
228 }
229
230 /****************************************************************************
231  Shut down printing backend. Called once at shutdown to close the tdb.
232 ****************************************************************************/
233
234 void printing_end(void)
235 {
236         close_all_print_db(); /* Don't leave any open. */
237 }
238
239 /****************************************************************************
240  Retrieve the set of printing functions for a given service.  This allows
241  us to set the printer function table based on the value of the 'printing'
242  service parameter.
243
244  Use the generic interface as the default and only use cups interface only
245  when asked for (and only when supported)
246 ****************************************************************************/
247
248 static struct printif *get_printer_fns_from_type( enum printing_types type )
249 {
250         struct printif *printer_fns = &generic_printif;
251
252 #ifdef HAVE_CUPS
253         if ( type == PRINT_CUPS ) {
254                 printer_fns = &cups_printif;
255         }
256 #endif /* HAVE_CUPS */
257
258 #ifdef HAVE_IPRINT
259         if ( type == PRINT_IPRINT ) {
260                 printer_fns = &iprint_printif;
261         }
262 #endif /* HAVE_IPRINT */
263
264         printer_fns->type = type;
265
266         return printer_fns;
267 }
268
269 static struct printif *get_printer_fns( int snum )
270 {
271         return get_printer_fns_from_type( (enum printing_types)lp_printing(snum) );
272 }
273
274
275 /****************************************************************************
276  Useful function to generate a tdb key.
277 ****************************************************************************/
278
279 static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
280 {
281         TDB_DATA ret;
282
283         SIVAL(tmp, 0, jobid);
284         ret.dptr = (uint8 *)tmp;
285         ret.dsize = sizeof(*tmp);
286         return ret;
287 }
288
289 /****************************************************************************
290  Pack the devicemode to store it in a tdb.
291 ****************************************************************************/
292 static int pack_devicemode(struct spoolss_DeviceMode *devmode, uint8 *buf, int buflen)
293 {
294         enum ndr_err_code ndr_err;
295         DATA_BLOB blob;
296         int len = 0;
297
298         if (devmode) {
299                 ndr_err = ndr_push_struct_blob(&blob, talloc_tos(),
300                                                devmode,
301                                                (ndr_push_flags_fn_t)
302                                                ndr_push_spoolss_DeviceMode);
303                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
304                         DEBUG(10, ("pack_devicemode: "
305                                    "error encoding spoolss_DeviceMode\n"));
306                         goto done;
307                 }
308         } else {
309                 ZERO_STRUCT(blob);
310         }
311
312         len = tdb_pack(buf, buflen, "B", blob.length, blob.data);
313
314         if (devmode) {
315                 DEBUG(8, ("Packed devicemode [%s]\n", devmode->formname));
316         }
317
318 done:
319         return len;
320 }
321
322 /****************************************************************************
323  Unpack the devicemode to store it in a tdb.
324 ****************************************************************************/
325 static int unpack_devicemode(TALLOC_CTX *mem_ctx,
326                       const uint8 *buf, int buflen,
327                       struct spoolss_DeviceMode **devmode)
328 {
329         struct spoolss_DeviceMode *dm;
330         enum ndr_err_code ndr_err;
331         char *data = NULL;
332         int data_len = 0;
333         DATA_BLOB blob;
334         int len = 0;
335
336         *devmode = NULL;
337
338         len = tdb_unpack(buf, buflen, "B", &data_len, &data);
339         if (!data) {
340                 return len;
341         }
342
343         dm = talloc_zero(mem_ctx, struct spoolss_DeviceMode);
344         if (!dm) {
345                 goto done;
346         }
347
348         blob = data_blob_const(data, data_len);
349
350         ndr_err = ndr_pull_struct_blob(&blob, dm, dm,
351                         (ndr_pull_flags_fn_t)ndr_pull_spoolss_DeviceMode);
352         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
353                 DEBUG(10, ("unpack_devicemode: "
354                            "error parsing spoolss_DeviceMode\n"));
355                 goto done;
356         }
357
358         DEBUG(8, ("Unpacked devicemode [%s](%s)\n",
359                   dm->devicename, dm->formname));
360         if (dm->driverextra_data.data) {
361                 DEBUG(8, ("with a private section of %d bytes\n",
362                           dm->__driverextra_length));
363         }
364
365         *devmode = dm;
366
367 done:
368         SAFE_FREE(data);
369         return len;
370 }
371
372 /***********************************************************************
373  unpack a pjob from a tdb buffer
374 ***********************************************************************/
375
376 /* FIXME talloc ctx */
377 static int unpack_pjob(uint8 *buf, int buflen, struct printjob *pjob)
378 {
379         int     len = 0;
380         int     used;
381         uint32 pjpid, pjjobid, pjsysjob, pjfd, pjstarttime, pjstatus;
382         uint32 pjsize, pjpage_count, pjspooled, pjsmbjob;
383
384         if (!buf || !pjob) {
385                 return -1;
386         }
387
388         len += tdb_unpack(buf+len, buflen-len, "ddddddddddfffff",
389                                 &pjpid,
390                                 &pjjobid,
391                                 &pjsysjob,
392                                 &pjfd,
393                                 &pjstarttime,
394                                 &pjstatus,
395                                 &pjsize,
396                                 &pjpage_count,
397                                 &pjspooled,
398                                 &pjsmbjob,
399                                 pjob->filename,
400                                 pjob->jobname,
401                                 pjob->user,
402                                 pjob->clientmachine,
403                                 pjob->queuename);
404
405         if (len == -1) {
406                 return -1;
407         }
408
409         used = unpack_devicemode(NULL, buf+len, buflen-len, &pjob->devmode);
410         if (used == -1) {
411                 return -1;
412         }
413
414         len += used;
415
416         pjob->pid = pjpid;
417         pjob->jobid = pjjobid;
418         pjob->sysjob = pjsysjob;
419         pjob->fd = pjfd;
420         pjob->starttime = pjstarttime;
421         pjob->status = pjstatus;
422         pjob->size = pjsize;
423         pjob->page_count = pjpage_count;
424         pjob->spooled = pjspooled;
425         pjob->smbjob = pjsmbjob;
426
427         return len;
428
429 }
430
431 /****************************************************************************
432  Useful function to find a print job in the database.
433 ****************************************************************************/
434
435 static struct printjob *print_job_find(TALLOC_CTX *mem_ctx,
436                                        const char *sharename,
437                                        uint32 jobid)
438 {
439         struct printjob         *pjob;
440         uint32_t tmp;
441         TDB_DATA                ret;
442         struct tdb_print_db     *pdb = get_print_db_byname(sharename);
443
444         DEBUG(10,("print_job_find: looking up job %u for share %s\n",
445                         (unsigned int)jobid, sharename ));
446
447         if (!pdb) {
448                 return NULL;
449         }
450
451         ret = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
452         release_print_db(pdb);
453
454         if (!ret.dptr) {
455                 DEBUG(10, ("print_job_find: failed to find jobid %u.\n",
456                            jobid));
457                 return NULL;
458         }
459
460         pjob = talloc_zero(mem_ctx, struct printjob);
461         if (pjob == NULL) {
462                 goto err_out;
463         }
464
465         if (unpack_pjob(ret.dptr, ret.dsize, pjob) == -1) {
466                 DEBUG(10, ("failed to unpack jobid %u.\n", jobid));
467                 talloc_free(pjob);
468                 pjob = NULL;
469                 goto err_out;
470         }
471
472         DEBUG(10,("print_job_find: returning system job %d for jobid %u.\n",
473                   pjob->sysjob, jobid));
474         SMB_ASSERT(pjob->jobid == jobid);
475
476 err_out:
477         SAFE_FREE(ret.dptr);
478         return pjob;
479 }
480
481 /* Convert a unix jobid to a smb jobid */
482
483 struct unixjob_traverse_state {
484         int sysjob;
485         uint32 sysjob_to_jobid_value;
486 };
487
488 static int unixjob_traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key,
489                                TDB_DATA data, void *private_data)
490 {
491         struct printjob *pjob;
492         struct unixjob_traverse_state *state =
493                 (struct unixjob_traverse_state *)private_data;
494
495         if (!data.dptr || data.dsize == 0)
496                 return 0;
497
498         pjob = (struct printjob *)data.dptr;
499         if (key.dsize != sizeof(uint32))
500                 return 0;
501
502         if (state->sysjob == pjob->sysjob) {
503                 state->sysjob_to_jobid_value = pjob->jobid;
504                 return 1;
505         }
506
507         return 0;
508 }
509
510 static uint32 sysjob_to_jobid_pdb(struct tdb_print_db *pdb, int sysjob)
511 {
512         struct unixjob_traverse_state state;
513
514         state.sysjob = sysjob;
515         state.sysjob_to_jobid_value = (uint32)-1;
516
517         tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
518
519         return state.sysjob_to_jobid_value;
520 }
521
522 /****************************************************************************
523  This is a *horribly expensive call as we have to iterate through all the
524  current printer tdb's. Don't do this often ! JRA.
525 ****************************************************************************/
526
527 uint32 sysjob_to_jobid(int unix_jobid)
528 {
529         int services = lp_numservices();
530         int snum;
531         struct unixjob_traverse_state state;
532
533         state.sysjob = unix_jobid;
534         state.sysjob_to_jobid_value = (uint32)-1;
535
536         for (snum = 0; snum < services; snum++) {
537                 struct tdb_print_db *pdb;
538                 if (!lp_print_ok(snum))
539                         continue;
540                 pdb = get_print_db_byname(lp_const_servicename(snum));
541                 if (!pdb) {
542                         continue;
543                 }
544                 tdb_traverse(pdb->tdb, unixjob_traverse_fn, &state);
545                 release_print_db(pdb);
546                 if (state.sysjob_to_jobid_value != (uint32)-1)
547                         return state.sysjob_to_jobid_value;
548         }
549         return (uint32)-1;
550 }
551
552 /****************************************************************************
553  Send notifications based on what has changed after a pjob_store.
554 ****************************************************************************/
555
556 static const struct {
557         uint32_t lpq_status;
558         uint32_t spoolss_status;
559 } lpq_to_spoolss_status_map[] = {
560         { LPQ_QUEUED, JOB_STATUS_QUEUED },
561         { LPQ_PAUSED, JOB_STATUS_PAUSED },
562         { LPQ_SPOOLING, JOB_STATUS_SPOOLING },
563         { LPQ_PRINTING, JOB_STATUS_PRINTING },
564         { LPQ_DELETING, JOB_STATUS_DELETING },
565         { LPQ_OFFLINE, JOB_STATUS_OFFLINE },
566         { LPQ_PAPEROUT, JOB_STATUS_PAPEROUT },
567         { LPQ_PRINTED, JOB_STATUS_PRINTED },
568         { LPQ_DELETED, JOB_STATUS_DELETED },
569         { LPQ_BLOCKED, JOB_STATUS_BLOCKED_DEVQ },
570         { LPQ_USER_INTERVENTION, JOB_STATUS_USER_INTERVENTION },
571         { (uint32_t)-1, 0 }
572 };
573
574 /* Convert a lpq status value stored in printing.tdb into the
575    appropriate win32 API constant. */
576
577 static uint32 map_to_spoolss_status(uint32 lpq_status)
578 {
579         int i = 0;
580
581         while (lpq_to_spoolss_status_map[i].lpq_status != -1) {
582                 if (lpq_to_spoolss_status_map[i].lpq_status == lpq_status)
583                         return lpq_to_spoolss_status_map[i].spoolss_status;
584                 i++;
585         }
586
587         return 0;
588 }
589
590 /***************************************************************************
591  Append a jobid to the 'jobs changed' list.
592 ***************************************************************************/
593
594 static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32_t jobid)
595 {
596         TDB_DATA data;
597         uint32_t store_jobid;
598
599         SIVAL(&store_jobid, 0, jobid);
600         data.dptr = (uint8 *) &store_jobid;
601         data.dsize = 4;
602
603         DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
604
605         return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_changed"),
606                            data) == 0);
607 }
608
609 /***************************************************************************
610  Remove a jobid from the 'jobs changed' list.
611 ***************************************************************************/
612
613 static bool remove_from_jobs_changed(const char* sharename, uint32_t jobid)
614 {
615         struct tdb_print_db *pdb = get_print_db_byname(sharename);
616         TDB_DATA data, key;
617         size_t job_count, i;
618         bool ret = False;
619         bool gotlock = False;
620
621         if (!pdb) {
622                 return False;
623         }
624
625         ZERO_STRUCT(data);
626
627         key = string_tdb_data("INFO/jobs_changed");
628
629         if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
630                 goto out;
631
632         gotlock = True;
633
634         data = tdb_fetch(pdb->tdb, key);
635
636         if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
637                 goto out;
638
639         job_count = data.dsize / 4;
640         for (i = 0; i < job_count; i++) {
641                 uint32 ch_jobid;
642
643                 ch_jobid = IVAL(data.dptr, i*4);
644                 if (ch_jobid == jobid) {
645                         if (i < job_count -1 )
646                                 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
647                         data.dsize -= 4;
648                         if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
649                                 goto out;
650                         break;
651                 }
652         }
653
654         ret = True;
655   out:
656
657         if (gotlock)
658                 tdb_chainunlock(pdb->tdb, key);
659         SAFE_FREE(data.dptr);
660         release_print_db(pdb);
661         if (ret)
662                 DEBUG(10,("remove_from_jobs_changed: removed jobid %u\n", (unsigned int)jobid ));
663         else
664                 DEBUG(10,("remove_from_jobs_changed: Failed to remove jobid %u\n", (unsigned int)jobid ));
665         return ret;
666 }
667
668 static void pjob_store_notify(struct tevent_context *ev,
669                               struct messaging_context *msg_ctx,
670                               const char* sharename, uint32 jobid,
671                               struct printjob *old_data,
672                               struct printjob *new_data,
673                               bool *pchanged)
674 {
675         bool new_job = false;
676         bool changed = false;
677
678         if (old_data == NULL) {
679                 new_job = true;
680         }
681
682         /* ACHTUNG!  Due to a bug in Samba's spoolss parsing of the
683            NOTIFY_INFO_DATA buffer, we *have* to send the job submission
684            time first or else we'll end up with potential alignment
685            errors.  I don't think the systemtime should be spooled as
686            a string, but this gets us around that error.
687            --jerry (i'll feel dirty for this) */
688
689         if (new_job) {
690                 notify_job_submitted(ev, msg_ctx,
691                                      sharename, jobid, new_data->starttime);
692                 notify_job_username(ev, msg_ctx,
693                                     sharename, jobid, new_data->user);
694                 notify_job_name(ev, msg_ctx,
695                                 sharename, jobid, new_data->jobname);
696                 notify_job_status(ev, msg_ctx,
697                                   sharename, jobid, map_to_spoolss_status(new_data->status));
698                 notify_job_total_bytes(ev, msg_ctx,
699                                        sharename, jobid, new_data->size);
700                 notify_job_total_pages(ev, msg_ctx,
701                                        sharename, jobid, new_data->page_count);
702         } else {
703                 if (!strequal(old_data->jobname, new_data->jobname)) {
704                         notify_job_name(ev, msg_ctx, sharename,
705                                         jobid, new_data->jobname);
706                         changed = true;
707                 }
708
709                 if (old_data->status != new_data->status) {
710                         notify_job_status(ev, msg_ctx,
711                                           sharename, jobid,
712                                           map_to_spoolss_status(new_data->status));
713                 }
714
715                 if (old_data->size != new_data->size) {
716                         notify_job_total_bytes(ev, msg_ctx,
717                                                sharename, jobid, new_data->size);
718                 }
719
720                 if (old_data->page_count != new_data->page_count) {
721                         notify_job_total_pages(ev, msg_ctx,
722                                                sharename, jobid,
723                                                new_data->page_count);
724                 }
725         }
726
727         *pchanged = changed;
728 }
729
730 /****************************************************************************
731  Store a job structure back to the database.
732 ****************************************************************************/
733
734 static bool pjob_store(struct tevent_context *ev,
735                        struct messaging_context *msg_ctx,
736                        const char* sharename, uint32 jobid,
737                        struct printjob *pjob)
738 {
739         uint32_t tmp;
740         TDB_DATA                old_data, new_data;
741         bool                    ret = False;
742         struct tdb_print_db     *pdb = get_print_db_byname(sharename);
743         uint8                   *buf = NULL;
744         int                     len, newlen, buflen;
745
746
747         if (!pdb)
748                 return False;
749
750         /* Get old data */
751
752         old_data = tdb_fetch(pdb->tdb, print_key(jobid, &tmp));
753
754         /* Doh!  Now we have to pack/unpack data since the NT_DEVICEMODE was added */
755
756         newlen = 0;
757
758         do {
759                 len = 0;
760                 buflen = newlen;
761                 len += tdb_pack(buf+len, buflen-len, "ddddddddddfffff",
762                                 (uint32)pjob->pid,
763                                 (uint32)pjob->jobid,
764                                 (uint32)pjob->sysjob,
765                                 (uint32)pjob->fd,
766                                 (uint32)pjob->starttime,
767                                 (uint32)pjob->status,
768                                 (uint32)pjob->size,
769                                 (uint32)pjob->page_count,
770                                 (uint32)pjob->spooled,
771                                 (uint32)pjob->smbjob,
772                                 pjob->filename,
773                                 pjob->jobname,
774                                 pjob->user,
775                                 pjob->clientmachine,
776                                 pjob->queuename);
777
778                 len += pack_devicemode(pjob->devmode, buf+len, buflen-len);
779
780                 if (buflen != len) {
781                         buf = (uint8 *)SMB_REALLOC(buf, len);
782                         if (!buf) {
783                                 DEBUG(0,("pjob_store: failed to enlarge buffer!\n"));
784                                 goto done;
785                         }
786                         newlen = len;
787                 }
788         } while ( buflen != len );
789
790
791         /* Store new data */
792
793         new_data.dptr = buf;
794         new_data.dsize = len;
795         ret = (tdb_store(pdb->tdb, print_key(jobid, &tmp), new_data,
796                          TDB_REPLACE) == 0);
797
798         /* Send notify updates for what has changed */
799
800         if ( ret ) {
801                 bool changed = false;
802                 struct printjob old_pjob;
803
804                 if ( old_data.dsize )
805                 {
806                         if ( unpack_pjob( old_data.dptr, old_data.dsize, &old_pjob ) != -1 )
807                         {
808                                 pjob_store_notify(server_event_context(),
809                                                   msg_ctx,
810                                                   sharename, jobid, &old_pjob,
811                                                   pjob,
812                                                   &changed);
813                                 talloc_free(old_pjob.devmode);
814
815                                 if (changed) {
816                                         add_to_jobs_changed(pdb, jobid);
817                                 }
818                         }
819
820                 }
821                 else {
822                         /* new job */
823                         pjob_store_notify(server_event_context(), msg_ctx,
824                                           sharename, jobid, NULL, pjob,
825                                           &changed);
826                 }
827         }
828
829 done:
830         release_print_db(pdb);
831         SAFE_FREE( old_data.dptr );
832         SAFE_FREE( buf );
833
834         return ret;
835 }
836
837 /****************************************************************************
838  Remove a job structure from the database.
839 ****************************************************************************/
840
841 static void pjob_delete(struct tevent_context *ev,
842                         struct messaging_context *msg_ctx,
843                         const char* sharename, uint32 jobid)
844 {
845         uint32_t tmp;
846         struct printjob *pjob;
847         uint32 job_status = 0;
848         struct tdb_print_db *pdb;
849         TALLOC_CTX *tmp_ctx = talloc_new(ev);
850         if (tmp_ctx == NULL) {
851                 return;
852         }
853
854         pdb = get_print_db_byname(sharename);
855         if (!pdb) {
856                 goto err_out;
857         }
858
859         pjob = print_job_find(tmp_ctx, sharename, jobid);
860         if (!pjob) {
861                 DEBUG(5, ("we were asked to delete nonexistent job %u\n",
862                           jobid));
863                 goto err_release;
864         }
865
866         /* We must cycle through JOB_STATUS_DELETING and
867            JOB_STATUS_DELETED for the port monitor to delete the job
868            properly. */
869
870         job_status = JOB_STATUS_DELETING|JOB_STATUS_DELETED;
871         notify_job_status(ev, msg_ctx, sharename, jobid, job_status);
872
873         /* Remove from printing.tdb */
874
875         tdb_delete(pdb->tdb, print_key(jobid, &tmp));
876         remove_from_jobs_added(sharename, jobid);
877         rap_jobid_delete(sharename, jobid);
878 err_release:
879         release_print_db(pdb);
880 err_out:
881         talloc_free(tmp_ctx);
882 }
883
884 /****************************************************************************
885  List a unix job in the print database.
886 ****************************************************************************/
887
888 static void print_unix_job(struct tevent_context *ev,
889                            struct messaging_context *msg_ctx,
890                            const char *sharename, print_queue_struct *q,
891                            uint32 jobid)
892 {
893         struct printjob pj, *old_pj;
894         TALLOC_CTX *tmp_ctx = talloc_new(ev);
895         if (tmp_ctx == NULL) {
896                 return;
897         }
898
899         if (jobid == (uint32)-1) {
900                 jobid = q->sysjob + UNIX_JOB_START;
901         }
902
903         /* Preserve the timestamp on an existing unix print job */
904
905         old_pj = print_job_find(tmp_ctx, sharename, jobid);
906
907         ZERO_STRUCT(pj);
908
909         pj.pid = (pid_t)-1;
910         pj.jobid = jobid;
911         pj.sysjob = q->sysjob;
912         pj.fd = -1;
913         pj.starttime = old_pj ? old_pj->starttime : q->time;
914         pj.status = q->status;
915         pj.size = q->size;
916         pj.spooled = True;
917         fstrcpy(pj.filename, old_pj ? old_pj->filename : "");
918         if (jobid < UNIX_JOB_START) {
919                 pj.smbjob = True;
920                 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : "Remote Downlevel Document");
921         } else {
922                 pj.smbjob = False;
923                 fstrcpy(pj.jobname, old_pj ? old_pj->jobname : q->fs_file);
924         }
925         fstrcpy(pj.user, old_pj ? old_pj->user : q->fs_user);
926         fstrcpy(pj.queuename, old_pj ? old_pj->queuename : sharename );
927
928         pjob_store(ev, msg_ctx, sharename, jobid, &pj);
929         talloc_free(tmp_ctx);
930 }
931
932
933 struct traverse_struct {
934         print_queue_struct *queue;
935         int qcount, snum, maxcount, total_jobs;
936         const char *sharename;
937         time_t lpq_time;
938         const char *lprm_command;
939         struct printif *print_if;
940         struct tevent_context *ev;
941         struct messaging_context *msg_ctx;
942 };
943
944 /****************************************************************************
945  Utility fn to delete any jobs that are no longer active.
946 ****************************************************************************/
947
948 static int traverse_fn_delete(TDB_CONTEXT *t, TDB_DATA key, TDB_DATA data, void *state)
949 {
950         struct traverse_struct *ts = (struct traverse_struct *)state;
951         struct printjob pjob;
952         uint32 jobid;
953         int i = 0;
954
955         if (  key.dsize != sizeof(jobid) )
956                 return 0;
957
958         if (unpack_pjob(data.dptr, data.dsize, &pjob) == -1)
959                 return 0;
960         talloc_free(pjob.devmode);
961         jobid = pjob.jobid;
962
963         if (!pjob.smbjob) {
964                 /* remove a unix job if it isn't in the system queue any more */
965                 for (i=0;i<ts->qcount;i++) {
966                         if (ts->queue[i].sysjob == pjob.sysjob) {
967                                 break;
968                         }
969                 }
970                 if (i == ts->qcount) {
971                         DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !smbjob\n",
972                                                 (unsigned int)jobid ));
973                         pjob_delete(ts->ev, ts->msg_ctx,
974                                     ts->sharename, jobid);
975                         return 0;
976                 }
977
978                 /* need to continue the the bottom of the function to
979                    save the correct attributes */
980         }
981
982         /* maybe it hasn't been spooled yet */
983         if (!pjob.spooled) {
984                 /* if a job is not spooled and the process doesn't
985                    exist then kill it. This cleans up after smbd
986                    deaths */
987                 if (!process_exists_by_pid(pjob.pid)) {
988                         DEBUG(10,("traverse_fn_delete: pjob %u deleted due to !process_exists (%u)\n",
989                                                 (unsigned int)jobid, (unsigned int)pjob.pid ));
990                         pjob_delete(ts->ev, ts->msg_ctx,
991                                     ts->sharename, jobid);
992                 } else
993                         ts->total_jobs++;
994                 return 0;
995         }
996
997         /* this check only makes sense for jobs submitted from Windows clients */
998
999         if (pjob.smbjob) {
1000                 for (i=0;i<ts->qcount;i++) {
1001                         if ( pjob.status == LPQ_DELETED )
1002                                 continue;
1003
1004                         if (ts->queue[i].sysjob == pjob.sysjob) {
1005
1006                                 /* try to clean up any jobs that need to be deleted */
1007
1008                                 if ( pjob.status == LPQ_DELETING ) {
1009                                         int result;
1010
1011                                         result = (*(ts->print_if->job_delete))(
1012                                                 ts->sharename, ts->lprm_command, &pjob );
1013
1014                                         if ( result != 0 ) {
1015                                                 /* if we can't delete, then reset the job status */
1016                                                 pjob.status = LPQ_QUEUED;
1017                                                 pjob_store(ts->ev, ts->msg_ctx,
1018                                                            ts->sharename, jobid, &pjob);
1019                                         }
1020                                         else {
1021                                                 /* if we deleted the job, the remove the tdb record */
1022                                                 pjob_delete(ts->ev,
1023                                                             ts->msg_ctx,
1024                                                             ts->sharename, jobid);
1025                                                 pjob.status = LPQ_DELETED;
1026                                         }
1027
1028                                 }
1029
1030                                 break;
1031                         }
1032                 }
1033         }
1034
1035         /* The job isn't in the system queue - we have to assume it has
1036            completed, so delete the database entry. */
1037
1038         if (i == ts->qcount) {
1039
1040                 /* A race can occur between the time a job is spooled and
1041                    when it appears in the lpq output.  This happens when
1042                    the job is added to printing.tdb when another smbd
1043                    running print_queue_update() has completed a lpq and
1044                    is currently traversing the printing tdb and deleting jobs.
1045                    Don't delete the job if it was submitted after the lpq_time. */
1046
1047                 if (pjob.starttime < ts->lpq_time) {
1048                         DEBUG(10,("traverse_fn_delete: pjob %u deleted due to pjob.starttime (%u) < ts->lpq_time (%u)\n",
1049                                                 (unsigned int)jobid,
1050                                                 (unsigned int)pjob.starttime,
1051                                                 (unsigned int)ts->lpq_time ));
1052                         pjob_delete(ts->ev, ts->msg_ctx,
1053                                     ts->sharename, jobid);
1054                 } else
1055                         ts->total_jobs++;
1056                 return 0;
1057         }
1058
1059         /* Save the pjob attributes we will store. */
1060         ts->queue[i].sysjob = pjob.sysjob;
1061         ts->queue[i].size = pjob.size;
1062         ts->queue[i].page_count = pjob.page_count;
1063         ts->queue[i].status = pjob.status;
1064         ts->queue[i].priority = 1;
1065         ts->queue[i].time = pjob.starttime;
1066         fstrcpy(ts->queue[i].fs_user, pjob.user);
1067         fstrcpy(ts->queue[i].fs_file, pjob.jobname);
1068
1069         ts->total_jobs++;
1070
1071         return 0;
1072 }
1073
1074 /****************************************************************************
1075  Check if the print queue has been updated recently enough.
1076 ****************************************************************************/
1077
1078 static void print_cache_flush(const char *sharename)
1079 {
1080         fstring key;
1081         struct tdb_print_db *pdb = get_print_db_byname(sharename);
1082
1083         if (!pdb)
1084                 return;
1085         slprintf(key, sizeof(key)-1, "CACHE/%s", sharename);
1086         tdb_store_int32(pdb->tdb, key, -1);
1087         release_print_db(pdb);
1088 }
1089
1090 /****************************************************************************
1091  Check if someone already thinks they are doing the update.
1092 ****************************************************************************/
1093
1094 static pid_t get_updating_pid(const char *sharename)
1095 {
1096         fstring keystr;
1097         TDB_DATA data, key;
1098         pid_t updating_pid;
1099         struct tdb_print_db *pdb = get_print_db_byname(sharename);
1100
1101         if (!pdb)
1102                 return (pid_t)-1;
1103         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1104         key = string_tdb_data(keystr);
1105
1106         data = tdb_fetch(pdb->tdb, key);
1107         release_print_db(pdb);
1108         if (!data.dptr || data.dsize != sizeof(pid_t)) {
1109                 SAFE_FREE(data.dptr);
1110                 return (pid_t)-1;
1111         }
1112
1113         updating_pid = IVAL(data.dptr, 0);
1114         SAFE_FREE(data.dptr);
1115
1116         if (process_exists_by_pid(updating_pid))
1117                 return updating_pid;
1118
1119         return (pid_t)-1;
1120 }
1121
1122 /****************************************************************************
1123  Set the fact that we're doing the update, or have finished doing the update
1124  in the tdb.
1125 ****************************************************************************/
1126
1127 static void set_updating_pid(const fstring sharename, bool updating)
1128 {
1129         fstring keystr;
1130         TDB_DATA key;
1131         TDB_DATA data;
1132         pid_t updating_pid = sys_getpid();
1133         uint8 buffer[4];
1134
1135         struct tdb_print_db *pdb = get_print_db_byname(sharename);
1136
1137         if (!pdb)
1138                 return;
1139
1140         slprintf(keystr, sizeof(keystr)-1, "UPDATING/%s", sharename);
1141         key = string_tdb_data(keystr);
1142
1143         DEBUG(5, ("set_updating_pid: %s updating lpq cache for print share %s\n",
1144                 updating ? "" : "not ",
1145                 sharename ));
1146
1147         if ( !updating ) {
1148                 tdb_delete(pdb->tdb, key);
1149                 release_print_db(pdb);
1150                 return;
1151         }
1152
1153         SIVAL( buffer, 0, updating_pid);
1154         data.dptr = buffer;
1155         data.dsize = 4;         /* we always assume this is a 4 byte value */
1156
1157         tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1158         release_print_db(pdb);
1159 }
1160
1161 /****************************************************************************
1162  Sort print jobs by submittal time.
1163 ****************************************************************************/
1164
1165 static int printjob_comp(print_queue_struct *j1, print_queue_struct *j2)
1166 {
1167         /* Silly cases */
1168
1169         if (!j1 && !j2)
1170                 return 0;
1171         if (!j1)
1172                 return -1;
1173         if (!j2)
1174                 return 1;
1175
1176         /* Sort on job start time */
1177
1178         if (j1->time == j2->time)
1179                 return 0;
1180         return (j1->time > j2->time) ? 1 : -1;
1181 }
1182
1183 /****************************************************************************
1184  Store the sorted queue representation for later portmon retrieval.
1185  Skip deleted jobs
1186 ****************************************************************************/
1187
1188 static void store_queue_struct(struct tdb_print_db *pdb, struct traverse_struct *pts)
1189 {
1190         TDB_DATA data;
1191         int max_reported_jobs = lp_max_reported_jobs(pts->snum);
1192         print_queue_struct *queue = pts->queue;
1193         size_t len;
1194         size_t i;
1195         unsigned int qcount;
1196
1197         if (max_reported_jobs && (max_reported_jobs < pts->qcount))
1198                 pts->qcount = max_reported_jobs;
1199         qcount = 0;
1200
1201         /* Work out the size. */
1202         data.dsize = 0;
1203         data.dsize += tdb_pack(NULL, 0, "d", qcount);
1204
1205         for (i = 0; i < pts->qcount; i++) {
1206                 if ( queue[i].status == LPQ_DELETED )
1207                         continue;
1208
1209                 qcount++;
1210                 data.dsize += tdb_pack(NULL, 0, "ddddddff",
1211                                 (uint32)queue[i].sysjob,
1212                                 (uint32)queue[i].size,
1213                                 (uint32)queue[i].page_count,
1214                                 (uint32)queue[i].status,
1215                                 (uint32)queue[i].priority,
1216                                 (uint32)queue[i].time,
1217                                 queue[i].fs_user,
1218                                 queue[i].fs_file);
1219         }
1220
1221         if ((data.dptr = (uint8 *)SMB_MALLOC(data.dsize)) == NULL)
1222                 return;
1223
1224         len = 0;
1225         len += tdb_pack(data.dptr + len, data.dsize - len, "d", qcount);
1226         for (i = 0; i < pts->qcount; i++) {
1227                 if ( queue[i].status == LPQ_DELETED )
1228                         continue;
1229
1230                 len += tdb_pack(data.dptr + len, data.dsize - len, "ddddddff",
1231                                 (uint32)queue[i].sysjob,
1232                                 (uint32)queue[i].size,
1233                                 (uint32)queue[i].page_count,
1234                                 (uint32)queue[i].status,
1235                                 (uint32)queue[i].priority,
1236                                 (uint32)queue[i].time,
1237                                 queue[i].fs_user,
1238                                 queue[i].fs_file);
1239         }
1240
1241         tdb_store(pdb->tdb, string_tdb_data("INFO/linear_queue_array"), data,
1242                   TDB_REPLACE);
1243         SAFE_FREE(data.dptr);
1244         return;
1245 }
1246
1247 static TDB_DATA get_jobs_added_data(struct tdb_print_db *pdb)
1248 {
1249         TDB_DATA data;
1250
1251         ZERO_STRUCT(data);
1252
1253         data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_added"));
1254         if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0)) {
1255                 SAFE_FREE(data.dptr);
1256                 ZERO_STRUCT(data);
1257         }
1258
1259         return data;
1260 }
1261
1262 static void check_job_added(const char *sharename, TDB_DATA data, uint32 jobid)
1263 {
1264         unsigned int i;
1265         unsigned int job_count = data.dsize / 4;
1266
1267         for (i = 0; i < job_count; i++) {
1268                 uint32 ch_jobid;
1269
1270                 ch_jobid = IVAL(data.dptr, i*4);
1271                 if (ch_jobid == jobid)
1272                         remove_from_jobs_added(sharename, jobid);
1273         }
1274 }
1275
1276 /****************************************************************************
1277  Check if the print queue has been updated recently enough.
1278 ****************************************************************************/
1279
1280 static bool print_cache_expired(const char *sharename, bool check_pending)
1281 {
1282         fstring key;
1283         time_t last_qscan_time, time_now = time(NULL);
1284         struct tdb_print_db *pdb = get_print_db_byname(sharename);
1285         bool result = False;
1286
1287         if (!pdb)
1288                 return False;
1289
1290         snprintf(key, sizeof(key), "CACHE/%s", sharename);
1291         last_qscan_time = (time_t)tdb_fetch_int32(pdb->tdb, key);
1292
1293         /*
1294          * Invalidate the queue for 3 reasons.
1295          * (1). last queue scan time == -1.
1296          * (2). Current time - last queue scan time > allowed cache time.
1297          * (3). last queue scan time > current time + MAX_CACHE_VALID_TIME (1 hour by default).
1298          * This last test picks up machines for which the clock has been moved
1299          * forward, an lpq scan done and then the clock moved back. Otherwise
1300          * that last lpq scan would stay around for a loooong loooong time... :-). JRA.
1301          */
1302
1303         if (last_qscan_time == ((time_t)-1)
1304                 || (time_now - last_qscan_time) >= lp_lpqcachetime()
1305                 || last_qscan_time > (time_now + MAX_CACHE_VALID_TIME))
1306         {
1307                 uint32 u;
1308                 time_t msg_pending_time;
1309
1310                 DEBUG(4, ("print_cache_expired: cache expired for queue %s "
1311                         "(last_qscan_time = %d, time now = %d, qcachetime = %d)\n",
1312                         sharename, (int)last_qscan_time, (int)time_now,
1313                         (int)lp_lpqcachetime() ));
1314
1315                 /* check if another smbd has already sent a message to update the
1316                    queue.  Give the pending message one minute to clear and
1317                    then send another message anyways.  Make sure to check for
1318                    clocks that have been run forward and then back again. */
1319
1320                 snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1321
1322                 if ( check_pending
1323                         && tdb_fetch_uint32( pdb->tdb, key, &u )
1324                         && (msg_pending_time=u) > 0
1325                         && msg_pending_time <= time_now
1326                         && (time_now - msg_pending_time) < 60 )
1327                 {
1328                         DEBUG(4,("print_cache_expired: message already pending for %s.  Accepting cache\n",
1329                                 sharename));
1330                         goto done;
1331                 }
1332
1333                 result = True;
1334         }
1335
1336 done:
1337         release_print_db(pdb);
1338         return result;
1339 }
1340
1341 /****************************************************************************
1342  main work for updating the lpq cache for a printer queue
1343 ****************************************************************************/
1344
1345 static void print_queue_update_internal(struct tevent_context *ev,
1346                                         struct messaging_context *msg_ctx,
1347                                         const char *sharename,
1348                                         struct printif *current_printif,
1349                                         char *lpq_command, char *lprm_command)
1350 {
1351         int i, qcount;
1352         print_queue_struct *queue = NULL;
1353         print_status_struct status;
1354         print_status_struct old_status;
1355         struct printjob *pjob;
1356         struct traverse_struct tstruct;
1357         TDB_DATA data, key;
1358         TDB_DATA jcdata;
1359         fstring keystr, cachestr;
1360         struct tdb_print_db *pdb = get_print_db_byname(sharename);
1361         TALLOC_CTX *tmp_ctx = talloc_new(ev);
1362
1363         if ((pdb == NULL) || (tmp_ctx == NULL)) {
1364                 return;
1365         }
1366
1367         DEBUG(5,("print_queue_update_internal: printer = %s, type = %d, lpq command = [%s]\n",
1368                 sharename, current_printif->type, lpq_command));
1369
1370         /*
1371          * Update the cache time FIRST ! Stops others even
1372          * attempting to get the lock and doing this
1373          * if the lpq takes a long time.
1374          */
1375
1376         slprintf(cachestr, sizeof(cachestr)-1, "CACHE/%s", sharename);
1377         tdb_store_int32(pdb->tdb, cachestr, (int)time(NULL));
1378
1379         /* get the current queue using the appropriate interface */
1380         ZERO_STRUCT(status);
1381
1382         qcount = (*(current_printif->queue_get))(sharename,
1383                 current_printif->type,
1384                 lpq_command, &queue, &status);
1385
1386         DEBUG(3, ("print_queue_update_internal: %d job%s in queue for %s\n",
1387                 qcount, (qcount != 1) ? "s" : "", sharename));
1388
1389         /* Sort the queue by submission time otherwise they are displayed
1390            in hash order. */
1391
1392         TYPESAFE_QSORT(queue, qcount, printjob_comp);
1393
1394         /*
1395           any job in the internal database that is marked as spooled
1396           and doesn't exist in the system queue is considered finished
1397           and removed from the database
1398
1399           any job in the system database but not in the internal database
1400           is added as a unix job
1401
1402           fill in any system job numbers as we go
1403         */
1404         jcdata = get_jobs_added_data(pdb);
1405
1406         for (i=0; i<qcount; i++) {
1407                 uint32 jobid = sysjob_to_jobid_pdb(pdb, queue[i].sysjob);
1408                 if (jobid == (uint32)-1) {
1409                         /* assume its a unix print job */
1410                         print_unix_job(ev, msg_ctx,
1411                                        sharename, &queue[i], jobid);
1412                         continue;
1413                 }
1414
1415                 /* we have an active SMB print job - update its status */
1416                 pjob = print_job_find(tmp_ctx, sharename, jobid);
1417                 if (!pjob) {
1418                         /* err, somethings wrong. Probably smbd was restarted
1419                            with jobs in the queue. All we can do is treat them
1420                            like unix jobs. Pity. */
1421                         DEBUG(1, ("queued print job %d not found in jobs list, "
1422                                   "assuming unix job\n", jobid));
1423                         print_unix_job(ev, msg_ctx,
1424                                        sharename, &queue[i], jobid);
1425                         continue;
1426                 }
1427
1428                 /* don't reset the status on jobs to be deleted */
1429
1430                 if ( pjob->status != LPQ_DELETING )
1431                         pjob->status = queue[i].status;
1432
1433                 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
1434
1435                 check_job_added(sharename, jcdata, jobid);
1436         }
1437
1438         SAFE_FREE(jcdata.dptr);
1439         talloc_free(tmp_ctx);
1440
1441         /* now delete any queued entries that don't appear in the
1442            system queue */
1443         tstruct.queue = queue;
1444         tstruct.qcount = qcount;
1445         tstruct.snum = -1;
1446         tstruct.total_jobs = 0;
1447         tstruct.lpq_time = time(NULL);
1448         tstruct.sharename = sharename;
1449         tstruct.lprm_command = lprm_command;
1450         tstruct.print_if = current_printif;
1451         tstruct.ev = ev;
1452         tstruct.msg_ctx = msg_ctx;
1453
1454         tdb_traverse(pdb->tdb, traverse_fn_delete, (void *)&tstruct);
1455
1456         /* Store the linearised queue, max jobs only. */
1457         store_queue_struct(pdb, &tstruct);
1458
1459         SAFE_FREE(tstruct.queue);
1460
1461         DEBUG(10,("print_queue_update_internal: printer %s INFO/total_jobs = %d\n",
1462                                 sharename, tstruct.total_jobs ));
1463
1464         tdb_store_int32(pdb->tdb, "INFO/total_jobs", tstruct.total_jobs);
1465
1466         get_queue_status(sharename, &old_status);
1467         if (old_status.qcount != qcount)
1468                 DEBUG(10,("print_queue_update_internal: queue status change %d jobs -> %d jobs for printer %s\n",
1469                                         old_status.qcount, qcount, sharename));
1470
1471         /* store the new queue status structure */
1472         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
1473         key = string_tdb_data(keystr);
1474
1475         status.qcount = qcount;
1476         data.dptr = (uint8 *)&status;
1477         data.dsize = sizeof(status);
1478         tdb_store(pdb->tdb, key, data, TDB_REPLACE);
1479
1480         /*
1481          * Update the cache time again. We want to do this call
1482          * as little as possible...
1483          */
1484
1485         slprintf(keystr, sizeof(keystr)-1, "CACHE/%s", sharename);
1486         tdb_store_int32(pdb->tdb, keystr, (int32)time(NULL));
1487
1488         /* clear the msg pending record for this queue */
1489
1490         snprintf(keystr, sizeof(keystr), "MSG_PENDING/%s", sharename);
1491
1492         if ( !tdb_store_uint32( pdb->tdb, keystr, 0 ) ) {
1493                 /* log a message but continue on */
1494
1495                 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1496                         sharename));
1497         }
1498
1499         release_print_db( pdb );
1500
1501         return;
1502 }
1503
1504 /****************************************************************************
1505  Update the internal database from the system print queue for a queue.
1506  obtain a lock on the print queue before proceeding (needed when mutiple
1507  smbd processes maytry to update the lpq cache concurrently).
1508 ****************************************************************************/
1509
1510 static void print_queue_update_with_lock( struct tevent_context *ev,
1511                                           struct messaging_context *msg_ctx,
1512                                           const char *sharename,
1513                                           struct printif *current_printif,
1514                                           char *lpq_command, char *lprm_command )
1515 {
1516         fstring keystr;
1517         struct tdb_print_db *pdb;
1518
1519         DEBUG(5,("print_queue_update_with_lock: printer share = %s\n", sharename));
1520         pdb = get_print_db_byname(sharename);
1521         if (!pdb)
1522                 return;
1523
1524         if ( !print_cache_expired(sharename, False) ) {
1525                 DEBUG(5,("print_queue_update_with_lock: print cache for %s is still ok\n", sharename));
1526                 release_print_db(pdb);
1527                 return;
1528         }
1529
1530         /*
1531          * Check to see if someone else is doing this update.
1532          * This is essentially a mutex on the update.
1533          */
1534
1535         if (get_updating_pid(sharename) != -1) {
1536                 release_print_db(pdb);
1537                 return;
1538         }
1539
1540         /* Lock the queue for the database update */
1541
1542         slprintf(keystr, sizeof(keystr) - 1, "LOCK/%s", sharename);
1543         /* Only wait 10 seconds for this. */
1544         if (tdb_lock_bystring_with_timeout(pdb->tdb, keystr, 10) == -1) {
1545                 DEBUG(0,("print_queue_update_with_lock: Failed to lock printer %s database\n", sharename));
1546                 release_print_db(pdb);
1547                 return;
1548         }
1549
1550         /*
1551          * Ensure that no one else got in here.
1552          * If the updating pid is still -1 then we are
1553          * the winner.
1554          */
1555
1556         if (get_updating_pid(sharename) != -1) {
1557                 /*
1558                  * Someone else is doing the update, exit.
1559                  */
1560                 tdb_unlock_bystring(pdb->tdb, keystr);
1561                 release_print_db(pdb);
1562                 return;
1563         }
1564
1565         /*
1566          * We're going to do the update ourselves.
1567          */
1568
1569         /* Tell others we're doing the update. */
1570         set_updating_pid(sharename, True);
1571
1572         /*
1573          * Allow others to enter and notice we're doing
1574          * the update.
1575          */
1576
1577         tdb_unlock_bystring(pdb->tdb, keystr);
1578
1579         /* do the main work now */
1580
1581         print_queue_update_internal(ev, msg_ctx,
1582                                     sharename, current_printif,
1583                                     lpq_command, lprm_command);
1584
1585         /* Delete our pid from the db. */
1586         set_updating_pid(sharename, False);
1587         release_print_db(pdb);
1588 }
1589
1590 /****************************************************************************
1591 this is the receive function of the background lpq updater
1592 ****************************************************************************/
1593 void print_queue_receive(struct messaging_context *msg,
1594                                 void *private_data,
1595                                 uint32_t msg_type,
1596                                 struct server_id server_id,
1597                                 DATA_BLOB *data)
1598 {
1599         fstring sharename;
1600         char *lpqcommand = NULL, *lprmcommand = NULL;
1601         int printing_type;
1602         size_t len;
1603
1604         len = tdb_unpack( (uint8 *)data->data, data->length, "fdPP",
1605                 sharename,
1606                 &printing_type,
1607                 &lpqcommand,
1608                 &lprmcommand );
1609
1610         if ( len == -1 ) {
1611                 SAFE_FREE(lpqcommand);
1612                 SAFE_FREE(lprmcommand);
1613                 DEBUG(0,("print_queue_receive: Got invalid print queue update message\n"));
1614                 return;
1615         }
1616
1617         print_queue_update_with_lock(server_event_context(), msg, sharename,
1618                 get_printer_fns_from_type((enum printing_types)printing_type),
1619                 lpqcommand, lprmcommand );
1620
1621         SAFE_FREE(lpqcommand);
1622         SAFE_FREE(lprmcommand);
1623         return;
1624 }
1625
1626 static void printing_pause_fd_handler(struct tevent_context *ev,
1627                                       struct tevent_fd *fde,
1628                                       uint16_t flags,
1629                                       void *private_data)
1630 {
1631         /*
1632          * If pause_pipe[1] is closed it means the parent smbd
1633          * and children exited or aborted.
1634          */
1635         exit_server_cleanly(NULL);
1636 }
1637
1638 extern struct child_pid *children;
1639 extern int num_children;
1640
1641 static void add_child_pid(pid_t pid)
1642 {
1643         struct child_pid *child;
1644
1645         child = SMB_MALLOC_P(struct child_pid);
1646         if (child == NULL) {
1647                 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
1648                 return;
1649         }
1650         child->pid = pid;
1651         DLIST_ADD(children, child);
1652         num_children += 1;
1653 }
1654
1655 static pid_t background_lpq_updater_pid = -1;
1656
1657 /****************************************************************************
1658 main thread of the background lpq updater
1659 ****************************************************************************/
1660 void start_background_queue(struct tevent_context *ev,
1661                             struct messaging_context *msg_ctx)
1662 {
1663         /* Use local variables for this as we don't
1664          * need to save the parent side of this, just
1665          * ensure it closes when the process exits.
1666          */
1667         int pause_pipe[2];
1668
1669         DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
1670
1671         if (pipe(pause_pipe) == -1) {
1672                 DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
1673                 exit(1);
1674         }
1675
1676         background_lpq_updater_pid = sys_fork();
1677
1678         if (background_lpq_updater_pid == -1) {
1679                 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
1680                 exit(1);
1681         }
1682
1683         /* Track the printing pid along with other smbd children */
1684         add_child_pid(background_lpq_updater_pid);
1685
1686         if(background_lpq_updater_pid == 0) {
1687                 struct tevent_fd *fde;
1688                 int ret;
1689                 NTSTATUS status;
1690
1691                 /* Child. */
1692                 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
1693
1694                 close(pause_pipe[0]);
1695                 pause_pipe[0] = -1;
1696
1697                 status = reinit_after_fork(msg_ctx, ev, procid_self(), true);
1698
1699                 if (!NT_STATUS_IS_OK(status)) {
1700                         DEBUG(0,("reinit_after_fork() failed\n"));
1701                         smb_panic("reinit_after_fork() failed");
1702                 }
1703
1704                 smbd_setup_sig_term_handler();
1705                 smbd_setup_sig_hup_handler(ev, msg_ctx);
1706
1707                 if (!serverid_register(procid_self(),
1708                                        FLAG_MSG_GENERAL|FLAG_MSG_SMBD
1709                                        |FLAG_MSG_PRINT_GENERAL)) {
1710                         exit(1);
1711                 }
1712
1713                 if (!locking_init()) {
1714                         exit(1);
1715                 }
1716
1717                 messaging_register(msg_ctx, NULL, MSG_PRINTER_UPDATE,
1718                                    print_queue_receive);
1719
1720                 fde = tevent_add_fd(ev, ev, pause_pipe[1], TEVENT_FD_READ,
1721                                     printing_pause_fd_handler,
1722                                     NULL);
1723                 if (!fde) {
1724                         DEBUG(0,("tevent_add_fd() failed for pause_pipe\n"));
1725                         smb_panic("tevent_add_fd() failed for pause_pipe");
1726                 }
1727
1728                 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
1729                 ret = tevent_loop_wait(ev);
1730                 /* should not be reached */
1731                 DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
1732                          ret, (ret == 0) ? "out of events" : strerror(errno)));
1733                 exit(1);
1734         }
1735
1736         close(pause_pipe[1]);
1737 }
1738
1739 /****************************************************************************
1740 update the internal database from the system print queue for a queue
1741 ****************************************************************************/
1742
1743 static void print_queue_update(struct messaging_context *msg_ctx,
1744                                int snum, bool force)
1745 {
1746         fstring key;
1747         fstring sharename;
1748         char *lpqcommand = NULL;
1749         char *lprmcommand = NULL;
1750         uint8 *buffer = NULL;
1751         size_t len = 0;
1752         size_t newlen;
1753         struct tdb_print_db *pdb;
1754         int type;
1755         struct printif *current_printif;
1756         TALLOC_CTX *ctx = talloc_tos();
1757
1758         fstrcpy( sharename, lp_const_servicename(snum));
1759
1760         /* don't strip out characters like '$' from the printername */
1761
1762         lpqcommand = talloc_string_sub2(ctx,
1763                         lp_lpqcommand(snum),
1764                         "%p",
1765                         lp_printername(snum),
1766                         false, false, false);
1767         if (!lpqcommand) {
1768                 return;
1769         }
1770         lpqcommand = talloc_sub_advanced(ctx,
1771                         lp_servicename(snum),
1772                         current_user_info.unix_name,
1773                         "",
1774                         current_user.ut.gid,
1775                         get_current_username(),
1776                         current_user_info.domain,
1777                         lpqcommand);
1778         if (!lpqcommand) {
1779                 return;
1780         }
1781
1782         lprmcommand = talloc_string_sub2(ctx,
1783                         lp_lprmcommand(snum),
1784                         "%p",
1785                         lp_printername(snum),
1786                         false, false, false);
1787         if (!lprmcommand) {
1788                 return;
1789         }
1790         lprmcommand = talloc_sub_advanced(ctx,
1791                         lp_servicename(snum),
1792                         current_user_info.unix_name,
1793                         "",
1794                         current_user.ut.gid,
1795                         get_current_username(),
1796                         current_user_info.domain,
1797                         lprmcommand);
1798         if (!lprmcommand) {
1799                 return;
1800         }
1801
1802         /*
1803          * Make sure that the background queue process exists.
1804          * Otherwise just do the update ourselves
1805          */
1806
1807         if ( force || background_lpq_updater_pid == -1 ) {
1808                 DEBUG(4,("print_queue_update: updating queue [%s] myself\n", sharename));
1809                 current_printif = get_printer_fns( snum );
1810                 print_queue_update_with_lock(server_event_context(), msg_ctx,
1811                                              sharename, current_printif,
1812                                              lpqcommand, lprmcommand);
1813
1814                 return;
1815         }
1816
1817         type = lp_printing(snum);
1818
1819         /* get the length */
1820
1821         len = tdb_pack( NULL, 0, "fdPP",
1822                 sharename,
1823                 type,
1824                 lpqcommand,
1825                 lprmcommand );
1826
1827         buffer = SMB_XMALLOC_ARRAY( uint8, len );
1828
1829         /* now pack the buffer */
1830         newlen = tdb_pack( buffer, len, "fdPP",
1831                 sharename,
1832                 type,
1833                 lpqcommand,
1834                 lprmcommand );
1835
1836         SMB_ASSERT( newlen == len );
1837
1838         DEBUG(10,("print_queue_update: Sending message -> printer = %s, "
1839                 "type = %d, lpq command = [%s] lprm command = [%s]\n",
1840                 sharename, type, lpqcommand, lprmcommand ));
1841
1842         /* here we set a msg pending record for other smbd processes
1843            to throttle the number of duplicate print_queue_update msgs
1844            sent.  */
1845
1846         pdb = get_print_db_byname(sharename);
1847         if (!pdb) {
1848                 SAFE_FREE(buffer);
1849                 return;
1850         }
1851
1852         snprintf(key, sizeof(key), "MSG_PENDING/%s", sharename);
1853
1854         if ( !tdb_store_uint32( pdb->tdb, key, time(NULL) ) ) {
1855                 /* log a message but continue on */
1856
1857                 DEBUG(0,("print_queue_update: failed to store MSG_PENDING flag for [%s]!\n",
1858                         sharename));
1859         }
1860
1861         release_print_db( pdb );
1862
1863         /* finally send the message */
1864
1865         messaging_send_buf(msg_ctx, pid_to_procid(background_lpq_updater_pid),
1866                            MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
1867
1868         SAFE_FREE( buffer );
1869
1870         return;
1871 }
1872
1873 /****************************************************************************
1874  Create/Update an entry in the print tdb that will allow us to send notify
1875  updates only to interested smbd's.
1876 ****************************************************************************/
1877
1878 bool print_notify_register_pid(int snum)
1879 {
1880         TDB_DATA data;
1881         struct tdb_print_db *pdb = NULL;
1882         TDB_CONTEXT *tdb = NULL;
1883         const char *printername;
1884         uint32 mypid = (uint32)sys_getpid();
1885         bool ret = False;
1886         size_t i;
1887
1888         /* if (snum == -1), then the change notify request was
1889            on a print server handle and we need to register on
1890            all print queus */
1891
1892         if (snum == -1)
1893         {
1894                 int num_services = lp_numservices();
1895                 int idx;
1896
1897                 for ( idx=0; idx<num_services; idx++ ) {
1898                         if (lp_snum_ok(idx) && lp_print_ok(idx) )
1899                                 print_notify_register_pid(idx);
1900                 }
1901
1902                 return True;
1903         }
1904         else /* register for a specific printer */
1905         {
1906                 printername = lp_const_servicename(snum);
1907                 pdb = get_print_db_byname(printername);
1908                 if (!pdb)
1909                         return False;
1910                 tdb = pdb->tdb;
1911         }
1912
1913         if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
1914                 DEBUG(0,("print_notify_register_pid: Failed to lock printer %s\n",
1915                                         printername));
1916                 if (pdb)
1917                         release_print_db(pdb);
1918                 return False;
1919         }
1920
1921         data = get_printer_notify_pid_list( tdb, printername, True );
1922
1923         /* Add ourselves and increase the refcount. */
1924
1925         for (i = 0; i < data.dsize; i += 8) {
1926                 if (IVAL(data.dptr,i) == mypid) {
1927                         uint32 new_refcount = IVAL(data.dptr, i+4) + 1;
1928                         SIVAL(data.dptr, i+4, new_refcount);
1929                         break;
1930                 }
1931         }
1932
1933         if (i == data.dsize) {
1934                 /* We weren't in the list. Realloc. */
1935                 data.dptr = (uint8 *)SMB_REALLOC(data.dptr, data.dsize + 8);
1936                 if (!data.dptr) {
1937                         DEBUG(0,("print_notify_register_pid: Relloc fail for printer %s\n",
1938                                                 printername));
1939                         goto done;
1940                 }
1941                 data.dsize += 8;
1942                 SIVAL(data.dptr,data.dsize - 8,mypid);
1943                 SIVAL(data.dptr,data.dsize - 4,1); /* Refcount. */
1944         }
1945
1946         /* Store back the record. */
1947         if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
1948                 DEBUG(0,("print_notify_register_pid: Failed to update pid \
1949 list for printer %s\n", printername));
1950                 goto done;
1951         }
1952
1953         ret = True;
1954
1955  done:
1956
1957         tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
1958         if (pdb)
1959                 release_print_db(pdb);
1960         SAFE_FREE(data.dptr);
1961         return ret;
1962 }
1963
1964 /****************************************************************************
1965  Update an entry in the print tdb that will allow us to send notify
1966  updates only to interested smbd's.
1967 ****************************************************************************/
1968
1969 bool print_notify_deregister_pid(int snum)
1970 {
1971         TDB_DATA data;
1972         struct tdb_print_db *pdb = NULL;
1973         TDB_CONTEXT *tdb = NULL;
1974         const char *printername;
1975         uint32 mypid = (uint32)sys_getpid();
1976         size_t i;
1977         bool ret = False;
1978
1979         /* if ( snum == -1 ), we are deregister a print server handle
1980            which means to deregister on all print queues */
1981
1982         if (snum == -1)
1983         {
1984                 int num_services = lp_numservices();
1985                 int idx;
1986
1987                 for ( idx=0; idx<num_services; idx++ ) {
1988                         if ( lp_snum_ok(idx) && lp_print_ok(idx) )
1989                                 print_notify_deregister_pid(idx);
1990                 }
1991
1992                 return True;
1993         }
1994         else /* deregister a specific printer */
1995         {
1996                 printername = lp_const_servicename(snum);
1997                 pdb = get_print_db_byname(printername);
1998                 if (!pdb)
1999                         return False;
2000                 tdb = pdb->tdb;
2001         }
2002
2003         if (tdb_lock_bystring_with_timeout(tdb, NOTIFY_PID_LIST_KEY, 10) == -1) {
2004                 DEBUG(0,("print_notify_register_pid: Failed to lock \
2005 printer %s database\n", printername));
2006                 if (pdb)
2007                         release_print_db(pdb);
2008                 return False;
2009         }
2010
2011         data = get_printer_notify_pid_list( tdb, printername, True );
2012
2013         /* Reduce refcount. Remove ourselves if zero. */
2014
2015         for (i = 0; i < data.dsize; ) {
2016                 if (IVAL(data.dptr,i) == mypid) {
2017                         uint32 refcount = IVAL(data.dptr, i+4);
2018
2019                         refcount--;
2020
2021                         if (refcount == 0) {
2022                                 if (data.dsize - i > 8)
2023                                         memmove( &data.dptr[i], &data.dptr[i+8], data.dsize - i - 8);
2024                                 data.dsize -= 8;
2025                                 continue;
2026                         }
2027                         SIVAL(data.dptr, i+4, refcount);
2028                 }
2029
2030                 i += 8;
2031         }
2032
2033         if (data.dsize == 0)
2034                 SAFE_FREE(data.dptr);
2035
2036         /* Store back the record. */
2037         if (tdb_store_bystring(tdb, NOTIFY_PID_LIST_KEY, data, TDB_REPLACE) == -1) {
2038                 DEBUG(0,("print_notify_register_pid: Failed to update pid \
2039 list for printer %s\n", printername));
2040                 goto done;
2041         }
2042
2043         ret = True;
2044
2045   done:
2046
2047         tdb_unlock_bystring(tdb, NOTIFY_PID_LIST_KEY);
2048         if (pdb)
2049                 release_print_db(pdb);
2050         SAFE_FREE(data.dptr);
2051         return ret;
2052 }
2053
2054 /****************************************************************************
2055  Check if a jobid is valid. It is valid if it exists in the database.
2056 ****************************************************************************/
2057
2058 bool print_job_exists(const char* sharename, uint32 jobid)
2059 {
2060         struct tdb_print_db *pdb = get_print_db_byname(sharename);
2061         bool ret;
2062         uint32_t tmp;
2063
2064         if (!pdb)
2065                 return False;
2066         ret = tdb_exists(pdb->tdb, print_key(jobid, &tmp));
2067         release_print_db(pdb);
2068         return ret;
2069 }
2070
2071 /****************************************************************************
2072  Give the filename used for a jobid.
2073  Only valid for the process doing the spooling and when the job
2074  has not been spooled.
2075 ****************************************************************************/
2076
2077 char *print_job_fname(const char* sharename, uint32 jobid)
2078 {
2079         struct printjob *pjob = print_job_find(NULL, sharename, jobid);
2080         if (!pjob || pjob->spooled || pjob->pid != sys_getpid())
2081                 return NULL;
2082         return pjob->filename;
2083 }
2084
2085
2086 /****************************************************************************
2087  Give the filename used for a jobid.
2088  Only valid for the process doing the spooling and when the job
2089  has not been spooled.
2090 ****************************************************************************/
2091
2092 struct spoolss_DeviceMode *print_job_devmode(TALLOC_CTX *mem_ctx,
2093                                              const char *sharename,
2094                                              uint32 jobid)
2095 {
2096         struct printjob *pjob = print_job_find(mem_ctx, sharename, jobid);
2097         if (pjob == NULL) {
2098                 return NULL;
2099         }
2100
2101         return pjob->devmode;
2102 }
2103
2104 /****************************************************************************
2105  Set the name of a job. Only possible for owner.
2106 ****************************************************************************/
2107
2108 bool print_job_set_name(struct tevent_context *ev,
2109                         struct messaging_context *msg_ctx,
2110                         const char *sharename, uint32 jobid, const char *name)
2111 {
2112         struct printjob *pjob;
2113         bool ret;
2114         TALLOC_CTX *tmp_ctx = talloc_new(ev);
2115         if (tmp_ctx == NULL) {
2116                 return false;
2117         }
2118
2119         pjob = print_job_find(tmp_ctx, sharename, jobid);
2120         if (!pjob || pjob->pid != sys_getpid()) {
2121                 ret = false;
2122                 goto err_out;
2123         }
2124
2125         fstrcpy(pjob->jobname, name);
2126         ret = pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2127 err_out:
2128         talloc_free(tmp_ctx);
2129         return ret;
2130 }
2131
2132 /****************************************************************************
2133  Get the name of a job. Only possible for owner.
2134 ****************************************************************************/
2135
2136 bool print_job_get_name(TALLOC_CTX *mem_ctx, const char *sharename, uint32_t jobid, char **name)
2137 {
2138         struct printjob *pjob;
2139
2140         pjob = print_job_find(mem_ctx, sharename, jobid);
2141         if (!pjob || pjob->pid != sys_getpid()) {
2142                 return false;
2143         }
2144
2145         return pjob->jobname;
2146 }
2147
2148
2149 /***************************************************************************
2150  Remove a jobid from the 'jobs added' list.
2151 ***************************************************************************/
2152
2153 static bool remove_from_jobs_added(const char* sharename, uint32 jobid)
2154 {
2155         struct tdb_print_db *pdb = get_print_db_byname(sharename);
2156         TDB_DATA data, key;
2157         size_t job_count, i;
2158         bool ret = False;
2159         bool gotlock = False;
2160
2161         if (!pdb) {
2162                 return False;
2163         }
2164
2165         ZERO_STRUCT(data);
2166
2167         key = string_tdb_data("INFO/jobs_added");
2168
2169         if (tdb_chainlock_with_timeout(pdb->tdb, key, 5) == -1)
2170                 goto out;
2171
2172         gotlock = True;
2173
2174         data = tdb_fetch(pdb->tdb, key);
2175
2176         if (data.dptr == NULL || data.dsize == 0 || (data.dsize % 4 != 0))
2177                 goto out;
2178
2179         job_count = data.dsize / 4;
2180         for (i = 0; i < job_count; i++) {
2181                 uint32 ch_jobid;
2182
2183                 ch_jobid = IVAL(data.dptr, i*4);
2184                 if (ch_jobid == jobid) {
2185                         if (i < job_count -1 )
2186                                 memmove(data.dptr + (i*4), data.dptr + (i*4) + 4, (job_count - i - 1)*4 );
2187                         data.dsize -= 4;
2188                         if (tdb_store(pdb->tdb, key, data, TDB_REPLACE) == -1)
2189                                 goto out;
2190                         break;
2191                 }
2192         }
2193
2194         ret = True;
2195   out:
2196
2197         if (gotlock)
2198                 tdb_chainunlock(pdb->tdb, key);
2199         SAFE_FREE(data.dptr);
2200         release_print_db(pdb);
2201         if (ret)
2202                 DEBUG(10,("remove_from_jobs_added: removed jobid %u\n", (unsigned int)jobid ));
2203         else
2204                 DEBUG(10,("remove_from_jobs_added: Failed to remove jobid %u\n", (unsigned int)jobid ));
2205         return ret;
2206 }
2207
2208 /****************************************************************************
2209  Delete a print job - don't update queue.
2210 ****************************************************************************/
2211
2212 static bool print_job_delete1(struct tevent_context *ev,
2213                               struct messaging_context *msg_ctx,
2214                               int snum, uint32 jobid)
2215 {
2216         const char* sharename = lp_const_servicename(snum);
2217         struct printjob *pjob;
2218         int result = 0;
2219         struct printif *current_printif = get_printer_fns( snum );
2220         bool ret;
2221         TALLOC_CTX *tmp_ctx = talloc_new(ev);
2222         if (tmp_ctx == NULL) {
2223                 return false;
2224         }
2225
2226         pjob = print_job_find(tmp_ctx, sharename, jobid);
2227         if (!pjob) {
2228                 ret = false;
2229                 goto err_out;
2230         }
2231
2232         /*
2233          * If already deleting just return.
2234          */
2235
2236         if (pjob->status == LPQ_DELETING) {
2237                 ret = true;
2238                 goto err_out;
2239         }
2240
2241         /* Hrm - we need to be able to cope with deleting a job before it
2242            has reached the spooler.  Just mark it as LPQ_DELETING and
2243            let the print_queue_update() code rmeove the record */
2244
2245
2246         if (pjob->sysjob == -1) {
2247                 DEBUG(5, ("attempt to delete job %u not seen by lpr\n", (unsigned int)jobid));
2248         }
2249
2250         /* Set the tdb entry to be deleting. */
2251
2252         pjob->status = LPQ_DELETING;
2253         pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2254
2255         if (pjob->spooled && pjob->sysjob != -1)
2256         {
2257                 result = (*(current_printif->job_delete))(
2258                         lp_printername(snum),
2259                         lp_lprmcommand(snum),
2260                         pjob);
2261
2262                 /* Delete the tdb entry if the delete succeeded or the job hasn't
2263                    been spooled. */
2264
2265                 if (result == 0) {
2266                         struct tdb_print_db *pdb = get_print_db_byname(sharename);
2267                         int njobs = 1;
2268
2269                         if (!pdb) {
2270                                 ret = false;
2271                                 goto err_out;
2272                         }
2273                         pjob_delete(ev, msg_ctx, sharename, jobid);
2274                         /* Ensure we keep a rough count of the number of total jobs... */
2275                         tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, -1);
2276                         release_print_db(pdb);
2277                 }
2278         }
2279
2280         remove_from_jobs_added( sharename, jobid );
2281
2282         ret = (result == 0);
2283 err_out:
2284         talloc_free(tmp_ctx);
2285         return ret;
2286 }
2287
2288 /****************************************************************************
2289  Return true if the current user owns the print job.
2290 ****************************************************************************/
2291
2292 static bool is_owner(const struct auth_serversupplied_info *server_info,
2293                      const char *servicename,
2294                      uint32 jobid)
2295 {
2296         struct printjob *pjob;
2297         bool ret;
2298         TALLOC_CTX *tmp_ctx = talloc_new(server_info);
2299         if (tmp_ctx == NULL) {
2300                 return false;
2301         }
2302
2303         pjob = print_job_find(tmp_ctx, servicename, jobid);
2304         if (!pjob || !server_info) {
2305                 ret = false;
2306                 goto err_out;
2307         }
2308
2309         ret = strequal(pjob->user, server_info->sanitized_username);
2310 err_out:
2311         talloc_free(tmp_ctx);
2312         return ret;
2313 }
2314
2315 /****************************************************************************
2316  Delete a print job.
2317 ****************************************************************************/
2318
2319 WERROR print_job_delete(const struct auth_serversupplied_info *server_info,
2320                         struct messaging_context *msg_ctx,
2321                         int snum, uint32_t jobid)
2322 {
2323         const char* sharename = lp_const_servicename(snum);
2324         struct printjob *pjob;
2325         bool    owner;
2326         WERROR werr;
2327         TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2328         if (tmp_ctx == NULL) {
2329                 return WERR_NOT_ENOUGH_MEMORY;
2330         }
2331
2332         owner = is_owner(server_info, lp_const_servicename(snum), jobid);
2333
2334         /* Check access against security descriptor or whether the user
2335            owns their job. */
2336
2337         if (!owner &&
2338             !print_access_check(server_info, msg_ctx, snum,
2339                                 JOB_ACCESS_ADMINISTER)) {
2340                 DEBUG(3, ("delete denied by security descriptor\n"));
2341
2342                 /* BEGIN_ADMIN_LOG */
2343                 sys_adminlog( LOG_ERR,
2344                               "Permission denied-- user not allowed to delete, \
2345 pause, or resume print job. User name: %s. Printer name: %s.",
2346                               uidtoname(server_info->utok.uid),
2347                               lp_printername(snum) );
2348                 /* END_ADMIN_LOG */
2349
2350                 werr = WERR_ACCESS_DENIED;
2351                 goto err_out;
2352         }
2353
2354         /*
2355          * get the spooled filename of the print job
2356          * if this works, then the file has not been spooled
2357          * to the underlying print system.  Just delete the
2358          * spool file & return.
2359          */
2360
2361         pjob = print_job_find(tmp_ctx, sharename, jobid);
2362         if (!pjob || pjob->spooled || pjob->pid != getpid()) {
2363                 DEBUG(10, ("Skipping spool file removal for job %u\n", jobid));
2364         } else {
2365                 DEBUG(10, ("Removing spool file [%s]\n", pjob->filename));
2366                 if (unlink(pjob->filename) == -1) {
2367                         werr = map_werror_from_unix(errno);
2368                         goto err_out;
2369                 }
2370         }
2371
2372         if (!print_job_delete1(server_event_context(), msg_ctx, snum, jobid)) {
2373                 werr = WERR_ACCESS_DENIED;
2374                 goto err_out;
2375         }
2376
2377         /* force update the database and say the delete failed if the
2378            job still exists */
2379
2380         print_queue_update(msg_ctx, snum, True);
2381
2382         pjob = print_job_find(tmp_ctx, sharename, jobid);
2383         if (pjob && (pjob->status != LPQ_DELETING)) {
2384                 werr = WERR_ACCESS_DENIED;
2385                 goto err_out;
2386         }
2387         werr = WERR_PRINTER_HAS_JOBS_QUEUED;
2388
2389 err_out:
2390         talloc_free(tmp_ctx);
2391         return werr;
2392 }
2393
2394 /****************************************************************************
2395  Pause a job.
2396 ****************************************************************************/
2397
2398 WERROR print_job_pause(const struct auth_serversupplied_info *server_info,
2399                      struct messaging_context *msg_ctx,
2400                      int snum, uint32 jobid)
2401 {
2402         const char* sharename = lp_const_servicename(snum);
2403         struct printjob *pjob;
2404         int ret = -1;
2405         struct printif *current_printif = get_printer_fns( snum );
2406         WERROR werr;
2407         TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2408         if (tmp_ctx == NULL) {
2409                 return WERR_NOT_ENOUGH_MEMORY;
2410         }
2411
2412         pjob = print_job_find(tmp_ctx, sharename, jobid);
2413         if (!pjob || !server_info) {
2414                 DEBUG(10, ("print_job_pause: no pjob or user for jobid %u\n",
2415                         (unsigned int)jobid ));
2416                 werr = WERR_INVALID_PARAM;
2417                 goto err_out;
2418         }
2419
2420         if (!pjob->spooled || pjob->sysjob == -1) {
2421                 DEBUG(10, ("print_job_pause: not spooled or bad sysjob = %d for jobid %u\n",
2422                         (int)pjob->sysjob, (unsigned int)jobid ));
2423                 werr = WERR_INVALID_PARAM;
2424                 goto err_out;
2425         }
2426
2427         if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2428             !print_access_check(server_info, msg_ctx, snum,
2429                                 JOB_ACCESS_ADMINISTER)) {
2430                 DEBUG(3, ("pause denied by security descriptor\n"));
2431
2432                 /* BEGIN_ADMIN_LOG */
2433                 sys_adminlog( LOG_ERR,
2434                         "Permission denied-- user not allowed to delete, \
2435 pause, or resume print job. User name: %s. Printer name: %s.",
2436                               uidtoname(server_info->utok.uid),
2437                               lp_printername(snum) );
2438                 /* END_ADMIN_LOG */
2439
2440                 werr = WERR_ACCESS_DENIED;
2441                 goto err_out;
2442         }
2443
2444         /* need to pause the spooled entry */
2445         ret = (*(current_printif->job_pause))(snum, pjob);
2446
2447         if (ret != 0) {
2448                 werr = WERR_INVALID_PARAM;
2449                 goto err_out;
2450         }
2451
2452         /* force update the database */
2453         print_cache_flush(lp_const_servicename(snum));
2454
2455         /* Send a printer notify message */
2456
2457         notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2458                           JOB_STATUS_PAUSED);
2459
2460         /* how do we tell if this succeeded? */
2461         werr = WERR_OK;
2462 err_out:
2463         talloc_free(tmp_ctx);
2464         return werr;
2465 }
2466
2467 /****************************************************************************
2468  Resume a job.
2469 ****************************************************************************/
2470
2471 WERROR print_job_resume(const struct auth_serversupplied_info *server_info,
2472                       struct messaging_context *msg_ctx,
2473                       int snum, uint32 jobid)
2474 {
2475         const char *sharename = lp_const_servicename(snum);
2476         struct printjob *pjob;
2477         int ret;
2478         struct printif *current_printif = get_printer_fns( snum );
2479         WERROR werr;
2480         TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2481         if (tmp_ctx == NULL)
2482                 return WERR_NOT_ENOUGH_MEMORY;
2483
2484         pjob = print_job_find(tmp_ctx, sharename, jobid);
2485         if (!pjob || !server_info) {
2486                 DEBUG(10, ("print_job_resume: no pjob or user for jobid %u\n",
2487                         (unsigned int)jobid ));
2488                 werr = WERR_INVALID_PARAM;
2489                 goto err_out;
2490         }
2491
2492         if (!pjob->spooled || pjob->sysjob == -1) {
2493                 DEBUG(10, ("print_job_resume: not spooled or bad sysjob = %d for jobid %u\n",
2494                         (int)pjob->sysjob, (unsigned int)jobid ));
2495                 werr = WERR_INVALID_PARAM;
2496                 goto err_out;
2497         }
2498
2499         if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
2500             !print_access_check(server_info, msg_ctx, snum,
2501                                 JOB_ACCESS_ADMINISTER)) {
2502                 DEBUG(3, ("resume denied by security descriptor\n"));
2503
2504                 /* BEGIN_ADMIN_LOG */
2505                 sys_adminlog( LOG_ERR,
2506                          "Permission denied-- user not allowed to delete, \
2507 pause, or resume print job. User name: %s. Printer name: %s.",
2508                               uidtoname(server_info->utok.uid),
2509                               lp_printername(snum) );
2510                 /* END_ADMIN_LOG */
2511                 werr = WERR_ACCESS_DENIED;
2512                 goto err_out;
2513         }
2514
2515         ret = (*(current_printif->job_resume))(snum, pjob);
2516
2517         if (ret != 0) {
2518                 werr = WERR_INVALID_PARAM;
2519                 goto err_out;
2520         }
2521
2522         /* force update the database */
2523         print_cache_flush(lp_const_servicename(snum));
2524
2525         /* Send a printer notify message */
2526
2527         notify_job_status(server_event_context(), msg_ctx, sharename, jobid,
2528                           JOB_STATUS_QUEUED);
2529
2530         werr = WERR_OK;
2531 err_out:
2532         talloc_free(tmp_ctx);
2533         return werr;
2534 }
2535
2536 /****************************************************************************
2537  Write to a print file.
2538 ****************************************************************************/
2539
2540 ssize_t print_job_write(struct tevent_context *ev,
2541                         struct messaging_context *msg_ctx,
2542                         int snum, uint32 jobid, const char *buf, size_t size)
2543 {
2544         const char* sharename = lp_const_servicename(snum);
2545         ssize_t return_code;
2546         struct printjob *pjob;
2547         TALLOC_CTX *tmp_ctx = talloc_new(ev);
2548         if (tmp_ctx == NULL) {
2549                 return -1;
2550         }
2551
2552         pjob = print_job_find(tmp_ctx, sharename, jobid);
2553         if (!pjob) {
2554                 return_code = -1;
2555                 goto err_out;
2556         }
2557
2558         /* don't allow another process to get this info - it is meaningless */
2559         if (pjob->pid != sys_getpid()) {
2560                 return_code = -1;
2561                 goto err_out;
2562         }
2563
2564         /* if SMBD is spooling this can't be allowed */
2565         if (pjob->status == PJOB_SMBD_SPOOLING) {
2566                 return_code = -1;
2567                 goto err_out;
2568         }
2569
2570         return_code = write_data(pjob->fd, buf, size);
2571         if (return_code > 0) {
2572                 pjob->size += size;
2573                 pjob_store(ev, msg_ctx, sharename, jobid, pjob);
2574         }
2575 err_out:
2576         talloc_free(tmp_ctx);
2577         return return_code;
2578 }
2579
2580 /****************************************************************************
2581  Get the queue status - do not update if db is out of date.
2582 ****************************************************************************/
2583
2584 static int get_queue_status(const char* sharename, print_status_struct *status)
2585 {
2586         fstring keystr;
2587         TDB_DATA data;
2588         struct tdb_print_db *pdb = get_print_db_byname(sharename);
2589         int len;
2590
2591         if (status) {
2592                 ZERO_STRUCTP(status);
2593         }
2594
2595         if (!pdb)
2596                 return 0;
2597
2598         if (status) {
2599                 fstr_sprintf(keystr, "STATUS/%s", sharename);
2600                 data = tdb_fetch(pdb->tdb, string_tdb_data(keystr));
2601                 if (data.dptr) {
2602                         if (data.dsize == sizeof(print_status_struct))
2603                                 /* this memcpy is ok since the status struct was
2604                                    not packed before storing it in the tdb */
2605                                 memcpy(status, data.dptr, sizeof(print_status_struct));
2606                         SAFE_FREE(data.dptr);
2607                 }
2608         }
2609         len = tdb_fetch_int32(pdb->tdb, "INFO/total_jobs");
2610         release_print_db(pdb);
2611         return (len == -1 ? 0 : len);
2612 }
2613
2614 /****************************************************************************
2615  Determine the number of jobs in a queue.
2616 ****************************************************************************/
2617
2618 int print_queue_length(struct messaging_context *msg_ctx, int snum,
2619                        print_status_struct *pstatus)
2620 {
2621         const char* sharename = lp_const_servicename( snum );
2622         print_status_struct status;
2623         int len;
2624
2625         ZERO_STRUCT( status );
2626
2627         /* make sure the database is up to date */
2628         if (print_cache_expired(lp_const_servicename(snum), True))
2629                 print_queue_update(msg_ctx, snum, False);
2630
2631         /* also fetch the queue status */
2632         memset(&status, 0, sizeof(status));
2633         len = get_queue_status(sharename, &status);
2634
2635         if (pstatus)
2636                 *pstatus = status;
2637
2638         return len;
2639 }
2640
2641 /***************************************************************************
2642  Allocate a jobid. Hold the lock for as short a time as possible.
2643 ***************************************************************************/
2644
2645 static WERROR allocate_print_jobid(struct tdb_print_db *pdb, int snum,
2646                                    const char *sharename, uint32 *pjobid)
2647 {
2648         int i;
2649         uint32 jobid;
2650         enum TDB_ERROR terr;
2651         int ret;
2652
2653         *pjobid = (uint32)-1;
2654
2655         for (i = 0; i < 3; i++) {
2656                 /* Lock the database - only wait 20 seconds. */
2657                 ret = tdb_lock_bystring_with_timeout(pdb->tdb,
2658                                                      "INFO/nextjob", 20);
2659                 if (ret == -1) {
2660                         DEBUG(0, ("allocate_print_jobid: "
2661                                   "Failed to lock printing database %s\n",
2662                                   sharename));
2663                         terr = tdb_error(pdb->tdb);
2664                         return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2665                 }
2666
2667                 if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
2668                         terr = tdb_error(pdb->tdb);
2669                         if (terr != TDB_ERR_NOEXIST) {
2670                                 DEBUG(0, ("allocate_print_jobid: "
2671                                           "Failed to fetch INFO/nextjob "
2672                                           "for print queue %s\n", sharename));
2673                                 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2674                                 return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2675                         }
2676                         DEBUG(10, ("allocate_print_jobid: "
2677                                    "No existing jobid in %s\n", sharename));
2678                         jobid = 0;
2679                 }
2680
2681                 DEBUG(10, ("allocate_print_jobid: "
2682                            "Read jobid %u from %s\n", jobid, sharename));
2683
2684                 jobid = NEXT_JOBID(jobid);
2685
2686                 ret = tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid);
2687                 if (ret == -1) {
2688                         terr = tdb_error(pdb->tdb);
2689                         DEBUG(3, ("allocate_print_jobid: "
2690                                   "Failed to store INFO/nextjob.\n"));
2691                         tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2692                         return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2693                 }
2694
2695                 /* We've finished with the INFO/nextjob lock. */
2696                 tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
2697
2698                 if (!print_job_exists(sharename, jobid)) {
2699                         break;
2700                 }
2701                 DEBUG(10, ("allocate_print_jobid: "
2702                            "Found jobid %u in %s\n", jobid, sharename));
2703         }
2704
2705         if (i > 2) {
2706                 DEBUG(0, ("allocate_print_jobid: "
2707                           "Failed to allocate a print job for queue %s\n",
2708                           sharename));
2709                 /* Probably full... */
2710                 return WERR_NO_SPOOL_SPACE;
2711         }
2712
2713         /* Store a dummy placeholder. */
2714         {
2715                 uint32_t tmp;
2716                 TDB_DATA dum;
2717                 dum.dptr = NULL;
2718                 dum.dsize = 0;
2719                 if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
2720                               TDB_INSERT) == -1) {
2721                         DEBUG(3, ("allocate_print_jobid: "
2722                                   "jobid (%d) failed to store placeholder.\n",
2723                                   jobid ));
2724                         terr = tdb_error(pdb->tdb);
2725                         return ntstatus_to_werror(map_nt_error_from_tdb(terr));
2726                 }
2727         }
2728
2729         *pjobid = jobid;
2730         return WERR_OK;
2731 }
2732
2733 /***************************************************************************
2734  Append a jobid to the 'jobs added' list.
2735 ***************************************************************************/
2736
2737 static bool add_to_jobs_added(struct tdb_print_db *pdb, uint32 jobid)
2738 {
2739         TDB_DATA data;
2740         uint32 store_jobid;
2741
2742         SIVAL(&store_jobid, 0, jobid);
2743         data.dptr = (uint8 *)&store_jobid;
2744         data.dsize = 4;
2745
2746         DEBUG(10,("add_to_jobs_added: Added jobid %u\n", (unsigned int)jobid ));
2747
2748         return (tdb_append(pdb->tdb, string_tdb_data("INFO/jobs_added"),
2749                            data) == 0);
2750 }
2751
2752
2753 /***************************************************************************
2754  Do all checks needed to determine if we can start a job.
2755 ***************************************************************************/
2756
2757 static WERROR print_job_checks(const struct auth_serversupplied_info *server_info,
2758                                struct messaging_context *msg_ctx,
2759                                int snum, int *njobs)
2760 {
2761         const char *sharename = lp_const_servicename(snum);
2762         uint64_t dspace, dsize;
2763         uint64_t minspace;
2764         int ret;
2765
2766         if (!print_access_check(server_info, msg_ctx, snum,
2767                                 PRINTER_ACCESS_USE)) {
2768                 DEBUG(3, ("print_job_checks: "
2769                           "job start denied by security descriptor\n"));
2770                 return WERR_ACCESS_DENIED;
2771         }
2772
2773         if (!print_time_access_check(server_info, msg_ctx, sharename)) {
2774                 DEBUG(3, ("print_job_checks: "
2775                           "job start denied by time check\n"));
2776                 return WERR_ACCESS_DENIED;
2777         }
2778
2779         /* see if we have sufficient disk space */
2780         if (lp_minprintspace(snum)) {
2781                 minspace = lp_minprintspace(snum);
2782                 ret = sys_fsusage(lp_pathname(snum), &dspace, &dsize);
2783                 if (ret == 0 && dspace < 2*minspace) {
2784                         DEBUG(3, ("print_job_checks: "
2785                                   "disk space check failed.\n"));
2786                         return WERR_NO_SPOOL_SPACE;
2787                 }
2788         }
2789
2790         /* for autoloaded printers, check that the printcap entry still exists */
2791         if (lp_autoloaded(snum) && !pcap_printername_ok(sharename)) {
2792                 DEBUG(3, ("print_job_checks: printer name %s check failed.\n",
2793                           sharename));
2794                 return WERR_ACCESS_DENIED;
2795         }
2796
2797         /* Insure the maximum queue size is not violated */
2798         *njobs = print_queue_length(msg_ctx, snum, NULL);
2799         if (*njobs > lp_maxprintjobs(snum)) {
2800                 DEBUG(3, ("print_job_checks: Queue %s number of jobs (%d) "
2801                           "larger than max printjobs per queue (%d).\n",
2802                           sharename, *njobs, lp_maxprintjobs(snum)));
2803                 return WERR_NO_SPOOL_SPACE;
2804         }
2805
2806         return WERR_OK;
2807 }
2808
2809 /***************************************************************************
2810  Create a job file.
2811 ***************************************************************************/
2812
2813 static WERROR print_job_spool_file(int snum, uint32_t jobid,
2814                                    const char *output_file,
2815                                    struct printjob *pjob)
2816 {
2817         WERROR werr;
2818         SMB_STRUCT_STAT st;
2819         const char *path;
2820         int len;
2821
2822         /* if this file is within the printer path, it means that smbd
2823          * is spooling it and will pass us control when it is finished.
2824          * Verify that the file name is ok, within path, and it is
2825          * already already there */
2826         if (output_file) {
2827                 path = lp_pathname(snum);
2828                 len = strlen(path);
2829                 if (strncmp(output_file, path, len) == 0 &&
2830                     (output_file[len - 1] == '/' || output_file[len] == '/')) {
2831
2832                         /* verify path is not too long */
2833                         if (strlen(output_file) >= sizeof(pjob->filename)) {
2834                                 return WERR_INVALID_NAME;
2835                         }
2836
2837                         /* verify that the file exists */
2838                         if (sys_stat(output_file, &st, false) != 0) {
2839                                 return WERR_INVALID_NAME;
2840                         }
2841
2842                         fstrcpy(pjob->filename, output_file);
2843
2844                         DEBUG(3, ("print_job_spool_file:"
2845                                   "External spooling activated"));
2846
2847                         /* we do not open the file until spooling is done */
2848                         pjob->fd = -1;
2849                         pjob->status = PJOB_SMBD_SPOOLING;
2850
2851                         return WERR_OK;
2852                 }
2853         }
2854
2855         slprintf(pjob->filename, sizeof(pjob->filename)-1,
2856                  "%s/%s%.8u.XXXXXX", lp_pathname(snum),
2857                  PRINT_SPOOL_PREFIX, (unsigned int)jobid);
2858         pjob->fd = mkstemp(pjob->filename);
2859
2860         if (pjob->fd == -1) {
2861                 werr = map_werror_from_unix(errno);
2862                 if (W_ERROR_EQUAL(werr, WERR_ACCESS_DENIED)) {
2863                         /* Common setup error, force a report. */
2864                         DEBUG(0, ("print_job_spool_file: "
2865                                   "insufficient permissions to open spool "
2866                                   "file %s.\n", pjob->filename));
2867                 } else {
2868                         /* Normal case, report at level 3 and above. */
2869                         DEBUG(3, ("print_job_spool_file: "
2870                                   "can't open spool file %s\n",
2871                                   pjob->filename));
2872                 }
2873                 return werr;
2874         }
2875
2876         return WERR_OK;
2877 }
2878
2879 /***************************************************************************
2880  Start spooling a job - return the jobid.
2881 ***************************************************************************/
2882
2883 WERROR print_job_start(const struct auth_serversupplied_info *server_info,
2884                        struct messaging_context *msg_ctx,
2885                        const char *clientmachine,
2886                        int snum, const char *docname, const char *filename,
2887                        struct spoolss_DeviceMode *devmode, uint32_t *_jobid)
2888 {
2889         uint32_t jobid;
2890         char *path;
2891         struct printjob pjob;
2892         const char *sharename = lp_const_servicename(snum);
2893         struct tdb_print_db *pdb = get_print_db_byname(sharename);
2894         int njobs;
2895         WERROR werr;
2896
2897         if (!pdb) {
2898                 return WERR_INTERNAL_DB_CORRUPTION;
2899         }
2900
2901         path = lp_pathname(snum);
2902
2903         werr = print_job_checks(server_info, msg_ctx, snum, &njobs);
2904         if (!W_ERROR_IS_OK(werr)) {
2905                 release_print_db(pdb);
2906                 return werr;
2907         }
2908
2909         DEBUG(10, ("print_job_start: "
2910                    "Queue %s number of jobs (%d), max printjobs = %d\n",
2911                    sharename, njobs, lp_maxprintjobs(snum)));
2912
2913         werr = allocate_print_jobid(pdb, snum, sharename, &jobid);
2914         if (!W_ERROR_IS_OK(werr)) {
2915                 goto fail;
2916         }
2917
2918         /* create the database entry */
2919
2920         ZERO_STRUCT(pjob);
2921
2922         pjob.pid = sys_getpid();
2923         pjob.jobid = jobid;
2924         pjob.sysjob = -1;
2925         pjob.fd = -1;
2926         pjob.starttime = time(NULL);
2927         pjob.status = LPQ_SPOOLING;
2928         pjob.size = 0;
2929         pjob.spooled = False;
2930         pjob.smbjob = True;
2931         pjob.devmode = devmode;
2932
2933         fstrcpy(pjob.jobname, docname);
2934
2935         fstrcpy(pjob.clientmachine, clientmachine);
2936
2937         fstrcpy(pjob.user, lp_printjob_username(snum));
2938         standard_sub_advanced(sharename, server_info->sanitized_username,
2939                               path, server_info->utok.gid,
2940                               server_info->sanitized_username,
2941                               server_info->info3->base.domain.string,
2942                               pjob.user, sizeof(pjob.user)-1);
2943         /* ensure NULL termination */
2944         pjob.user[sizeof(pjob.user)-1] = '\0';
2945
2946         fstrcpy(pjob.queuename, lp_const_servicename(snum));
2947
2948         /* we have a job entry - now create the spool file */
2949         werr = print_job_spool_file(snum, jobid, filename, &pjob);
2950         if (!W_ERROR_IS_OK(werr)) {
2951                 goto fail;
2952         }
2953
2954         pjob_store(server_event_context(), msg_ctx, sharename, jobid, &pjob);
2955
2956         /* Update the 'jobs added' entry used by print_queue_status. */
2957         add_to_jobs_added(pdb, jobid);
2958
2959         /* Ensure we keep a rough count of the number of total jobs... */
2960         tdb_change_int32_atomic(pdb->tdb, "INFO/total_jobs", &njobs, 1);
2961
2962         release_print_db(pdb);
2963
2964         *_jobid = jobid;
2965         return WERR_OK;
2966
2967 fail:
2968         if (jobid != -1) {
2969                 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
2970         }
2971
2972         release_print_db(pdb);
2973
2974         DEBUG(3, ("print_job_start: returning fail. "
2975                   "Error = %s\n", win_errstr(werr)));
2976         return werr;
2977 }
2978
2979 /****************************************************************************
2980  Update the number of pages spooled to jobid
2981 ****************************************************************************/
2982
2983 void print_job_endpage(struct messaging_context *msg_ctx,
2984                        int snum, uint32 jobid)
2985 {
2986         const char* sharename = lp_const_servicename(snum);
2987         struct printjob *pjob;
2988         TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
2989         if (tmp_ctx == NULL) {
2990                 return;
2991         }
2992
2993         pjob = print_job_find(tmp_ctx, sharename, jobid);
2994         if (!pjob) {
2995                 goto err_out;
2996         }
2997         /* don't allow another process to get this info - it is meaningless */
2998         if (pjob->pid != sys_getpid()) {
2999                 goto err_out;
3000         }
3001
3002         pjob->page_count++;
3003         pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
3004 err_out:
3005         talloc_free(tmp_ctx);
3006 }
3007
3008 /****************************************************************************
3009  Print a file - called on closing the file. This spools the job.
3010  If normal close is false then we're tearing down the jobs - treat as an
3011  error.
3012 ****************************************************************************/
3013
3014 NTSTATUS print_job_end(struct messaging_context *msg_ctx, int snum,
3015                        uint32 jobid, enum file_close_type close_type)
3016 {
3017         const char* sharename = lp_const_servicename(snum);
3018         struct printjob *pjob;
3019         int ret;
3020         SMB_STRUCT_STAT sbuf;
3021         struct printif *current_printif = get_printer_fns(snum);
3022         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
3023         TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
3024         if (tmp_ctx == NULL) {
3025                 return NT_STATUS_NO_MEMORY;
3026         }
3027
3028         pjob = print_job_find(tmp_ctx, sharename, jobid);
3029         if (!pjob) {
3030                 status = NT_STATUS_PRINT_CANCELLED;
3031                 goto err_out;
3032         }
3033
3034         if (pjob->spooled || pjob->pid != sys_getpid()) {
3035                 status = NT_STATUS_ACCESS_DENIED;
3036                 goto err_out;
3037         }
3038
3039         if (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) {
3040                 if (pjob->status == PJOB_SMBD_SPOOLING) {
3041                         /* take over the file now, smbd is done */
3042                         if (sys_stat(pjob->filename, &sbuf, false) != 0) {
3043                                 status = map_nt_error_from_unix(errno);
3044                                 DEBUG(3, ("print_job_end: "
3045                                           "stat file failed for jobid %d\n",
3046                                           jobid));
3047                                 goto fail;
3048                         }
3049
3050                         pjob->status = LPQ_SPOOLING;
3051
3052                 } else {
3053
3054                         if ((sys_fstat(pjob->fd, &sbuf, false) != 0)) {
3055                                 status = map_nt_error_from_unix(errno);
3056                                 close(pjob->fd);
3057                                 DEBUG(3, ("print_job_end: "
3058                                           "stat file failed for jobid %d\n",
3059                                           jobid));
3060                                 goto fail;
3061                         }
3062
3063                         close(pjob->fd);
3064                 }
3065
3066                 pjob->size = sbuf.st_ex_size;
3067         } else {
3068
3069                 /*
3070                  * Not a normal close, something has gone wrong. Cleanup.
3071                  */
3072                 if (pjob->fd != -1) {
3073                         close(pjob->fd);
3074                 }
3075                 goto fail;
3076         }
3077
3078         /* Technically, this is not quite right. If the printer has a separator
3079          * page turned on, the NT spooler prints the separator page even if the
3080          * print job is 0 bytes. 010215 JRR */
3081         if (pjob->size == 0 || pjob->status == LPQ_DELETING) {
3082                 /* don't bother spooling empty files or something being deleted. */
3083                 DEBUG(5,("print_job_end: canceling spool of %s (%s)\n",
3084                         pjob->filename, pjob->size ? "deleted" : "zero length" ));
3085                 unlink(pjob->filename);
3086                 pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
3087                 return NT_STATUS_OK;
3088         }
3089
3090         ret = (*(current_printif->job_submit))(snum, pjob);
3091
3092         if (ret) {
3093                 status = NT_STATUS_PRINT_CANCELLED;
3094                 goto fail;
3095         }
3096
3097         /* The print job has been successfully handed over to the back-end */
3098
3099         pjob->spooled = True;
3100         pjob->status = LPQ_QUEUED;
3101         pjob_store(server_event_context(), msg_ctx, sharename, jobid, pjob);
3102
3103         /* make sure the database is up to date */
3104         if (print_cache_expired(lp_const_servicename(snum), True))
3105                 print_queue_update(msg_ctx, snum, False);
3106
3107         return NT_STATUS_OK;
3108
3109 fail:
3110
3111         /* The print job was not successfully started. Cleanup */
3112         /* Still need to add proper error return propagation! 010122:JRR */
3113         pjob->fd = -1;
3114         unlink(pjob->filename);
3115         pjob_delete(server_event_context(), msg_ctx, sharename, jobid);
3116 err_out:
3117         talloc_free(tmp_ctx);
3118         return status;
3119 }
3120
3121 /****************************************************************************
3122  Get a snapshot of jobs in the system without traversing.
3123 ****************************************************************************/
3124
3125 static bool get_stored_queue_info(struct messaging_context *msg_ctx,
3126                                   struct tdb_print_db *pdb, int snum,
3127                                   int *pcount, print_queue_struct **ppqueue)
3128 {
3129         TDB_DATA data, cgdata, jcdata;
3130         print_queue_struct *queue = NULL;
3131         uint32 qcount = 0;
3132         uint32 extra_count = 0;
3133         uint32_t changed_count = 0;
3134         int total_count = 0;
3135         size_t len = 0;
3136         uint32 i;
3137         int max_reported_jobs = lp_max_reported_jobs(snum);
3138         bool ret = False;
3139         const char* sharename = lp_servicename(snum);
3140         TALLOC_CTX *tmp_ctx = talloc_new(msg_ctx);
3141         if (tmp_ctx == NULL) {
3142                 return false;
3143         }
3144
3145         /* make sure the database is up to date */
3146         if (print_cache_expired(lp_const_servicename(snum), True))
3147                 print_queue_update(msg_ctx, snum, False);
3148
3149         *pcount = 0;
3150         *ppqueue = NULL;
3151
3152         ZERO_STRUCT(data);
3153         ZERO_STRUCT(cgdata);
3154
3155         /* Get the stored queue data. */
3156         data = tdb_fetch(pdb->tdb, string_tdb_data("INFO/linear_queue_array"));
3157
3158         if (data.dptr && data.dsize >= sizeof(qcount))
3159                 len += tdb_unpack(data.dptr + len, data.dsize - len, "d", &qcount);
3160
3161         /* Get the added jobs list. */
3162         cgdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_added"));
3163         if (cgdata.dptr != NULL && (cgdata.dsize % 4 == 0))
3164                 extra_count = cgdata.dsize/4;
3165
3166         /* Get the changed jobs list. */
3167         jcdata = tdb_fetch(pdb->tdb, string_tdb_data("INFO/jobs_changed"));
3168         if (jcdata.dptr != NULL && (jcdata.dsize % 4 == 0))
3169                 changed_count = jcdata.dsize / 4;
3170
3171         DEBUG(5,("get_stored_queue_info: qcount = %u, extra_count = %u\n", (unsigned int)qcount, (unsigned int)extra_count));
3172
3173         /* Allocate the queue size. */
3174         if (qcount == 0 && extra_count == 0)
3175                 goto out;
3176
3177         if ((queue = SMB_MALLOC_ARRAY(print_queue_struct, qcount + extra_count)) == NULL)
3178                 goto out;
3179
3180         /* Retrieve the linearised queue data. */
3181
3182         for( i  = 0; i < qcount; i++) {
3183                 uint32 qjob, qsize, qpage_count, qstatus, qpriority, qtime;
3184                 len += tdb_unpack(data.dptr + len, data.dsize - len, "ddddddff",
3185                                 &qjob,
3186                                 &qsize,
3187                                 &qpage_count,
3188                                 &qstatus,
3189                                 &qpriority,
3190                                 &qtime,
3191                                 queue[i].fs_user,
3192                                 queue[i].fs_file);
3193                 queue[i].sysjob = qjob;
3194                 queue[i].size = qsize;
3195                 queue[i].page_count = qpage_count;
3196                 queue[i].status = qstatus;
3197                 queue[i].priority = qpriority;
3198                 queue[i].time = qtime;
3199         }
3200
3201         total_count = qcount;
3202
3203         /* Add new jobids to the queue. */
3204         for( i  = 0; i < extra_count; i++) {
3205                 uint32 jobid;
3206                 struct printjob *pjob;
3207
3208                 jobid = IVAL(cgdata.dptr, i*4);
3209                 DEBUG(5,("get_stored_queue_info: added job = %u\n", (unsigned int)jobid));
3210                 pjob = print_job_find(tmp_ctx, lp_const_servicename(snum), jobid);
3211                 if (!pjob) {
3212                         DEBUG(5,("get_stored_queue_info: failed to find added job = %u\n", (unsigned int)jobid));
3213                         remove_from_jobs_added(sharename, jobid);
3214                         continue;
3215                 }
3216
3217                 queue[total_count].sysjob = jobid;
3218                 queue[total_count].size = pjob->size;
3219                 queue[total_count].page_count = pjob->page_count;
3220                 queue[total_count].status = pjob->status;
3221                 queue[total_count].priority = 1;
3222                 queue[total_count].time = pjob->starttime;
3223                 fstrcpy(queue[total_count].fs_user, pjob->user);
3224                 fstrcpy(queue[total_count].fs_file, pjob->jobname);
3225                 total_count++;
3226                 talloc_free(pjob);
3227         }
3228
3229         /* Update the changed jobids. */
3230         for (i = 0; i < changed_count; i++) {
3231                 uint32_t jobid = IVAL(jcdata.dptr, i * 4);
3232                 uint32_t j;
3233                 bool found = false;
3234
3235                 for (j = 0; j < total_count; j++) {
3236                         if (queue[j].sysjob == jobid) {
3237                                 found = true;
3238                                 break;
3239                         }
3240                 }
3241
3242                 if (found) {
3243                         struct printjob *pjob;
3244
3245                         DEBUG(5,("get_stored_queue_info: changed job: %u\n",
3246                                  (unsigned int) jobid));
3247
3248                         pjob = print_job_find(tmp_ctx, sharename, jobid);
3249                         if (pjob == NULL) {
3250                                 DEBUG(5,("get_stored_queue_info: failed to find "
3251                                          "changed job = %u\n",
3252                                          (unsigned int) jobid));
3253                                 remove_from_jobs_changed(sharename, jobid);
3254                                 continue;
3255                         }
3256
3257                         queue[j].sysjob = jobid;
3258                         queue[j].size = pjob->size;
3259                         queue[j].page_count = pjob->page_count;
3260                         queue[j].status = pjob->status;
3261                         queue[j].priority = 1;
3262                         queue[j].time = pjob->starttime;
3263                         fstrcpy(queue[j].fs_user, pjob->user);
3264                         fstrcpy(queue[j].fs_file, pjob->jobname);
3265                         talloc_free(pjob);
3266
3267                         DEBUG(5,("get_stored_queue_info: updated queue[%u], jobid: %u, jobname: %s\n",
3268                                  (unsigned int) j, (unsigned int) jobid, pjob->jobname));
3269                 }
3270
3271                 remove_from_jobs_changed(sharename, jobid);
3272         }
3273
3274         /* Sort the queue by submission time otherwise they are displayed
3275            in hash order. */
3276
3277         TYPESAFE_QSORT(queue, total_count, printjob_comp);
3278
3279         DEBUG(5,("get_stored_queue_info: total_count = %u\n", (unsigned int)total_count));
3280
3281         if (max_reported_jobs && total_count > max_reported_jobs)
3282                 total_count = max_reported_jobs;
3283
3284         *ppqueue = queue;
3285         *pcount = total_count;
3286
3287         ret = True;
3288
3289   out:
3290
3291         SAFE_FREE(data.dptr);
3292         SAFE_FREE(cgdata.dptr);
3293         talloc_free(tmp_ctx);
3294         return ret;
3295 }
3296
3297 /****************************************************************************
3298  Get a printer queue listing.
3299  set queue = NULL and status = NULL if you just want to update the cache
3300 ****************************************************************************/
3301
3302 int print_queue_status(struct messaging_context *msg_ctx, int snum,
3303                        print_queue_struct **ppqueue,
3304                        print_status_struct *status)
3305 {
3306         fstring keystr;
3307         TDB_DATA data, key;
3308         const char *sharename;
3309         struct tdb_print_db *pdb;
3310         int count = 0;
3311
3312         /* make sure the database is up to date */
3313
3314         if (print_cache_expired(lp_const_servicename(snum), True))
3315                 print_queue_update(msg_ctx, snum, False);
3316
3317         /* return if we are done */
3318         if ( !ppqueue || !status )
3319                 return 0;
3320
3321         *ppqueue = NULL;
3322         sharename = lp_const_servicename(snum);
3323         pdb = get_print_db_byname(sharename);
3324
3325         if (!pdb)
3326                 return 0;
3327
3328         /*
3329          * Fetch the queue status.  We must do this first, as there may
3330          * be no jobs in the queue.
3331          */
3332
3333         ZERO_STRUCTP(status);
3334         slprintf(keystr, sizeof(keystr)-1, "STATUS/%s", sharename);
3335         key = string_tdb_data(keystr);
3336
3337         data = tdb_fetch(pdb->tdb, key);
3338         if (data.dptr) {
3339                 if (data.dsize == sizeof(*status)) {
3340                         /* this memcpy is ok since the status struct was
3341                            not packed before storing it in the tdb */
3342                         memcpy(status, data.dptr, sizeof(*status));
3343                 }
3344                 SAFE_FREE(data.dptr);
3345         }
3346
3347         /*
3348          * Now, fetch the print queue information.  We first count the number
3349          * of entries, and then only retrieve the queue if necessary.
3350          */
3351
3352         if (!get_stored_queue_info(msg_ctx, pdb, snum, &count, ppqueue)) {
3353                 release_print_db(pdb);
3354                 return 0;
3355         }
3356
3357         release_print_db(pdb);
3358         return count;
3359 }
3360
3361 /****************************************************************************
3362  Pause a queue.
3363 ****************************************************************************/
3364
3365 WERROR print_queue_pause(const struct auth_serversupplied_info *server_info,
3366                          struct messaging_context *msg_ctx, int snum)
3367 {
3368         int ret;
3369         struct printif *current_printif = get_printer_fns( snum );
3370
3371         if (!print_access_check(server_info, msg_ctx, snum,
3372                                 PRINTER_ACCESS_ADMINISTER)) {
3373                 return WERR_ACCESS_DENIED;
3374         }
3375
3376
3377         become_root();
3378
3379         ret = (*(current_printif->queue_pause))(snum);
3380
3381         unbecome_root();
3382
3383         if (ret != 0) {
3384                 return WERR_INVALID_PARAM;
3385         }
3386
3387         /* force update the database */
3388         print_cache_flush(lp_const_servicename(snum));
3389
3390         /* Send a printer notify message */
3391
3392         notify_printer_status(server_event_context(), msg_ctx, snum,
3393                               PRINTER_STATUS_PAUSED);
3394
3395         return WERR_OK;
3396 }
3397
3398 /****************************************************************************
3399  Resume a queue.
3400 ****************************************************************************/
3401
3402 WERROR print_queue_resume(const struct auth_serversupplied_info *server_info,
3403                           struct messaging_context *msg_ctx, int snum)
3404 {
3405         int ret;
3406         struct printif *current_printif = get_printer_fns( snum );
3407
3408         if (!print_access_check(server_info, msg_ctx, snum,
3409                                 PRINTER_ACCESS_ADMINISTER)) {
3410                 return WERR_ACCESS_DENIED;
3411         }
3412
3413         become_root();
3414
3415         ret = (*(current_printif->queue_resume))(snum);
3416
3417         unbecome_root();
3418
3419         if (ret != 0) {
3420                 return WERR_INVALID_PARAM;
3421         }
3422
3423         /* make sure the database is up to date */
3424         if (print_cache_expired(lp_const_servicename(snum), True))
3425                 print_queue_update(msg_ctx, snum, True);
3426
3427         /* Send a printer notify message */
3428
3429         notify_printer_status(server_event_context(), msg_ctx, snum,
3430                               PRINTER_STATUS_OK);
3431
3432         return WERR_OK;
3433 }
3434
3435 /****************************************************************************
3436  Purge a queue - implemented by deleting all jobs that we can delete.
3437 ****************************************************************************/
3438
3439 WERROR print_queue_purge(const struct auth_serversupplied_info *server_info,
3440                          struct messaging_context *msg_ctx, int snum)
3441 {
3442         print_queue_struct *queue;
3443         print_status_struct status;
3444         int njobs, i;
3445         bool can_job_admin;
3446
3447         /* Force and update so the count is accurate (i.e. not a cached count) */
3448         print_queue_update(msg_ctx, snum, True);
3449
3450         can_job_admin = print_access_check(server_info,
3451                                            msg_ctx,
3452                                            snum,
3453                                            JOB_ACCESS_ADMINISTER);
3454         njobs = print_queue_status(msg_ctx, snum, &queue, &status);
3455
3456         if ( can_job_admin )
3457                 become_root();
3458
3459         for (i=0;i<njobs;i++) {
3460                 bool owner = is_owner(server_info, lp_const_servicename(snum),
3461                                       queue[i].sysjob);
3462
3463                 if (owner || can_job_admin) {
3464                         print_job_delete1(server_event_context(), msg_ctx,
3465                                           snum, queue[i].sysjob);
3466                 }
3467         }
3468
3469         if ( can_job_admin )
3470                 unbecome_root();
3471
3472         /* update the cache */
3473         print_queue_update(msg_ctx, snum, True);
3474
3475         SAFE_FREE(queue);
3476
3477         return WERR_OK;
3478 }