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