s3: Lift the server_messaging_context from get_stored_queue_info
[amitay/samba.git] / source3 / printing / printing.c
index b2ba6c57997ecc345b1cb2b4dc26f6f9aa09b2a2..72e388fda744296f7d7625f95b3d9467cd22fbfd 100644 (file)
@@ -22,6 +22,9 @@
 #include "includes.h"
 #include "printing.h"
 #include "librpc/gen_ndr/messaging.h"
+#include "../librpc/gen_ndr/ndr_spoolss.h"
+#include "nt_printing.h"
+#include "../librpc/gen_ndr/netlogon.h"
 
 extern struct current_user current_user;
 extern userdom_struct current_user_info;
@@ -275,6 +278,89 @@ static TDB_DATA print_key(uint32 jobid, uint32 *tmp)
        return ret;
 }
 
+/****************************************************************************
+ Pack the devicemode to store it in a tdb.
+****************************************************************************/
+static int pack_devicemode(struct spoolss_DeviceMode *devmode, uint8 *buf, int buflen)
+{
+       enum ndr_err_code ndr_err;
+       DATA_BLOB blob;
+       int len = 0;
+
+       if (devmode) {
+               ndr_err = ndr_push_struct_blob(&blob, talloc_tos(),
+                                              devmode,
+                                              (ndr_push_flags_fn_t)
+                                              ndr_push_spoolss_DeviceMode);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       DEBUG(10, ("pack_devicemode: "
+                                  "error encoding spoolss_DeviceMode\n"));
+                       goto done;
+               }
+       } else {
+               ZERO_STRUCT(blob);
+       }
+
+       len = tdb_pack(buf, buflen, "B", blob.length, blob.data);
+
+       if (devmode) {
+               DEBUG(8, ("Packed devicemode [%s]\n", devmode->formname));
+       }
+
+done:
+       return len;
+}
+
+/****************************************************************************
+ Unpack the devicemode to store it in a tdb.
+****************************************************************************/
+static int unpack_devicemode(TALLOC_CTX *mem_ctx,
+                     const uint8 *buf, int buflen,
+                     struct spoolss_DeviceMode **devmode)
+{
+       struct spoolss_DeviceMode *dm;
+       enum ndr_err_code ndr_err;
+       char *data = NULL;
+       int data_len = 0;
+       DATA_BLOB blob;
+       int len = 0;
+
+       *devmode = NULL;
+
+       len = tdb_unpack(buf, buflen, "B", &data_len, &data);
+       if (!data) {
+               return len;
+       }
+
+       dm = talloc_zero(mem_ctx, struct spoolss_DeviceMode);
+       if (!dm) {
+               goto done;
+       }
+
+       blob = data_blob_const(data, data_len);
+
+       ndr_err = ndr_pull_struct_blob(&blob, dm, dm,
+                       (ndr_pull_flags_fn_t)ndr_pull_spoolss_DeviceMode);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               DEBUG(10, ("unpack_devicemode: "
+                          "error parsing spoolss_DeviceMode\n"));
+               goto done;
+       }
+
+       DEBUG(8, ("Unpacked devicemode [%s](%s)\n",
+                 dm->devicename, dm->formname));
+       if (dm->driverextra_data.data) {
+               DEBUG(8, ("with a private section of %d bytes\n",
+                         dm->__driverextra_length));
+       }
+
+       *devmode = dm;
+
+done:
+       SAFE_FREE(data);
+       return len;
+}
+
 /***********************************************************************
  unpack a pjob from a tdb buffer
 ***********************************************************************/
@@ -1402,7 +1488,8 @@ static pid_t background_lpq_updater_pid = -1;
 /****************************************************************************
 main thread of the background lpq updater
 ****************************************************************************/
-void start_background_queue(void)
+void start_background_queue(struct tevent_context *ev,
+                           struct messaging_context *msg_ctx)
 {
        /* Use local variables for this as we don't
         * need to save the parent side of this, just
@@ -1438,9 +1525,7 @@ void start_background_queue(void)
                close(pause_pipe[0]);
                pause_pipe[0] = -1;
 
-               status = reinit_after_fork(server_messaging_context(),
-                                          server_event_context(),
-                                          procid_self(), true);
+               status = reinit_after_fork(msg_ctx, ev, procid_self(), true);
 
                if (!NT_STATUS_IS_OK(status)) {
                        DEBUG(0,("reinit_after_fork() failed\n"));
@@ -1448,7 +1533,7 @@ void start_background_queue(void)
                }
 
                smbd_setup_sig_term_handler();
-               smbd_setup_sig_hup_handler();
+               smbd_setup_sig_hup_handler(ev, msg_ctx);
 
                if (!serverid_register(procid_self(),
                                       FLAG_MSG_GENERAL|FLAG_MSG_SMBD
@@ -1460,12 +1545,10 @@ void start_background_queue(void)
                        exit(1);
                }
 
-               messaging_register(server_messaging_context(), NULL,
-                                  MSG_PRINTER_UPDATE, print_queue_receive);
+               messaging_register(msg_ctx, NULL, MSG_PRINTER_UPDATE,
+                                  print_queue_receive);
 
-               fde = tevent_add_fd(server_event_context(),
-                                   server_event_context(),
-                                   pause_pipe[1], TEVENT_FD_READ,
+               fde = tevent_add_fd(ev, ev, pause_pipe[1], TEVENT_FD_READ,
                                    printing_pause_fd_handler,
                                    NULL);
                if (!fde) {
@@ -1474,7 +1557,7 @@ void start_background_queue(void)
                }
 
                DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
-               ret = tevent_loop_wait(server_event_context());
+               ret = tevent_loop_wait(ev);
                /* should not be reached */
                DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
                         ret, (ret == 0) ? "out of events" : strerror(errno)));
