s3: Lift the server_messaging_context from check_reload
[amitay/samba.git] / source3 / smbd / process.c
index 485439a089648f76bccda6b43d3a0dcb439b6176..1d00e12c7e7577216b76b06a91e77271870a664c 100644 (file)
 #include "../librpc/gen_ndr/srv_svcctl.h"
 #include "../librpc/gen_ndr/srv_winreg.h"
 #include "../librpc/gen_ndr/srv_wkssvc.h"
+#include "librpc/gen_ndr/messaging.h"
+#include "printing/nt_printing_migrate.h"
 
 extern bool global_machine_password_needs_changing;
 
 static void construct_reply_common(struct smb_request *req, const char *inbuf,
                                   char *outbuf);
+static struct pending_message_list *get_deferred_open_message_smb(uint64_t mid);
 
 static bool smbd_lock_socket_internal(struct smbd_server_connection *sconn)
 {
        bool ok;
 
-       if (smbd_server_conn->smb1.echo_handler.socket_lock_fd == -1) {
+       if (sconn->smb1.echo_handler.socket_lock_fd == -1) {
                return true;
        }
 
-       smbd_server_conn->smb1.echo_handler.ref_count++;
+       sconn->smb1.echo_handler.ref_count++;
 
-       if (smbd_server_conn->smb1.echo_handler.ref_count > 1) {
+       if (sconn->smb1.echo_handler.ref_count > 1) {
                return true;
        }
 
        DEBUG(10,("pid[%d] wait for socket lock\n", (int)sys_getpid()));
 
-       ok = fcntl_lock(smbd_server_conn->smb1.echo_handler.socket_lock_fd,
+       ok = fcntl_lock(sconn->smb1.echo_handler.socket_lock_fd,
                        SMB_F_SETLKW, 0, 0, F_WRLCK);
        if (!ok) {
                return false;
@@ -78,17 +81,17 @@ static bool smbd_unlock_socket_internal(struct smbd_server_connection *sconn)
 {
        bool ok;
 
-       if (smbd_server_conn->smb1.echo_handler.socket_lock_fd == -1) {
+       if (sconn->smb1.echo_handler.socket_lock_fd == -1) {
                return true;
        }
 
-       smbd_server_conn->smb1.echo_handler.ref_count--;
+       sconn->smb1.echo_handler.ref_count--;
 
-       if (smbd_server_conn->smb1.echo_handler.ref_count > 0) {
+       if (sconn->smb1.echo_handler.ref_count > 0) {
                return true;
        }
 
-       ok = fcntl_lock(smbd_server_conn->smb1.echo_handler.socket_lock_fd,
+       ok = fcntl_lock(sconn->smb1.echo_handler.socket_lock_fd,
                        SMB_F_SETLKW, 0, 0, F_UNLCK);
        if (!ok) {
                return false;
@@ -261,7 +264,8 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
         * valid writeX call.
         */
 
-       if (is_valid_writeX_buffer((uint8_t *)writeX_header)) {
+       if (is_valid_writeX_buffer(smbd_server_conn,
+                                  (uint8_t *)writeX_header)) {
                /*
                 * If the data offset is beyond what
                 * we've read, drain the extra bytes.
@@ -438,11 +442,12 @@ static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,   int fd,
  * Initialize a struct smb_request from an inbuf
  */
 
-static bool init_smb_request(struct smb_request *req, const uint8 *inbuf,
+static bool init_smb_request(struct smb_request *req,
+                            struct smbd_server_connection *sconn,
+                            const uint8 *inbuf,
                             size_t unread_bytes, bool encrypted,
                             uint32_t seqnum)
 {
-       struct smbd_server_connection *sconn = smbd_server_conn;
        size_t req_size = smb_len(inbuf) + 4;
        /* Ensure we have at least smb_size bytes. */
        if (req_size < smb_size) {
@@ -453,7 +458,7 @@ static bool init_smb_request(struct smb_request *req, const uint8 *inbuf,
        req->cmd    = CVAL(inbuf, smb_com);
        req->flags2 = SVAL(inbuf, smb_flg2);
        req->smbpid = SVAL(inbuf, smb_pid);
-       req->mid    = SVAL(inbuf, smb_mid);
+       req->mid    = (uint64_t)SVAL(inbuf, smb_mid);
        req->seqnum = seqnum;
        req->vuid   = SVAL(inbuf, smb_uid);
        req->tid    = SVAL(inbuf, smb_tid);
@@ -463,10 +468,12 @@ static bool init_smb_request(struct smb_request *req, const uint8 *inbuf,
        req->buf    = (const uint8_t *)smb_buf(inbuf);
        req->unread_bytes = unread_bytes;
        req->encrypted = encrypted;
+       req->sconn = sconn;
        req->conn = conn_find(sconn,req->tid);
        req->chain_fsp = NULL;
        req->chain_outbuf = NULL;
        req->done = false;
+       req->smb2req = NULL;
        smb_init_perfcount_data(&req->pcd);
 
        /* Ensure we have at least wct words and 2 bytes of bcc. */
@@ -503,7 +510,7 @@ static void smbd_deferred_open_timer(struct event_context *ev,
        struct pending_message_list *msg = talloc_get_type(private_data,
                                           struct pending_message_list);
        TALLOC_CTX *mem_ctx = talloc_tos();
-       uint16_t mid = SVAL(msg->buf.data,smb_mid);
+       uint64_t mid = (uint64_t)SVAL(msg->buf.data,smb_mid);
        uint8_t *inbuf;
 
        inbuf = (uint8_t *)talloc_memdup(mem_ctx, msg->buf.data,
@@ -515,8 +522,8 @@ static void smbd_deferred_open_timer(struct event_context *ev,
 
        /* We leave this message on the queue so the open code can
           know this is a retry. */
-       DEBUG(5,("smbd_deferred_open_timer: trigger mid %u.\n",
-               (unsigned int)mid ));
+       DEBUG(5,("smbd_deferred_open_timer: trigger mid %llu.\n",
+               (unsigned long long)mid ));
 
        /* Mark the message as processed so this is not
         * re-processed in error. */
@@ -527,9 +534,9 @@ static void smbd_deferred_open_timer(struct event_context *ev,
                    msg->seqnum, msg->encrypted, &msg->pcd);
 
        /* If it's still there and was processed, remove it. */
-       msg = get_open_deferred_message(mid);
+       msg = get_deferred_open_message_smb(mid);
        if (msg && msg->processed) {
-               remove_deferred_open_smb_message(mid);
+               remove_deferred_open_message_smb(mid);
        }
 }
 
@@ -599,15 +606,20 @@ static bool push_queued_message(struct smb_request *req,
  Function to delete a sharing violation open message by mid.
 ****************************************************************************/
 
-void remove_deferred_open_smb_message(uint16 mid)
+void remove_deferred_open_message_smb(uint64_t mid)
 {
        struct pending_message_list *pml;
 
+       if (smbd_server_conn->using_smb2) {
+               remove_deferred_open_message_smb2(smbd_server_conn, mid);
+               return;
+       }
+
        for (pml = deferred_open_queue; pml; pml = pml->next) {
-               if (mid == SVAL(pml->buf.data,smb_mid)) {
-                       DEBUG(10,("remove_deferred_open_smb_message: "
-                                 "deleting mid %u len %u\n",
-                                 (unsigned int)mid,
+               if (mid == (uint64_t)SVAL(pml->buf.data,smb_mid)) {
+                       DEBUG(10,("remove_deferred_open_message_smb: "
+                                 "deleting mid %llu len %u\n",
+                                 (unsigned long long)mid,
                                  (unsigned int)pml->buf.length ));
                        DLIST_REMOVE(deferred_open_queue, pml);
                        TALLOC_FREE(pml);
@@ -621,16 +633,23 @@ void remove_deferred_open_smb_message(uint16 mid)
  schedule it for immediate processing.
 ****************************************************************************/
 
-void schedule_deferred_open_smb_message(uint16 mid)
+void schedule_deferred_open_message_smb(uint64_t mid)
 {
        struct pending_message_list *pml;
        int i = 0;
 
+       if (smbd_server_conn->using_smb2) {
+               schedule_deferred_open_message_smb2(smbd_server_conn, mid);
+               return;
+       }
+
        for (pml = deferred_open_queue; pml; pml = pml->next) {
-               uint16 msg_mid = SVAL(pml->buf.data,smb_mid);
+               uint64_t msg_mid = (uint64_t)SVAL(pml->buf.data,smb_mid);
 
-               DEBUG(10,("schedule_deferred_open_smb_message: [%d] msg_mid = %u\n", i++,
-                       (unsigned int)msg_mid ));
+               DEBUG(10,("schedule_deferred_open_message_smb: [%d] "
+                       "msg_mid = %llu\n",
+                       i++,
+                       (unsigned long long)msg_mid ));
 
                if (mid == msg_mid) {
                        struct timed_event *te;
@@ -638,14 +657,15 @@ void schedule_deferred_open_smb_message(uint16 mid)
                        if (pml->processed) {
                                /* A processed message should not be
                                 * rescheduled. */
-                               DEBUG(0,("schedule_deferred_open_smb_message: LOGIC ERROR "
-                                       "message mid %u was already processed\n",
-                                       msg_mid ));
+                               DEBUG(0,("schedule_deferred_open_message_smb: LOGIC ERROR "
+                                       "message mid %llu was already processed\n",
+                                       (unsigned long long)msg_mid ));
                                continue;
                        }
 
-                       DEBUG(10,("schedule_deferred_open_smb_message: scheduling mid %u\n",
-                               mid ));
+                       DEBUG(10,("schedule_deferred_open_message_smb: "
+                               "scheduling mid %llu\n",
+                               (unsigned long long)mid ));
 
                        te = event_add_timed(smbd_event_context(),
                                             pml,
@@ -653,9 +673,10 @@ void schedule_deferred_open_smb_message(uint16 mid)
                                             smbd_deferred_open_timer,
                                             pml);
                        if (!te) {
-                               DEBUG(10,("schedule_deferred_open_smb_message: "
-                                         "event_add_timed() failed, skipping mid %u\n",
-                                         mid ));
+                               DEBUG(10,("schedule_deferred_open_message_smb: "
+                                       "event_add_timed() failed, "
+                                       "skipping mid %llu\n",
+                                       (unsigned long long)msg_mid ));
                        }
 
                        TALLOC_FREE(pml->te);
@@ -665,20 +686,25 @@ void schedule_deferred_open_smb_message(uint16 mid)
                }
        }
 
-       DEBUG(10,("schedule_deferred_open_smb_message: failed to find message mid %u\n",
-               mid ));
+       DEBUG(10,("schedule_deferred_open_message_smb: failed to "
+               "find message mid %llu\n",
+               (unsigned long long)mid ));
 }
 
 /****************************************************************************
  Return true if this mid is on the deferred queue and was not yet processed.
 ****************************************************************************/
 
-bool open_was_deferred(uint16 mid)
+bool open_was_deferred(uint64_t mid)
 {
        struct pending_message_list *pml;
 
+       if (smbd_server_conn->using_smb2) {
+               return open_was_deferred_smb2(smbd_server_conn, mid);
+       }
+
        for (pml = deferred_open_queue; pml; pml = pml->next) {
-               if (SVAL(pml->buf.data,smb_mid) == mid && !pml->processed) {
+               if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid && !pml->processed) {
                        return True;
                }
        }
@@ -689,45 +715,85 @@ bool open_was_deferred(uint16 mid)
  Return the message queued by this mid.
 ****************************************************************************/
 
-struct pending_message_list *get_open_deferred_message(uint16 mid)
+static struct pending_message_list *get_deferred_open_message_smb(uint64_t mid)
 {
        struct pending_message_list *pml;
 
        for (pml = deferred_open_queue; pml; pml = pml->next) {
-               if (SVAL(pml->buf.data,smb_mid) == mid) {
+               if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid) {
                        return pml;
                }
        }
        return NULL;
 }
 
+/****************************************************************************
+ Get the state data queued by this mid.
+****************************************************************************/
+
+bool get_deferred_open_message_state(struct smb_request *smbreq,
+                               struct timeval *p_request_time,
+                               void **pp_state)
+{
+       struct pending_message_list *pml;
+
+       if (smbd_server_conn->using_smb2) {
+               return get_deferred_open_message_state_smb2(smbreq->smb2req,
+                                       p_request_time,
+                                       pp_state);
+       }
+
+       pml = get_deferred_open_message_smb(smbreq->mid);
+       if (!pml) {
+               return false;
+       }
+       if (p_request_time) {
+               *p_request_time = pml->request_time;
+       }
+       if (pp_state) {
+               *pp_state = (void *)pml->private_data.data;
+       }
+       return true;
+}
+
 /****************************************************************************
  Function to push a deferred open smb message onto a linked list of local smb
  messages ready for processing.
 ****************************************************************************/
 
-bool push_deferred_smb_message(struct smb_request *req,
+bool push_deferred_open_message_smb(struct smb_request *req,
                               struct timeval request_time,
                               struct timeval timeout,
+                              struct file_id id,
                               char *private_data, size_t priv_len)
 {
        struct timeval end_time;
 
+       if (req->smb2req) {
+               return push_deferred_open_message_smb2(req->smb2req,
+                                               request_time,
+                                               timeout,
+                                               id,
+                                               private_data,
+                                               priv_len);
+       }
+
        if (req->unread_bytes) {
-               DEBUG(0,("push_deferred_smb_message: logic error ! "
+               DEBUG(0,("push_deferred_open_message_smb: logic error ! "
                        "unread_bytes = %u\n",
                        (unsigned int)req->unread_bytes ));
-               smb_panic("push_deferred_smb_message: "
+               smb_panic("push_deferred_open_message_smb: "
                        "logic error unread_bytes != 0" );
        }
 
        end_time = timeval_sum(&request_time, &timeout);
 
-       DEBUG(10,("push_deferred_open_smb_message: pushing message len %u mid %u "
-                 "timeout time [%u.%06u]\n",
-                 (unsigned int) smb_len(req->inbuf)+4, (unsigned int)req->mid,
-                 (unsigned int)end_time.tv_sec,
-                 (unsigned int)end_time.tv_usec));
+       DEBUG(10,("push_deferred_open_message_smb: pushing message "
+               "len %u mid %llu timeout time [%u.%06u]\n",
+               (unsigned int) smb_len(req->inbuf)+4,
+               (unsigned long long)req->mid,
+               (unsigned int)end_time.tv_sec,
+               (unsigned int)end_time.tv_usec));
 
        return push_queued_message(req, request_time, end_time,
                                   private_data, priv_len);
@@ -844,20 +910,20 @@ static void smbd_sig_hup_handler(struct tevent_context *ev,
                                  void *siginfo,
                                  void *private_data)
 {
+       struct messaging_context *msg_ctx = talloc_get_type_abort(
+               private_data, struct messaging_context);
        change_to_root_user();
        DEBUG(1,("Reloading services after SIGHUP\n"));
-       reload_services(False);
+       reload_services(msg_ctx, False);
 }
 
-void smbd_setup_sig_hup_handler(void)
+void smbd_setup_sig_hup_handler(struct tevent_context *ev,
+                               struct messaging_context *msg_ctx)
 {
        struct tevent_signal *se;
 
-       se = tevent_add_signal(smbd_event_context(),
-                              smbd_event_context(),
-                              SIGHUP, 0,
-                              smbd_sig_hup_handler,
-                              NULL);
+       se = tevent_add_signal(ev, ev, SIGHUP, 0, smbd_sig_hup_handler,
+                              msg_ctx);
        if (!se) {
                exit_server("failed to setup SIGHUP handler");
        }
@@ -909,6 +975,17 @@ static NTSTATUS smbd_server_connection_loop_once(struct smbd_server_connection *
                errno = sav;
        }
 
+        if ((conn->smb1.echo_handler.trusted_fd != -1)
+           && FD_ISSET(smbd_server_fd(), &r_fds)
+           && FD_ISSET(conn->smb1.echo_handler.trusted_fd, &r_fds)) {
+               /*
+                * Prefer to read pending requests from the echo handler. To
+                * quote Jeremy (da70f8ab1): This is a hack of monstrous
+                * proportions...
+                */
+               FD_CLR(smbd_server_fd(), &r_fds);
+        }
+
        if (run_events(smbd_event_context(), selrtn, &r_fds, &w_fds)) {
                return NT_STATUS_RETRY;
        }
@@ -933,7 +1010,7 @@ static NTSTATUS smbd_server_connection_loop_once(struct smbd_server_connection *
  * prevent a DoS.
  */
 
-NTSTATUS allow_new_trans(struct trans_state *list, int mid)
+NTSTATUS allow_new_trans(struct trans_state *list, uint64_t mid)
 {
        int count = 0;
        for (; list != NULL; list = list->next) {
@@ -1335,7 +1412,7 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
        int flags;
        uint16 session_tag;
        connection_struct *conn = NULL;
-       struct smbd_server_connection *sconn = smbd_server_conn;
+       struct smbd_server_connection *sconn = req->sconn;
 
        errno = 0;
 
@@ -1389,8 +1466,7 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
                                set_current_user_info(
                                        vuser->server_info->sanitized_username,
                                        vuser->server_info->unix_name,
-                                       pdb_get_domain(vuser->server_info
-                                                      ->sam_account));
+                                       vuser->server_info->info3->base.domain.string);
                        }
                }
        }
@@ -1414,7 +1490,8 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
 
                if (!change_to_user(conn,session_tag)) {
                        DEBUG(0, ("Error: Could not change to user. Removing "
-                           "deferred open, mid=%d.\n", req->mid));
+                               "deferred open, mid=%llu.\n",
+                               (unsigned long long)req->mid));
                        reply_force_doserror(req, ERRSRV, ERRbaduid);
                        return conn;
                }
@@ -1488,8 +1565,8 @@ static void construct_reply(char *inbuf, int size, size_t unread_bytes,
                smb_panic("could not allocate smb_request");
        }
 
-       if (!init_smb_request(req, (uint8 *)inbuf, unread_bytes, encrypted,
-                             seqnum)) {
+       if (!init_smb_request(req, smbd_server_conn, (uint8 *)inbuf,
+                             unread_bytes, encrypted, seqnum)) {
                exit_server_cleanly("Invalid SMB request");
        }
 
@@ -1563,16 +1640,22 @@ static void process_smb(struct smbd_server_connection *conn,
                /*
                 * NetBIOS session request, keepalive, etc.
                 */
-               reply_special((char *)inbuf);
+               reply_special(conn, (char *)inbuf);
                goto done;
        }
 
-       if (smbd_server_conn->allow_smb2) {
+       if (smbd_server_conn->using_smb2) {
+               /* At this point we're not really using smb2,
+                * we make the decision here.. */
                if (smbd_is_smb2_header(inbuf, nread)) {
                        smbd_smb2_first_negprot(smbd_server_conn, inbuf, nread);
                        return;
+               } else if (nread >= smb_size && valid_smb_header(inbuf)
+                               && CVAL(inbuf, smb_com) != 0x72) {
+                       /* This is a non-negprot SMB1 packet.
+                          Disable SMB2 from now on. */
+                       smbd_server_conn->using_smb2 = false;
                }
-               smbd_server_conn->allow_smb2 = false;
        }
 
        show_msg((char *)inbuf);
@@ -2115,7 +2198,7 @@ void chain_reply(struct smb_request *req)
  Check if services need reloading.
 ****************************************************************************/
 
-void check_reload(time_t t)
+static void check_reload(struct messaging_context *msg_ctx, time_t t)
 {
        time_t printcap_cache_time = (time_t)lp_printcap_cache_time();
 
@@ -2140,7 +2223,7 @@ void check_reload(time_t t)
        }
 
        if (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK) {
-               reload_services(True);
+               reload_services(msg_ctx, True);
                last_smb_conf_reload_time = t;
        }
 
@@ -2154,7 +2237,7 @@ void check_reload(time_t t)
                        || (t-last_printer_reload_time  < 0) ) 
                {
                        DEBUG( 3,( "Printcap cache time expired.\n"));
-                       reload_printers();
+                       reload_printers(msg_ctx);
                        last_printer_reload_time = t;
                }
        }
@@ -2328,8 +2411,14 @@ static int client_get_tcp_info(struct sockaddr_storage *server,
  */
 static bool keepalive_fn(const struct timeval *now, void *private_data)
 {
+       struct smbd_server_connection *sconn = smbd_server_conn;
        bool ret;
 
+       if (sconn->using_smb2) {
+               /* Don't do keepalives on an SMB2 connection. */
+               return false;
+       }
+
        smbd_lock_socket(smbd_server_conn);
        ret = send_keepalive(smbd_server_fd());
        smbd_unlock_socket(smbd_server_conn);
@@ -2346,15 +2435,16 @@ static bool keepalive_fn(const struct timeval *now, void *private_data)
  */
 static bool deadtime_fn(const struct timeval *now, void *private_data)
 {
-       struct smbd_server_connection *sconn = smbd_server_conn;
+       struct smbd_server_connection *sconn =
+               (struct smbd_server_connection *)private_data;
 
-       if (sconn->allow_smb2) {
+       if (sconn->using_smb2) {
                /* TODO: implement real idle check */
                if (sconn->smb2.sessions.list) {
                        return true;
                }
                DEBUG( 2, ( "Closing idle SMB2 connection\n" ) );
-               messaging_send(smbd_messaging_context(), procid_self(),
+               messaging_send(sconn->msg_ctx, procid_self(),
                               MSG_SHUTDOWN, &data_blob_null);
                return false;
        }
@@ -2362,7 +2452,7 @@ static bool deadtime_fn(const struct timeval *now, void *private_data)
        if ((conn_num_open(sconn) == 0)
            || (conn_idle_all(sconn, now->tv_sec))) {
                DEBUG( 2, ( "Closing idle SMB1 connection\n" ) );
-               messaging_send(smbd_messaging_context(), procid_self(),
+               messaging_send(sconn->msg_ctx, procid_self(),
                               MSG_SHUTDOWN, &data_blob_null);
                return False;
        }
@@ -2379,10 +2469,10 @@ static bool housekeeping_fn(const struct timeval *now, void *private_data)
        change_to_root_user();
 
        /* update printer queue caches if necessary */
-       update_monitored_printq_cache();
+       update_monitored_printq_cache(smbd_messaging_context());
 
        /* check if we need to reload services */
-       check_reload(time(NULL));
+       check_reload(smbd_messaging_context(), time(NULL));
 
        /* Change machine password if neccessary. */
        attempt_machine_password_change();
@@ -2500,7 +2590,8 @@ static bool smbd_echo_reply(int fd,
                return false;
        }
 
-       if (!init_smb_request(&req, inbuf, 0, false, seqnum)) {
+       if (!init_smb_request(&req, smbd_server_conn, inbuf, 0, false,
+                             seqnum)) {
                return false;
        }
        req.inbuf = inbuf;
@@ -2602,7 +2693,7 @@ static void smbd_echo_reader(struct tevent_context *ev,
 
        DEBUG(10,("echo_handler[%d]: reading pdu\n", (int)sys_getpid()));
 
-       status = receive_smb_talloc(state, smbd_server_fd(),
+       status = receive_smb_talloc(state->pending, smbd_server_fd(),
                                    (char **)(void *)&state->pending[num_pending].iov_base,
                                    0 /* timeout */,
                                    &unread,
@@ -2717,8 +2808,9 @@ static bool fork_echo_handler(struct smbd_server_connection *sconn)
 
                close(listener_pipe[0]);
 
-               status = reinit_after_fork(smbd_messaging_context(),
-                                          smbd_event_context(), false);
+               status = reinit_after_fork(sconn->msg_ctx,
+                                          smbd_event_context(),
+                                          procid_self(), false);
                if (!NT_STATUS_IS_OK(status)) {
                        DEBUG(1, ("reinit_after_fork failed: %s\n",
                                  nt_errstr(status)));
@@ -2766,6 +2858,11 @@ fail:
        return false;
 }
 
+static bool spoolss_init_cb(void *ptr)
+{
+       return nt_printing_tdb_migrate(smbd_messaging_context());
+}
+
 /****************************************************************************
  Process commands from the client
 ****************************************************************************/
@@ -2773,12 +2870,26 @@ fail:
 void smbd_process(void)
 {
        TALLOC_CTX *frame = talloc_stackframe();
-       char remaddr[INET6_ADDRSTRLEN];
+       struct sockaddr_storage ss;
+       struct sockaddr *sa = NULL;
+       socklen_t sa_len;
+       struct tsocket_address *local_address = NULL;
+       struct tsocket_address *remote_address = NULL;
+       const char *remaddr = NULL;
+       int ret;
+       struct rpc_srv_callbacks spoolss_cb;
 
        if (lp_maxprotocol() == PROTOCOL_SMB2 &&
            lp_security() != SEC_SHARE &&
            !lp_async_smb_echo_handler()) {
-               smbd_server_conn->allow_smb2 = true;
+               /*
+                * We're not making the desion here,
+                * we're just allowing the client
+                * to decide between SMB1 and SMB2
+                * with the first negprot
+                * packet.
+                */
+               smbd_server_conn->using_smb2 = true;
        }
 
        /* Ensure child is set to blocking mode */
@@ -2787,13 +2898,58 @@ void smbd_process(void)
        set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
        set_socket_options(smbd_server_fd(), lp_socket_options());
 
+       sa = (struct sockaddr *)(void *)&ss;
+       sa_len = sizeof(ss);
+       ret = getpeername(smbd_server_fd(), sa, &sa_len);
+       if (ret != 0) {
+               int level = (errno == ENOTCONN)?2:0;
+               DEBUG(level,("getpeername() failed - %s\n", strerror(errno)));
+               exit_server_cleanly("getpeername() failed.\n");
+       }
+       ret = tsocket_address_bsd_from_sockaddr(smbd_server_conn,
+                                               sa, sa_len,
+                                               &remote_address);
+       if (ret != 0) {
+               DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
+                       __location__, strerror(errno)));
+               exit_server_cleanly("tsocket_address_bsd_from_sockaddr remote failed.\n");
+       }
+
+       sa = (struct sockaddr *)(void *)&ss;
+       sa_len = sizeof(ss);
+       ret = getsockname(smbd_server_fd(), sa, &sa_len);
+       if (ret != 0) {
+               int level = (errno == ENOTCONN)?2:0;
+               DEBUG(level,("getsockname() failed - %s\n", strerror(errno)));
+               exit_server_cleanly("getsockname() failed.\n");
+       }
+       ret = tsocket_address_bsd_from_sockaddr(smbd_server_conn,
+                                               sa, sa_len,
+                                               &local_address);
+       if (ret != 0) {
+               DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
+                       __location__, strerror(errno)));
+               exit_server_cleanly("tsocket_address_bsd_from_sockaddr remote failed.\n");
+       }
+
+       smbd_server_conn->local_address = local_address;
+       smbd_server_conn->remote_address = remote_address;
+
+       if (tsocket_address_is_inet(remote_address, "ip")) {
+               remaddr = tsocket_address_inet_addr_string(
+                               smbd_server_conn->remote_address,
+                               talloc_tos());
+               if (remaddr == NULL) {
+
+               }
+       } else {
+               remaddr = "0.0.0.0";
+       }
+
        /* this is needed so that we get decent entries
           in smbstatus for port 445 connects */
-       set_remote_machine_name(get_peer_addr(smbd_server_fd(),
-                                             remaddr,
-                                             sizeof(remaddr)),
-                                             false);
-       reload_services(true);
+       set_remote_machine_name(remaddr, false);
+       reload_services(smbd_server_conn->msg_ctx, true);
 
        /*
         * Before the first packet, check the global hosts allow/ hosts deny
@@ -2804,21 +2960,22 @@ void smbd_process(void)
 
        if (!check_access(smbd_server_fd(), lp_hostsallow(-1),
                          lp_hostsdeny(-1))) {
-               char addr[INET6_ADDRSTRLEN];
-
                /*
                 * send a negative session response "not listening on calling
                 * name"
                 */
                unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
-               DEBUG( 1, ("Connection denied from %s\n",
-                          client_addr(get_client_fd(),addr,sizeof(addr)) ) );
+               DEBUG( 1, ("Connection denied from %s to %s\n",
+                          tsocket_address_string(remote_address, talloc_tos()),
+                          tsocket_address_string(local_address, talloc_tos())));
                (void)srv_send_smb(smbd_server_fd(),(char *)buf, false,
                                   0, false, NULL);
                exit_server_cleanly("connection denied");
        }
 
-       static_init_rpc;
+       DEBUG(10, ("Connection allowed from %s to %s\n",
+                  tsocket_address_string(remote_address, talloc_tos()),
+                  tsocket_address_string(local_address, talloc_tos())));
 
        init_modules();
 
@@ -2880,7 +3037,7 @@ void smbd_process(void)
 
        if (!(event_add_idle(smbd_event_context(), NULL,
                             timeval_set(IDLE_CLOSED_TIMEOUT, 0),
-                            "deadtime", deadtime_fn, NULL))) {
+                            "deadtime", deadtime_fn, smbd_server_conn))) {
                DEBUG(0, ("Could not add deadtime event\n"));
                exit(1);
        }
@@ -2909,7 +3066,7 @@ void smbd_process(void)
                        NTSTATUS status;
 
                        status = ctdbd_register_ips(
-                               messaging_ctdbd_connection(),
+                               messaging_ctdbd_connection(procid_self()),
                                &srv, &clnt, release_ip, NULL);
 
                        if (!NT_STATUS_IS_OK(status)) {
@@ -2941,9 +3098,6 @@ void smbd_process(void)
        smbd_server_conn->smb1.sessions.validated_users = NULL;
        smbd_server_conn->smb1.sessions.next_vuid = VUID_OFFSET;
        smbd_server_conn->smb1.sessions.num_validated_vuids = 0;
-#ifdef HAVE_NETGROUP
-       smbd_server_conn->smb1.sessions.my_yp_domain = NULL;
-#endif
 
        conn_init(smbd_server_conn);
        if (!init_dptrs(smbd_server_conn)) {
@@ -2960,6 +3114,25 @@ void smbd_process(void)
                exit_server("failed to create smbd_server_connection fde");
        }
 
+       /*
+        * Initialize spoolss with an init function to convert printers first.
+        * static_init_rpc will try to initialize the spoolss server too but you
+        * can't register it twice.
+        */
+       spoolss_cb.init = spoolss_init_cb;
+       spoolss_cb.shutdown = NULL;
+
+
+       if (!NT_STATUS_IS_OK(rpc_winreg_init(NULL))) {
+               exit(1);
+       }
+
+       if (!NT_STATUS_IS_OK(rpc_spoolss_init(&spoolss_cb))) {
+               exit(1);
+       }
+
+       static_init_rpc;
+
        TALLOC_FREE(frame);
 
        while (True) {