@@ -1488,7 +1571,8 @@ void start_background_queue(void)
 update the internal database from the system print queue for a queue
 ****************************************************************************/
 
-static void print_queue_update(int snum, bool force)
+static void print_queue_update(struct messaging_context *msg_ctx,
+                              int snum, bool force)
 {
        fstring key;
        fstring sharename;
@@ -1607,8 +1691,7 @@ static void print_queue_update(int snum, bool force)
 
        /* finally send the message */
 
-       messaging_send_buf(server_messaging_context(),
-                          pid_to_procid(background_lpq_updater_pid),
+       messaging_send_buf(msg_ctx, pid_to_procid(background_lpq_updater_pid),
                           MSG_PRINTER_UPDATE, (uint8 *)buffer, len);
 
        SAFE_FREE( buffer );
@@ -1814,21 +1897,6 @@ bool print_job_exists(const char* sharename, uint32 jobid)
        return ret;
 }
 
-/****************************************************************************
- Give the fd used for a jobid.
-****************************************************************************/
-
-int print_job_fd(const char* sharename, uint32 jobid)
-{
-       struct printjob *pjob = print_job_find(sharename, jobid);
-       if (!pjob)
-               return -1;
-       /* don't allow another process to get this info - it is meaningless */
-       if (pjob->pid != sys_getpid())
-               return -1;
-       return pjob->fd;
-}
-
 /****************************************************************************
  Give the filename used for a jobid.
  Only valid for the process doing the spooling and when the job
@@ -2040,25 +2108,24 @@ static bool is_owner(struct auth_serversupplied_info *server_info,
  Delete a print job.
 ****************************************************************************/
 
-bool print_job_delete(struct auth_serversupplied_info *server_info, int snum,
-                     uint32 jobid, WERROR *errcode)
+WERROR print_job_delete(struct auth_serversupplied_info *server_info,
+                       struct messaging_context *msg_ctx,
+                       int snum, uint32_t jobid)
 {
-       const char* sharename = lp_const_servicename( snum );
+       const char* sharename = lp_const_servicename(snum);
        struct printjob *pjob;
        bool    owner;
        char    *fname;
 
-       *errcode = WERR_OK;
-
        owner = is_owner(server_info, lp_const_servicename(snum), jobid);
 
        /* Check access against security descriptor or whether the user
           owns their job. */
 
        if (!owner &&
-           !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
+           !print_access_check(server_info, msg_ctx, snum,
+                               JOB_ACCESS_ADMINISTER)) {
                DEBUG(3, ("delete denied by security descriptor\n"));
-               *errcode = WERR_ACCESS_DENIED;
 
                /* BEGIN_ADMIN_LOG */
                sys_adminlog( LOG_ERR,
@@ -2068,7 +2135,7 @@ pause, or resume print job. User name: %s. Printer name: %s.",
                              lp_printername(snum) );
                /* END_ADMIN_LOG */
 
-               return False;
+               return WERR_ACCESS_DENIED;
        }
 
        /*
@@ -2078,39 +2145,40 @@ pause, or resume print job. User name: %s. Printer name: %s.",
         * spool file & return.
         */
 
-       if ( (fname = print_job_fname( sharename, jobid )) != NULL )
-       {
+       fname = print_job_fname(sharename, jobid);
+       if (fname != NULL) {
                /* remove the spool file */
-               DEBUG(10,("print_job_delete: Removing spool file [%s]\n", fname ));
-               if ( unlink( fname ) == -1 ) {
-                       *errcode = map_werror_from_unix(errno);
-                       return False;
+               DEBUG(10, ("print_job_delete: "
+                          "Removing spool file [%s]\n", fname));
+               if (unlink(fname) == -1) {
+                       return map_werror_from_unix(errno);
                }
        }
 
        if (!print_job_delete1(snum, jobid)) {
-               *errcode = WERR_ACCESS_DENIED;
-               return False;
+               return WERR_ACCESS_DENIED;
        }
 
        /* force update the database and say the delete failed if the
            job still exists */
 
-       print_queue_update(snum, True);
+       print_queue_update(msg_ctx, snum, True);
 
        pjob = print_job_find(sharename, jobid);
-       if ( pjob && (pjob->status != LPQ_DELETING) )
-               *errcode = WERR_ACCESS_DENIED;
+       if (pjob && (pjob->status != LPQ_DELETING)) {
+               return WERR_ACCESS_DENIED;
+       }
 
-       return (pjob == NULL );
+       return WERR_PRINTER_HAS_JOBS_QUEUED;
 }
 
 /****************************************************************************
  Pause a job.
 ****************************************************************************/
 
-bool print_job_pause(struct auth_serversupplied_info *server_info, int snum,
-                    uint32 jobid, WERROR *errcode)
+bool print_job_pause(struct auth_serversupplied_info *server_info,
+                    struct messaging_context *msg_ctx,
+                    int snum, uint32 jobid, WERROR *errcode)
 {
        const char* sharename = lp_const_servicename(snum);
        struct printjob *pjob;
@@ -2132,7 +2200,8 @@ bool print_job_pause(struct auth_serversupplied_info *server_info, int snum,
        }
 
        if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
-           !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
+           !print_access_check(server_info, msg_ctx, snum,
+                               JOB_ACCESS_ADMINISTER)) {
                DEBUG(3, ("pause denied by security descriptor\n"));
 
                /* BEGIN_ADMIN_LOG */
@@ -2171,8 +2240,9 @@ pause, or resume print job. User name: %s. Printer name: %s.",
  Resume a job.
 ****************************************************************************/
 
-bool print_job_resume(struct auth_serversupplied_info *server_info, int snum,
-                     uint32 jobid, WERROR *errcode)
+bool print_job_resume(struct auth_serversupplied_info *server_info,
+                     struct messaging_context *msg_ctx,
+                     int snum, uint32 jobid, WERROR *errcode)
 {
        const char *sharename = lp_const_servicename(snum);
        struct printjob *pjob;
@@ -2194,7 +2264,8 @@ bool print_job_resume(struct auth_serversupplied_info *server_info, int snum,
        }
 
        if (!is_owner(server_info, lp_const_servicename(snum), jobid) &&
-           !print_access_check(server_info, snum, JOB_ACCESS_ADMINISTER)) {
+           !print_access_check(server_info, msg_ctx, snum,
+                               JOB_ACCESS_ADMINISTER)) {
                DEBUG(3, ("resume denied by security descriptor\n"));
                *errcode = WERR_ACCESS_DENIED;
 
@@ -2243,6 +2314,11 @@ ssize_t print_job_write(int snum, uint32 jobid, const char *buf, SMB_OFF_T pos,
        if (pjob->pid != sys_getpid())
                return -1;
 
+       /* if SMBD is spooling this can't be allowed */
+       if (pjob->status == PJOB_SMBD_SPOOLING) {
+               return -1;
+       }
+
        return_code = write_data_at_offset(pjob->fd, buf, size, pos);
 
        if (return_code>0) {
@@ -2290,7 +2366,8 @@ static int get_queue_status(const char* sharename, print_status_struct *status)
  Determine the number of jobs in a queue.
 ****************************************************************************/
 
-int print_queue_length(int snum, print_status_struct *pstatus)
+int print_queue_length(struct messaging_context *msg_ctx, int snum,
+                      print_status_struct *pstatus)
 {
        const char* sharename = lp_const_servicename( snum );
        print_status_struct status;
@@ -2300,7 +2377,7 @@ int print_queue_length(int snum, print_status_struct *pstatus)
 
        /* make sure the database is up to date */
        if (print_cache_expired(lp_const_servicename(snum), True))
-               print_queue_update(snum, False);
+               print_queue_update(msg_ctx, snum, False);
 
        /* also fetch the queue status */
        memset(&status, 0, sizeof(status));
@@ -2316,39 +2393,54 @@ int print_queue_length(int snum, print_status_struct *pstatus)
  Allocate a jobid. Hold the lock for as short a time as possible.
 ***************************************************************************/
 
-static bool allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char *sharename, uint32 *pjobid)
+static WERROR allocate_print_jobid(struct tdb_print_db *pdb, int snum,
+                                  const char *sharename, uint32 *pjobid)
 {
        int i;
        uint32 jobid;
+       enum TDB_ERROR terr;
+       int ret;
 
        *pjobid = (uint32)-1;
 
        for (i = 0; i < 3; i++) {
                /* Lock the database - only wait 20 seconds. */
-               if (tdb_lock_bystring_with_timeout(pdb->tdb, "INFO/nextjob", 20) == -1) {
-                       DEBUG(0,("allocate_print_jobid: failed to lock printing database %s\n", sharename));
-                       return False;
+               ret = tdb_lock_bystring_with_timeout(pdb->tdb,
+                                                    "INFO/nextjob", 20);
+               if (ret == -1) {
+                       DEBUG(0, ("allocate_print_jobid: "
+                                 "Failed to lock printing database %s\n",
+                                 sharename));
+                       terr = tdb_error(pdb->tdb);
+                       return ntstatus_to_werror(map_nt_error_from_tdb(terr));
                }
 
                if (!tdb_fetch_uint32(pdb->tdb, "INFO/nextjob", &jobid)) {
-                       if (tdb_error(pdb->tdb) != TDB_ERR_NOEXIST) {
-                               DEBUG(0, ("allocate_print_jobid: failed to fetch INFO/nextjob for print queue %s\n",
-                                       sharename));
+                       terr = tdb_error(pdb->tdb);
+                       if (terr != TDB_ERR_NOEXIST) {
+                               DEBUG(0, ("allocate_print_jobid: "
+                                         "Failed to fetch INFO/nextjob "
+                                         "for print queue %s\n", sharename));
                                tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
-                               return False;
+                               return ntstatus_to_werror(map_nt_error_from_tdb(terr));
                        }
-                       DEBUG(10,("allocate_print_jobid: no existing jobid in %s\n", sharename));
+                       DEBUG(10, ("allocate_print_jobid: "
+                                  "No existing jobid in %s\n", sharename));
                        jobid = 0;
                }
 
-               DEBUG(10,("allocate_print_jobid: read jobid %u from %s\n", jobid, sharename));
+               DEBUG(10, ("allocate_print_jobid: "
+                          "Read jobid %u from %s\n", jobid, sharename));
 
                jobid = NEXT_JOBID(jobid);
 
-               if (tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid)==-1) {
-                       DEBUG(3, ("allocate_print_jobid: failed to store INFO/nextjob.\n"));
+               ret = tdb_store_int32(pdb->tdb, "INFO/nextjob", jobid);
+               if (ret == -1) {
+                       terr = tdb_error(pdb->tdb);
+                       DEBUG(3, ("allocate_print_jobid: "
+                                 "Failed to store INFO/nextjob.\n"));
                        tdb_unlock_bystring(pdb->tdb, "INFO/nextjob");
-                       return False;
+                       return ntstatus_to_werror(map_nt_error_from_tdb(terr));
                }
 
                /* We've finished with the INFO/nextjob lock. */
@@ -2357,15 +2449,16 @@ static bool allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char
                if (!print_job_exists(sharename, jobid)) {
                        break;
                }
-               DEBUG(10,("allocate_print_jobid: found jobid %u in %s\n", jobid, sharename));
+               DEBUG(10, ("allocate_print_jobid: "
+                          "Found jobid %u in %s\n", jobid, sharename));
        }
 
        if (i > 2) {
-               DEBUG(0, ("allocate_print_jobid: failed to allocate a print job for queue %s\n",
-                       sharename));
+               DEBUG(0, ("allocate_print_jobid: "
+                         "Failed to allocate a print job for queue %s\n",
+                         sharename));
                /* Probably full... */
-               errno = ENOSPC;
-               return False;
+               return WERR_NO_SPOOL_SPACE;
        }
 
        /* Store a dummy placeholder. */
@@ -2376,14 +2469,16 @@ static bool allocate_print_jobid(struct tdb_print_db *pdb, int snum, const char
                dum.dsize = 0;
                if (tdb_store(pdb->tdb, print_key(jobid, &tmp), dum,
                              TDB_INSERT) == -1) {
-                       DEBUG(3, ("allocate_print_jobid: jobid (%d) failed to store placeholder.\n",
-                               jobid ));
-                       return False;
+                       DEBUG(3, ("allocate_print_jobid: "
+                                 "jobid (%d) failed to store placeholder.\n",
+                                 jobid ));
+                       terr = tdb_error(pdb->tdb);
+                       return ntstatus_to_werror(map_nt_error_from_tdb(terr));
                }
        }
 
        *pjobid = jobid;
-       return True;
+       return WERR_OK;
 }
 
 /***************************************************************************
@@ -2405,73 +2500,170 @@ static bool add_to_jobs_changed(struct tdb_print_db *pdb, uint32 jobid)
                           data) == 0);
 }
 
+
 /***************************************************************************
Start spooling a job - return the jobid.
Do all checks needed to determine if we can start a job.
 ***************************************************************************/
 
-uint32 print_job_start(struct auth_serversupplied_info *server_info, int snum,
-                      const char *jobname, struct spoolss_DeviceMode *devmode )
+static WERROR print_job_checks(struct auth_serversupplied_info *server_info,
+                              struct messaging_context *msg_ctx,
+                              int snum, int *njobs)
 {
-       uint32 jobid;
-       char *path;
-       struct printjob pjob;
        const char *sharename = lp_const_servicename(snum);
-       struct tdb_print_db *pdb = get_print_db_byname(sharename);
-       int njobs;
-
-       errno = 0;
-
-       if (!pdb)
-               return (uint32)-1;
+       uint64_t dspace, dsize;
+       uint64_t minspace;
+       int ret;
 
-       if (!print_access_check(server_info, snum, PRINTER_ACCESS_USE)) {
-               DEBUG(3, ("print_job_start: job start denied by security descriptor\n"));
-               release_print_db(pdb);
-               return (uint32)-1;
+       if (!print_access_check(server_info, msg_ctx, snum,
+                               PRINTER_ACCESS_USE)) {
+               DEBUG(3, ("print_job_checks: "
+                         "job start denied by security descriptor\n"));
+               return WERR_ACCESS_DENIED;
        }
 
-       if (!print_time_access_check(server_info, lp_servicename(snum))) {
-               DEBUG(3, ("print_job_start: job start denied by time check\n"));
-               release_print_db(pdb);
-               return (uint32)-1;
+       if (!print_time_access_check(server_info, msg_ctx, sharename)) {
+               DEBUG(3, ("print_job_checks: "
+                         "job start denied by time check\n"));
+               return WERR_ACCESS_DENIED;
        }
 
-       path = lp_pathname(snum);
-
        /* see if we have sufficient disk space */
        if (lp_minprintspace(snum)) {
-               uint64_t dspace, dsize;
-               if (sys_fsusage(path, &dspace, &dsize) == 0 &&
-                   dspace < 2*(uint64_t)lp_minprintspace(snum)) {
-                       DEBUG(3, ("print_job_start: disk space check failed.\n"));
-                       release_print_db(pdb);
-                       errno = ENOSPC;
-                       return (uint32)-1;
+               minspace = lp_minprintspace(snum);
+               ret = sys_fsusage(lp_pathname(snum), &dspace, &dsize);
+               if (ret == 0 && dspace < 2*minspace) {
+                       DEBUG(3, ("print_job_checks: "
+                                 "disk space check failed.\n"));
+                       return WERR_NO_SPOOL_SPACE;
                }
        }
 
        /* for autoloaded printers, check that the printcap entry still exists */
-       if (lp_autoloaded(snum) && !pcap_printername_ok(lp_const_servicename(snum))) {
-               DEBUG(3, ("print_job_start: printer name %s check failed.\n", lp_const_servicename(snum) ));
-               release_print_db(pdb);
-               errno = ENOENT;
-               return (uint32)-1;
+       if (lp_autoloaded(snum) && !pcap_printername_ok(sharename)) {
+               DEBUG(3, ("print_job_checks: printer name %s check failed.\n",
+                         sharename));
+               return WERR_ACCESS_DENIED;
        }
 
        /* Insure the maximum queue size is not violated */
-       if ((njobs = print_queue_length(snum,NULL)) > lp_maxprintjobs(snum)) {
-               DEBUG(3, ("print_job_start: Queue %s number of jobs (%d) larger than max printjobs per queue (%d).\n",
-                       sharename, njobs, lp_maxprintjobs(snum) ));
+       *njobs = print_queue_length(msg_ctx, snum, NULL);
+       if (*njobs > lp_maxprintjobs(snum)) {
+               DEBUG(3, ("print_job_checks: Queue %s number of jobs (%d) "
+                         "larger than max printjobs per queue (%d).\n",
+                         sharename, *njobs, lp_maxprintjobs(snum)));
+               return WERR_NO_SPOOL_SPACE;
+       }
+
+       return WERR_OK;
+}
+
+/***************************************************************************
+ Create a job file.
+***************************************************************************/
+
+static WERROR print_job_spool_file(int snum, uint32_t jobid,
+                                  const char *output_file,
+                                  struct printjob *pjob)
+{
+       WERROR werr;
+       SMB_STRUCT_STAT st;
+       const char *path;
+       int len;
+
+       /* if this file is within the printer path, it means that smbd
+        * is spooling it and will pass us control when it is finished.
+        * Verify that the file name is ok, within path, and it is
+        * already already there */
+       if (output_file) {
+               path = lp_pathname(snum);
+               len = strlen(path);
+               if (strncmp(output_file, path, len) == 0 &&
+                   (output_file[len - 1] == '/' || output_file[len] == '/')) {
+
+                       /* verify path is not too long */
+                       if (strlen(output_file) >= sizeof(pjob->filename)) {
+                               return WERR_INVALID_NAME;
+                       }
+
+                       /* verify that the file exists */
+                       if (sys_stat(output_file, &st, false) != 0) {
+                               return WERR_INVALID_NAME;
+                       }
+
+                       fstrcpy(pjob->filename, output_file);
+
+                       DEBUG(3, ("print_job_spool_file:"
+                                 "External spooling activated"));
+
+                       /* we do not open the file until spooling is done */
+                       pjob->fd = -1;
+                       pjob->status = PJOB_SMBD_SPOOLING;
+
+                       return WERR_OK;
+               }
+       }
+
+       slprintf(pjob->filename, sizeof(pjob->filename)-1,
+                "%s/%s%.8u.XXXXXX", lp_pathname(snum),
+                PRINT_SPOOL_PREFIX, (unsigned int)jobid);
+       pjob->fd = mkstemp(pjob->filename);
+
+       if (pjob->fd == -1) {
+               werr = map_werror_from_unix(errno);
+               if (W_ERROR_EQUAL(werr, WERR_ACCESS_DENIED)) {
+                       /* Common setup error, force a report. */
+                       DEBUG(0, ("print_job_spool_file: "
+                                 "insufficient permissions to open spool "
+                                 "file %s.\n", pjob->filename));
+               } else {
+                       /* Normal case, report at level 3 and above. */
+                       DEBUG(3, ("print_job_spool_file: "
+                                 "can't open spool file %s\n",
+                                 pjob->filename));
+               }
+               return werr;
+       }
+
+       return WERR_OK;
+}
+
+/***************************************************************************
+ Start spooling a job - return the jobid.
+***************************************************************************/
+
+WERROR print_job_start(struct auth_serversupplied_info *server_info,
+                      struct messaging_context *msg_ctx,
+                      int snum, const char *docname, const char *filename,
+                      struct spoolss_DeviceMode *devmode, uint32_t *_jobid)
+{
+       uint32_t jobid;
+       char *path;
+       struct printjob pjob;
+       const char *sharename = lp_const_servicename(snum);
+       struct tdb_print_db *pdb = get_print_db_byname(sharename);
+       int njobs;
+       WERROR werr;
+
+       if (!pdb) {
+               return WERR_INTERNAL_DB_CORRUPTION;
+       }
+
+       path = lp_pathname(snum);
+
+       werr = print_job_checks(server_info, msg_ctx, snum, &njobs);
+       if (!W_ERROR_IS_OK(werr)) {
                release_print_db(pdb);
-               errno = ENOSPC;
-               return (uint32)-1;
+               return werr;
        }
 
-       DEBUG(10,("print_job_start: Queue %s number of jobs (%d), max printjobs = %d\n",
-               sharename, njobs, lp_maxprintjobs(snum) ));
+       DEBUG(10, ("print_job_start: "
+                  "Queue %s number of jobs (%d), max printjobs = %d\n",
+                  sharename, njobs, lp_maxprintjobs(snum)));
 
-       if (!allocate_print_jobid(pdb, snum, sharename, &jobid))
+       werr = allocate_print_jobid(pdb, snum, sharename, &jobid);
+       if (!W_ERROR_IS_OK(werr)) {
                goto fail;
+       }
 
        /* create the database entry */
 
@@ -2487,7 +2679,7 @@ uint32 print_job_start(struct auth_serversupplied_info *server_info, int snum,
        pjob.smbjob = True;
        pjob.devmode = devmode;
 
-       fstrcpy(pjob.jobname, jobname);
+       fstrcpy(pjob.jobname, docname);
 
        fstrcpy(pjob.user, lp_printjob_username(snum));
        standard_sub_advanced(sharename, server_info->sanitized_username,
@@ -2501,20 +2693,8 @@ uint32 print_job_start(struct auth_serversupplied_info *server_info, int snum,
        fstrcpy(pjob.queuename, lp_const_servicename(snum));
 
        /* we have a job entry - now create the spool file */
-       slprintf(pjob.filename, sizeof(pjob.filename)-1, "%s/%s%.8u.XXXXXX",
-                path, PRINT_SPOOL_PREFIX, (unsigned int)jobid);
-       pjob.fd = mkstemp(pjob.filename);
-
-       if (pjob.fd == -1) {
-               if (errno == EACCES) {
-                       /* Common setup error, force a report. */
-                       DEBUG(0, ("print_job_start: insufficient permissions \
-to open spool file %s.\n", pjob.filename));
-               } else {
-                       /* Normal case, report at level 3 and above. */
-                       DEBUG(3, ("print_job_start: can't open spool file %s,\n", pjob.filename));
-                       DEBUGADD(3, ("errno = %d (%s).\n", errno, strerror(errno)));
-               }
+       werr = print_job_spool_file(snum, jobid, filename, &pjob);
+       if (!W_ERROR_IS_OK(werr)) {
                goto fail;
        }
 
@@ -2528,16 +2708,19 @@ to open spool file %s.\n", pjob.filename));
 
        release_print_db(pdb);
 
-       return jobid;
+       *_jobid = jobid;
+       return WERR_OK;
 
- fail:
-       if (jobid != -1)
+fail:
+       if (jobid != -1) {
                pjob_delete(sharename, jobid);
+       }
 
        release_print_db(pdb);
 
-       DEBUG(3, ("print_job_start: returning fail. Error = %s\n", strerror(errno) ));
-       return (uint32)-1;
+       DEBUG(3, ("print_job_start: returning fail. "
+                 "Error = %s\n", win_errstr(werr)));
+       return werr;
 }
 
 /****************************************************************************
@@ -2566,36 +2749,62 @@ void print_job_endpage(int snum, uint32 jobid)
  error.
 ****************************************************************************/
 
-bool print_job_end(int snum, uint32 jobid, enum file_close_type close_type)
+NTSTATUS print_job_end(struct messaging_context *msg_ctx, int snum,
+                      uint32 jobid, enum file_close_type close_type)
 {
        const char* sharename = lp_const_servicename(snum);
        struct printjob *pjob;
        int ret;
        SMB_STRUCT_STAT sbuf;
        struct printif *current_printif = get_printer_fns( snum );
+       NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
 
        pjob = print_job_find(sharename, jobid);
 
-       if (!pjob)
-               return False;
+       if (!pjob) {
+               return NT_STATUS_PRINT_CANCELLED;
+       }
 
-       if (pjob->spooled || pjob->pid != sys_getpid())
-               return False;
+       if (pjob->spooled || pjob->pid != sys_getpid()) {
+               return NT_STATUS_ACCESS_DENIED;
+       }
+
+       if (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) {
+               if (pjob->status == PJOB_SMBD_SPOOLING) {
+                       /* take over the file now, smbd is done */
+                       if (sys_stat(pjob->filename, &sbuf, false) != 0) {
+                               status = map_nt_error_from_unix(errno);
+                               DEBUG(3, ("print_job_end: "
+                                         "stat file failed for jobid %d\n",
+                                         jobid));
+                               goto fail;
+                       }
+
+                       pjob->status = LPQ_SPOOLING;
+
+               } else {
+
+                       if ((sys_fstat(pjob->fd, &sbuf, false) != 0)) {
+                               status = map_nt_error_from_unix(errno);
+                               close(pjob->fd);
+                               DEBUG(3, ("print_job_end: "
+                                         "stat file failed for jobid %d\n",
+                                         jobid));
+                               goto fail;
+                       }
+
+                       close(pjob->fd);
+               }
 
-       if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
-           (sys_fstat(pjob->fd, &sbuf, false) == 0)) {
                pjob->size = sbuf.st_ex_size;
-               close(pjob->fd);
-               pjob->fd = -1;
        } else {
 
                /*
-                * Not a normal close or we couldn't stat the job file,
-                * so something has gone wrong. Cleanup.
+                * Not a normal close, something has gone wrong. Cleanup.
                 */
-               close(pjob->fd);
-               pjob->fd = -1;
-               DEBUG(3,("print_job_end: failed to stat file for jobid %d\n", jobid ));
+               if (pjob->fd != -1) {
+                       close(pjob->fd);
+               }
                goto fail;
        }
 
@@ -2608,13 +2817,15 @@ bool print_job_end(int snum, uint32 jobid, enum file_close_type close_type)
                        pjob->filename, pjob->size ? "deleted" : "zero length" ));
                unlink(pjob->filename);
                pjob_delete(sharename, jobid);
-               return True;
+               return NT_STATUS_OK;
        }
 
        ret = (*(current_printif->job_submit))(snum, pjob);
 
-       if (ret)
+       if (ret) {
+               status = NT_STATUS_PRINT_CANCELLED;
                goto fail;
+       }
 
        /* The print job has been successfully handed over to the back-end */
 
@@ -2624,24 +2835,27 @@ bool print_job_end(int snum, uint32 jobid, enum file_close_type close_type)
 
        /* make sure the database is up to date */
        if (print_cache_expired(lp_const_servicename(snum), True))
-               print_queue_update(snum, False);
+               print_queue_update(msg_ctx, snum, False);
 
-       return True;
+       return NT_STATUS_OK;
 
 fail:
 
        /* The print job was not successfully started. Cleanup */
        /* Still need to add proper error return propagation! 010122:JRR */
+       pjob->fd = -1;
        unlink(pjob->filename);
        pjob_delete(sharename, jobid);
-       return False;
+       return status;
 }
 
 /****************************************************************************
  Get a snapshot of jobs in the system without traversing.
 ****************************************************************************/
 
-static bool get_stored_queue_info(struct tdb_print_db *pdb, int snum, int *pcount, print_queue_struct **ppqueue)
+static bool get_stored_queue_info(struct messaging_context *msg_ctx,
+                                 struct tdb_print_db *pdb, int snum,
+                                 int *pcount, print_queue_struct **ppqueue)
 {
        TDB_DATA data, cgdata;
        print_queue_struct *queue = NULL;
@@ -2656,7 +2870,7 @@ static bool get_stored_queue_info(struct tdb_print_db *pdb, int snum, int *pcoun
 
        /* make sure the database is up to date */
        if (print_cache_expired(lp_const_servicename(snum), True))
-               print_queue_update(snum, False);
+               print_queue_update(msg_ctx, snum, False);
 
        *pcount = 0;
        *ppqueue = NULL;
@@ -2772,7 +2986,7 @@ int print_queue_status(int snum,
        /* make sure the database is up to date */
 
        if (print_cache_expired(lp_const_servicename(snum), True))
-               print_queue_update(snum, False);
+               print_queue_update(server_messaging_context(), snum, False);
 
        /* return if we are done */
        if ( !ppqueue || !status )
@@ -2809,7 +3023,8 @@ int print_queue_status(int snum,
         * of entries, and then only retrieve the queue if necessary.
         */
 
-       if (!get_stored_queue_info(pdb, snum, &count, ppqueue)) {
+       if (!get_stored_queue_info(server_messaging_context(), pdb, snum,
+                                  &count, ppqueue)) {
                release_print_db(pdb);
                return 0;
        }
@@ -2822,12 +3037,13 @@ int print_queue_status(int snum,
  Pause a queue.
 ****************************************************************************/
 
-WERROR print_queue_pause(struct auth_serversupplied_info *server_info, int snum)
+WERROR print_queue_pause(struct auth_serversupplied_info *server_info,
+                        struct messaging_context *msg_ctx, int snum)
 {
        int ret;
        struct printif *current_printif = get_printer_fns( snum );
 
-       if (!print_access_check(server_info, snum,
+       if (!print_access_check(server_info, msg_ctx, snum,
                                PRINTER_ACCESS_ADMINISTER)) {
                return WERR_ACCESS_DENIED;
        }
@@ -2857,12 +3073,13 @@ WERROR print_queue_pause(struct auth_serversupplied_info *server_info, int snum)
  Resume a queue.
 ****************************************************************************/
 
-WERROR print_queue_resume(struct auth_serversupplied_info *server_info, int snum)
+WERROR print_queue_resume(struct auth_serversupplied_info *server_info,
+                         struct messaging_context *msg_ctx, int snum)
 {
        int ret;
        struct printif *current_printif = get_printer_fns( snum );
 
-       if (!print_access_check(server_info, snum,
+       if (!print_access_check(server_info, msg_ctx, snum,
                                PRINTER_ACCESS_ADMINISTER)) {
                return WERR_ACCESS_DENIED;
        }
@@ -2879,7 +3096,7 @@ WERROR print_queue_resume(struct auth_serversupplied_info *server_info, int snum
 
        /* make sure the database is up to date */
        if (print_cache_expired(lp_const_servicename(snum), True))
-               print_queue_update(snum, True);
+               print_queue_update(msg_ctx, snum, True);
 
        /* Send a printer notify message */
 
@@ -2892,7 +3109,8 @@ WERROR print_queue_resume(struct auth_serversupplied_info *server_info, int snum
  Purge a queue - implemented by deleting all jobs that we can delete.
 ****************************************************************************/
 
-WERROR print_queue_purge(struct auth_serversupplied_info *server_info, int snum)
+WERROR print_queue_purge(struct auth_serversupplied_info *server_info,
+                        struct messaging_context *msg_ctx, int snum)
 {
        print_queue_struct *queue;
        print_status_struct status;
@@ -2900,9 +3118,11 @@ WERROR print_queue_purge(struct auth_serversupplied_info *server_info, int snum)
        bool can_job_admin;
 
        /* Force and update so the count is accurate (i.e. not a cached count) */
-       print_queue_update(snum, True);
+       print_queue_update(msg_ctx, snum, True);
 
-       can_job_admin = print_access_check(server_info, snum,
+       can_job_admin = print_access_check(server_info,
+                                          msg_ctx,
+                                          snum,
                                           JOB_ACCESS_ADMINISTER);
        njobs = print_queue_status(snum, &queue, &status);
 
@@ -2922,7 +3142,7 @@ WERROR print_queue_purge(struct auth_serversupplied_info *server_info, int snum)
                unbecome_root();
 
        /* update the cache */
-       print_queue_update( snum, True );
+       print_queue_update(msg_ctx, snum, True);
 
        SAFE_FREE(queue);