2 Unix SMB/CIFS implementation.
3 process incoming packets - main loop
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Volker Lendecke 2005-2007
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "../lib/tsocket/tsocket.h"
23 #include "system/filesys.h"
24 #include "smbd/smbd.h"
25 #include "smbd/globals.h"
26 #include "smbd/smbXsrv_open.h"
27 #include "librpc/gen_ndr/netlogon.h"
28 #include "../lib/async_req/async_sock.h"
29 #include "ctdbd_conn.h"
30 #include "../lib/util/select.h"
31 #include "printing/queue_process.h"
32 #include "system/select.h"
36 #include "lib/messages_ctdb.h"
37 #include "smbprofile.h"
38 #include "rpc_server/spoolss/srv_spoolss_nt.h"
39 #include "../lib/util/tevent_ntstatus.h"
40 #include "../libcli/security/dom_sid.h"
41 #include "../libcli/security/security_token.h"
42 #include "lib/id_cache.h"
43 #include "lib/util/sys_rw_data.h"
44 #include "system/threads.h"
45 #include "lib/pthreadpool/pthreadpool_tevent.h"
46 #include "util_event.h"
47 #include "libcli/smb/smbXcli_base.h"
48 #include "lib/util/time_basic.h"
49 #include "source3/lib/substitute.h"
50 #include "source3/smbd/dir.h"
52 /* Internal message queue for deferred opens. */
53 struct pending_message_list {
54 struct pending_message_list *next, *prev;
55 struct timeval request_time; /* When was this first issued? */
56 struct smbd_server_connection *sconn;
57 struct smbXsrv_connection *xconn;
58 struct tevent_timer *te;
63 struct deferred_open_record *open_rec;
66 static struct pending_message_list *get_deferred_open_message_smb(
67 struct smbd_server_connection *sconn, uint64_t mid);
69 #if !defined(WITH_SMB1SERVER)
70 bool smb1_srv_send(struct smbXsrv_connection *xconn,
78 len = smb_len_large(buffer) + 4;
79 ret = write_data(xconn->transport.sock, buffer, len);
84 /*******************************************************************
85 Setup the word count and byte count for a smb1 message.
86 ********************************************************************/
88 size_t srv_smb1_set_message(char *buf,
93 if (zero && (num_words || num_bytes)) {
94 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
96 SCVAL(buf,smb_wct,num_words);
97 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
98 smb_setlen(buf,(smb_size + num_words*2 + num_bytes - 4));
99 return (smb_size + num_words*2 + num_bytes);
102 NTSTATUS read_packet_remainder(int fd, char *buffer,
103 unsigned int timeout, ssize_t len)
111 status = read_fd_with_timeout(fd, buffer, len, len, timeout, NULL);
112 if (!NT_STATUS_IS_OK(status)) {
113 char addr[INET6_ADDRSTRLEN];
114 DEBUG(0, ("read_fd_with_timeout failed for client %s read "
116 get_peer_addr(fd, addr, sizeof(addr)),
122 #if !defined(WITH_SMB1SERVER)
123 static NTSTATUS smb2_receive_raw_talloc(TALLOC_CTX *mem_ctx,
124 struct smbXsrv_connection *xconn,
126 char **buffer, unsigned int timeout,
127 size_t *p_unread, size_t *plen)
135 status = read_smb_length_return_keepalive(sock, lenbuf, timeout,
137 if (!NT_STATUS_IS_OK(status)) {
142 * The +4 here can't wrap, we've checked the length above already.
145 *buffer = talloc_array(mem_ctx, char, len+4);
147 if (*buffer == NULL) {
148 DEBUG(0, ("Could not allocate inbuf of length %d\n",
150 return NT_STATUS_NO_MEMORY;
153 memcpy(*buffer, lenbuf, sizeof(lenbuf));
155 status = read_packet_remainder(sock, (*buffer)+4, timeout, len);
156 if (!NT_STATUS_IS_OK(status)) {
164 static NTSTATUS smb2_receive_talloc(TALLOC_CTX *mem_ctx,
165 struct smbXsrv_connection *xconn,
167 char **buffer, unsigned int timeout,
168 size_t *p_unread, bool *p_encrypted,
171 bool trusted_channel)
176 *p_encrypted = false;
178 status = smb2_receive_raw_talloc(mem_ctx, xconn, sock, buffer, timeout,
180 if (!NT_STATUS_IS_OK(status)) {
181 DEBUG(NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)?5:1,
182 ("smb2_receive_raw_talloc failed for client %s "
183 "read error = %s.\n",
184 smbXsrv_connection_dbg(xconn),
185 nt_errstr(status)) );
194 NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,
195 struct smbXsrv_connection *xconn,
197 char **buffer, unsigned int timeout,
198 size_t *p_unread, bool *p_encrypted,
201 bool trusted_channel)
203 #if defined(WITH_SMB1SERVER)
204 return smb1_receive_talloc(mem_ctx, xconn, sock, buffer, timeout,
205 p_unread, p_encrypted, p_len, seqnum,
208 return smb2_receive_talloc(mem_ctx, xconn, sock, buffer, timeout,
209 p_unread, p_encrypted, p_len, seqnum,
214 /****************************************************************************
215 Function to delete a sharing violation open message by mid.
216 ****************************************************************************/
218 void remove_deferred_open_message_smb(struct smbXsrv_connection *xconn,
221 struct smbd_server_connection *sconn = xconn->client->sconn;
222 struct pending_message_list *pml;
224 if (sconn->using_smb2) {
225 remove_deferred_open_message_smb2(xconn, mid);
229 for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
230 if (mid == (uint64_t)SVAL(pml->buf.data,smb_mid)) {
231 DEBUG(10,("remove_deferred_open_message_smb: "
232 "deleting mid %llu len %u\n",
233 (unsigned long long)mid,
234 (unsigned int)pml->buf.length ));
235 DLIST_REMOVE(sconn->deferred_open_queue, pml);
242 static void smbd_deferred_open_timer(struct tevent_context *ev,
243 struct tevent_timer *te,
244 struct timeval _tval,
247 struct pending_message_list *msg = talloc_get_type(private_data,
248 struct pending_message_list);
249 struct smbd_server_connection *sconn = msg->sconn;
250 struct smbXsrv_connection *xconn = msg->xconn;
251 TALLOC_CTX *mem_ctx = talloc_tos();
252 uint64_t mid = (uint64_t)SVAL(msg->buf.data,smb_mid);
255 inbuf = (uint8_t *)talloc_memdup(mem_ctx, msg->buf.data,
258 exit_server("smbd_deferred_open_timer: talloc failed\n");
262 /* We leave this message on the queue so the open code can
263 know this is a retry. */
264 DEBUG(5,("smbd_deferred_open_timer: trigger mid %llu.\n",
265 (unsigned long long)mid ));
267 /* Mark the message as processed so this is not
268 * re-processed in error. */
269 msg->processed = true;
278 /* If it's still there and was processed, remove it. */
279 msg = get_deferred_open_message_smb(sconn, mid);
280 if (msg && msg->processed) {
281 remove_deferred_open_message_smb(xconn, mid);
285 /****************************************************************************
286 Move a sharing violation open retry message to the front of the list and
287 schedule it for immediate processing.
288 ****************************************************************************/
290 bool schedule_deferred_open_message_smb(struct smbXsrv_connection *xconn,
293 struct smbd_server_connection *sconn = xconn->client->sconn;
294 struct pending_message_list *pml;
297 if (sconn->using_smb2) {
298 return schedule_deferred_open_message_smb2(xconn, mid);
301 for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
302 uint64_t msg_mid = (uint64_t)SVAL(pml->buf.data,smb_mid);
304 DEBUG(10,("schedule_deferred_open_message_smb: [%d] "
307 (unsigned long long)msg_mid ));
309 if (mid == msg_mid) {
310 struct tevent_timer *te;
312 if (pml->processed) {
313 /* A processed message should not be
315 DEBUG(0,("schedule_deferred_open_message_smb: LOGIC ERROR "
316 "message mid %llu was already processed\n",
317 (unsigned long long)msg_mid ));
321 DEBUG(10,("schedule_deferred_open_message_smb: "
322 "scheduling mid %llu\n",
323 (unsigned long long)mid ));
326 * smbd_deferred_open_timer() calls
327 * process_smb() to redispatch the request
328 * including the required impersonation.
330 * So we can just use the raw tevent_context.
332 te = tevent_add_timer(xconn->client->raw_ev_ctx,
335 smbd_deferred_open_timer,
338 DEBUG(10,("schedule_deferred_open_message_smb: "
339 "event_add_timed() failed, "
340 "skipping mid %llu\n",
341 (unsigned long long)msg_mid ));
344 TALLOC_FREE(pml->te);
346 DLIST_PROMOTE(sconn->deferred_open_queue, pml);
351 DEBUG(10,("schedule_deferred_open_message_smb: failed to "
352 "find message mid %llu\n",
353 (unsigned long long)mid ));
358 /****************************************************************************
359 Return true if this mid is on the deferred queue and was not yet processed.
360 ****************************************************************************/
362 bool open_was_deferred(struct smbXsrv_connection *xconn, uint64_t mid)
364 struct smbd_server_connection *sconn = xconn->client->sconn;
365 struct pending_message_list *pml;
367 if (sconn->using_smb2) {
368 return open_was_deferred_smb2(xconn, mid);
371 for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
372 if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid && !pml->processed) {
379 /****************************************************************************
380 Return the message queued by this mid.
381 ****************************************************************************/
383 static struct pending_message_list *get_deferred_open_message_smb(
384 struct smbd_server_connection *sconn, uint64_t mid)
386 struct pending_message_list *pml;
388 for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
389 if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid) {
396 /****************************************************************************
397 Get the state data queued by this mid.
398 ****************************************************************************/
400 bool get_deferred_open_message_state(struct smb_request *smbreq,
401 struct timeval *p_request_time,
402 struct deferred_open_record **open_rec)
404 struct pending_message_list *pml;
406 if (smbreq->sconn->using_smb2) {
407 return get_deferred_open_message_state_smb2(smbreq->smb2req,
412 pml = get_deferred_open_message_smb(smbreq->sconn, smbreq->mid);
416 if (p_request_time) {
417 *p_request_time = pml->request_time;
419 if (open_rec != NULL) {
420 *open_rec = pml->open_rec;
425 bool push_deferred_open_message_smb(struct smb_request *req,
426 struct timeval timeout,
428 struct deferred_open_record *open_rec)
430 #if defined(WITH_SMB1SERVER)
433 return push_deferred_open_message_smb2(req->smb2req,
438 #if defined(WITH_SMB1SERVER)
440 return push_deferred_open_message_smb1(req, timeout,
446 static void construct_smb1_reply_common(uint8_t cmd, const uint8_t *inbuf,
449 uint16_t in_flags2 = SVAL(inbuf,smb_flg2);
450 uint16_t out_flags2 = common_flags2;
452 out_flags2 |= in_flags2 & FLAGS2_UNICODE_STRINGS;
453 out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES;
454 out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES_REQUIRED;
456 srv_smb1_set_message(outbuf,0,0,false);
458 SCVAL(outbuf, smb_com, cmd);
459 SIVAL(outbuf,smb_rcls,0);
460 SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES));
461 SSVAL(outbuf,smb_flg2, out_flags2);
462 memset(outbuf+smb_pidhigh,'\0',(smb_tid-smb_pidhigh));
463 memcpy(outbuf+smb_ss_field, inbuf+smb_ss_field, 8);
465 SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
466 SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
467 SSVAL(outbuf,smb_pidhigh,SVAL(inbuf,smb_pidhigh));
468 SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
469 SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
472 void construct_smb1_reply_common_req(struct smb_request *req, char *outbuf)
474 construct_smb1_reply_common(req->cmd, req->inbuf, outbuf);
477 /*******************************************************************
478 allocate and initialize a reply packet
479 ********************************************************************/
481 bool create_smb1_outbuf(TALLOC_CTX *mem_ctx, struct smb_request *req,
482 const uint8_t *inbuf, char **outbuf,
483 uint8_t num_words, uint32_t num_bytes)
485 size_t smb_len = MIN_SMB_SIZE + VWV(num_words) + num_bytes;
488 * Protect against integer wrap.
489 * The SMB layer reply can be up to 0xFFFFFF bytes.
491 if ((num_bytes > 0xffffff) || (smb_len > 0xffffff)) {
493 if (asprintf(&msg, "num_bytes too large: %u",
494 (unsigned)num_bytes) == -1) {
495 msg = discard_const_p(char, "num_bytes too large");
501 * Here we include the NBT header for now.
503 *outbuf = talloc_array(mem_ctx, char,
504 NBT_HDR_SIZE + smb_len);
505 if (*outbuf == NULL) {
509 construct_smb1_reply_common(req->cmd, inbuf, *outbuf);
510 srv_smb1_set_message(*outbuf, num_words, num_bytes, false);
512 * Zero out the word area, the caller has to take care of the bcc area
515 if (num_words != 0) {
516 memset(*outbuf + (NBT_HDR_SIZE + HDR_VWV), 0, VWV(num_words));
522 void reply_smb1_outbuf(struct smb_request *req, uint8_t num_words, uint32_t num_bytes)
525 if (!create_smb1_outbuf(req, req, req->inbuf, &outbuf, num_words,
527 smb_panic("could not allocate output buffer\n");
529 req->outbuf = (uint8_t *)outbuf;
532 bool valid_smb1_header(const uint8_t *inbuf)
534 if (is_encrypted_packet(inbuf)) {
538 * This used to be (strncmp(smb_base(inbuf),"\377SMB",4) == 0)
539 * but it just looks weird to call strncmp for this one.
541 return (IVAL(smb_base(inbuf), 0) == 0x424D53FF);
544 /****************************************************************************
545 Process an smb from the client
546 ****************************************************************************/
548 static void process_smb2(struct smbXsrv_connection *xconn,
555 const uint8_t *inpdu = inbuf + NBT_HDR_SIZE;
556 size_t pdulen = nread - NBT_HDR_SIZE;
557 NTSTATUS status = smbd_smb2_process_negprot(xconn, 0, inpdu, pdulen);
558 if (!NT_STATUS_IS_OK(status)) {
559 exit_server_cleanly("SMB2 negprot fail");
563 void process_smb(struct smbXsrv_connection *xconn,
570 struct smbd_server_connection *sconn = xconn->client->sconn;
571 int msg_type = CVAL(inbuf,0);
573 DO_PROFILE_INC(request);
575 DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type,
577 DEBUG(3, ("Transaction %d of length %d (%u toread)\n",
578 sconn->trans_num, (int)nread, (unsigned int)unread_bytes));
580 if (msg_type != NBSSmessage) {
582 * NetBIOS session request, keepalive, etc.
584 reply_special(xconn, (char *)inbuf, nread);
588 #if defined(WITH_SMB1SERVER)
589 if (sconn->using_smb2) {
590 /* At this point we're not really using smb2,
591 * we make the decision here.. */
592 if (smbd_is_smb2_header(inbuf, nread)) {
601 #if defined(WITH_SMB1SERVER)
603 if (nread >= smb_size && valid_smb1_header(inbuf)
604 && CVAL(inbuf, smb_com) != 0x72) {
605 /* This is a non-negprot SMB1 packet.
606 Disable SMB2 from now on. */
607 sconn->using_smb2 = false;
610 process_smb1(xconn, inbuf, nread, unread_bytes, seqnum, encrypted);
614 sconn->num_requests++;
616 /* The timeout_processing function isn't run nearly
617 often enough to implement 'max log size' without
618 overrunning the size of the file by many megabytes.
619 This is especially true if we are running at debug
620 level 10. Checking every 50 SMBs is a nice
621 tradeoff of performance vs log file size overrun. */
623 if ((sconn->num_requests % 50) == 0 &&
624 need_to_check_log_size()) {
625 change_to_root_user();
630 NTSTATUS smbXsrv_connection_init_tables(struct smbXsrv_connection *conn,
631 enum protocol_types protocol)
635 conn->protocol = protocol;
637 if (conn->client->session_table != NULL) {
641 if (protocol >= PROTOCOL_SMB2_02) {
642 status = smb2srv_session_table_init(conn);
643 if (!NT_STATUS_IS_OK(status)) {
644 conn->protocol = PROTOCOL_NONE;
648 status = smb2srv_open_table_init(conn);
649 if (!NT_STATUS_IS_OK(status)) {
650 conn->protocol = PROTOCOL_NONE;
654 #if defined(WITH_SMB1SERVER)
655 status = smb1srv_session_table_init(conn);
656 if (!NT_STATUS_IS_OK(status)) {
657 conn->protocol = PROTOCOL_NONE;
661 status = smb1srv_tcon_table_init(conn);
662 if (!NT_STATUS_IS_OK(status)) {
663 conn->protocol = PROTOCOL_NONE;
667 status = smb1srv_open_table_init(conn);
668 if (!NT_STATUS_IS_OK(status)) {
669 conn->protocol = PROTOCOL_NONE;
673 conn->protocol = PROTOCOL_NONE;
674 return NT_STATUS_INVALID_NETWORK_RESPONSE;
678 set_Protocol(protocol);
683 * Create a debug string for the connection
685 * This is allocated to talloc_tos() or a string constant
686 * in certain corner cases. The returned string should
687 * hence not be free'd directly but only via the talloc stack.
689 const char *smbXsrv_connection_dbg(const struct smbXsrv_connection *xconn)
694 * TODO: this can be improved later
695 * maybe including the client guid or more
697 addr = tsocket_address_string(xconn->remote_address, talloc_tos());
699 return "<tsocket_address_string() failed>";
702 ret = talloc_asprintf(talloc_tos(), "ptr=%p,id=%llu,addr=%s",
703 xconn, (unsigned long long)xconn->channel_id, addr);
706 return "<talloc_asprintf() failed>";
713 * Initialize a struct smb_request from an inbuf
716 bool init_smb1_request(struct smb_request *req,
717 struct smbd_server_connection *sconn,
718 struct smbXsrv_connection *xconn,
719 const uint8_t *inbuf,
720 size_t unread_bytes, bool encrypted,
723 struct smbXsrv_tcon *tcon;
726 size_t req_size = smb_len(inbuf) + 4;
728 /* Ensure we have at least smb_size bytes. */
729 if (req_size < smb_size) {
730 DEBUG(0,("init_smb1_request: invalid request size %u\n",
731 (unsigned int)req_size ));
735 *req = (struct smb_request) { .cmd = 0};
737 req->request_time = timeval_current();
738 now = timeval_to_nttime(&req->request_time);
740 req->cmd = CVAL(inbuf, smb_com);
741 req->flags2 = SVAL(inbuf, smb_flg2);
742 req->smbpid = SVAL(inbuf, smb_pid);
743 req->mid = (uint64_t)SVAL(inbuf, smb_mid);
744 req->seqnum = seqnum;
745 req->vuid = SVAL(inbuf, smb_uid);
746 req->tid = SVAL(inbuf, smb_tid);
747 req->wct = CVAL(inbuf, smb_wct);
748 req->vwv = (const uint16_t *)(inbuf+smb_vwv);
749 req->buflen = smb_buflen(inbuf);
750 req->buf = (const uint8_t *)smb_buf_const(inbuf);
751 req->unread_bytes = unread_bytes;
752 req->encrypted = encrypted;
756 status = smb1srv_tcon_lookup(xconn, req->tid, now, &tcon);
757 if (NT_STATUS_IS_OK(status)) {
758 req->conn = tcon->compat;
761 req->posix_pathnames = lp_posix_pathnames();
763 /* Ensure we have at least wct words and 2 bytes of bcc. */
764 if (smb_size + req->wct*2 > req_size) {
765 DEBUG(0,("init_smb1_request: invalid wct number %u (size %u)\n",
766 (unsigned int)req->wct,
767 (unsigned int)req_size));
770 /* Ensure bcc is correct. */
771 if (((const uint8_t *)smb_buf_const(inbuf)) + req->buflen > inbuf + req_size) {
772 DEBUG(0,("init_smb1_request: invalid bcc number %u "
773 "(wct = %u, size %u)\n",
774 (unsigned int)req->buflen,
775 (unsigned int)req->wct,
776 (unsigned int)req_size));
783 /****************************************************************************
784 Construct a reply to the incoming packet.
785 ****************************************************************************/
787 static void construct_reply_smb1negprot(struct smbXsrv_connection *xconn,
788 char *inbuf, int size,
791 struct smbd_server_connection *sconn = xconn->client->sconn;
792 struct smb_request *req;
795 if (!(req = talloc(talloc_tos(), struct smb_request))) {
796 smb_panic("could not allocate smb_request");
799 if (!init_smb1_request(req, sconn, xconn, (uint8_t *)inbuf, unread_bytes,
801 exit_server_cleanly("Invalid SMB request");
804 req->inbuf = (uint8_t *)talloc_move(req, &inbuf);
806 status = smb2_multi_protocol_reply_negprot(req);
807 if (req->outbuf == NULL) {
809 * req->outbuf == NULL means we bootstrapped into SMB2.
813 if (!NT_STATUS_IS_OK(status)) {
814 if (!smb1_srv_send(req->xconn,
818 IS_CONN_ENCRYPTED(req->conn) ||
820 exit_server_cleanly("construct_reply_smb1negprot: "
821 "smb1_srv_send failed.");
825 /* This code path should only *ever* bootstrap into SMB2. */
826 exit_server_cleanly("Internal error SMB1negprot didn't reply "
827 "with an SMB2 packet");
831 static void smbd_server_connection_write_handler(
832 struct smbXsrv_connection *xconn)
834 /* TODO: make write nonblocking */
837 static void smbd_smb2_server_connection_read_handler(
838 struct smbXsrv_connection *xconn, int fd)
840 char lenbuf[NBT_HDR_SIZE];
842 uint8_t *buffer = NULL;
843 size_t bufferlen = 0;
845 uint8_t msg_type = 0;
847 /* Read the first 4 bytes - contains length of remainder. */
848 status = read_smb_length_return_keepalive(fd, lenbuf, 0, &len);
849 if (!NT_STATUS_IS_OK(status)) {
850 exit_server_cleanly("failed to receive request length");
854 /* Integer wrap check. */
855 if (len + NBT_HDR_SIZE < len) {
856 exit_server_cleanly("Invalid length on initial request");
861 * The +4 here can't wrap, we've checked the length above already.
863 bufferlen = len+NBT_HDR_SIZE;
865 buffer = talloc_array(talloc_tos(), uint8_t, bufferlen);
866 if (buffer == NULL) {
867 DBG_ERR("Could not allocate request inbuf of length %zu\n",
869 exit_server_cleanly("talloc fail");
873 /* Copy the NBT_HDR_SIZE length. */
874 memcpy(buffer, lenbuf, sizeof(lenbuf));
876 status = read_packet_remainder(fd, (char *)buffer+NBT_HDR_SIZE, 0, len);
877 if (!NT_STATUS_IS_OK(status)) {
878 exit_server_cleanly("Failed to read remainder of initial request");
882 /* Check the message type. */
883 msg_type = PULL_LE_U8(buffer,0);
884 if (msg_type == NBSSrequest) {
886 * clients can send this request before
887 * bootstrapping into SMB2. Cope with this
888 * message only, don't allow any other strange
891 reply_special(xconn, (char *)buffer, bufferlen);
892 xconn->client->sconn->num_requests++;
896 /* Only a 'normal' message type allowed now. */
897 if (msg_type != NBSSmessage) {
898 DBG_ERR("Invalid message type %d\n", msg_type);
899 exit_server_cleanly("Invalid message type for initial request");
903 /* Could this be an SMB1 negprot bootstrap into SMB2 ? */
904 if (bufferlen < smb_size) {
905 exit_server_cleanly("Invalid initial SMB1 or SMB2 packet");
908 if (valid_smb1_header(buffer)) {
909 /* Can *only* allow an SMB1 negprot here. */
910 uint8_t cmd = PULL_LE_U8(buffer, smb_com);
911 if (cmd != SMBnegprot) {
912 DBG_ERR("Incorrect SMB1 command 0x%hhx, "
913 "should be SMBnegprot (0x72)\n",
915 exit_server_cleanly("Invalid initial SMB1 packet");
917 /* Minimal process_smb(). */
918 show_msg((char *)buffer);
919 construct_reply_smb1negprot(xconn, (char *)buffer,
921 xconn->client->sconn->trans_num++;
922 xconn->client->sconn->num_requests++;
925 } else if (!smbd_is_smb2_header(buffer, bufferlen)) {
926 exit_server_cleanly("Invalid initial SMB2 packet");
930 /* Here we know we're a valid SMB2 packet. */
933 * Point at the start of the SMB2 PDU.
934 * len is the length of the SMB2 PDU.
937 status = smbd_smb2_process_negprot(xconn,
939 (const uint8_t *)buffer+NBT_HDR_SIZE,
941 if (!NT_STATUS_IS_OK(status)) {
942 exit_server_cleanly("SMB2 negprot fail");
947 static void smbd_server_connection_handler(struct tevent_context *ev,
948 struct tevent_fd *fde,
952 struct smbXsrv_connection *xconn =
953 talloc_get_type_abort(private_data,
954 struct smbXsrv_connection);
956 if (!NT_STATUS_IS_OK(xconn->transport.status)) {
958 * we're not supposed to do any io
960 TEVENT_FD_NOT_READABLE(xconn->transport.fde);
961 TEVENT_FD_NOT_WRITEABLE(xconn->transport.fde);
965 if (flags & TEVENT_FD_WRITE) {
966 smbd_server_connection_write_handler(xconn);
969 if (flags & TEVENT_FD_READ) {
970 #if defined(WITH_SMB1SERVER)
971 if (lp_server_min_protocol() > PROTOCOL_NT1) {
973 smbd_smb2_server_connection_read_handler(xconn,
974 xconn->transport.sock);
975 #if defined(WITH_SMB1SERVER)
977 smbd_smb1_server_connection_read_handler(xconn,
978 xconn->transport.sock);
985 struct smbd_release_ip_state {
986 struct smbXsrv_connection *xconn;
987 struct tevent_immediate *im;
988 struct sockaddr_storage srv;
989 struct sockaddr_storage clnt;
990 char addr[INET6_ADDRSTRLEN];
993 static int release_ip(struct tevent_context *ev,
1001 static int smbd_release_ip_state_destructor(struct smbd_release_ip_state *s)
1003 struct ctdbd_connection *cconn = messaging_ctdb_connection();
1004 struct smbXsrv_connection *xconn = s->xconn;
1006 if (cconn == NULL) {
1010 if (NT_STATUS_EQUAL(xconn->transport.status, NT_STATUS_CONNECTION_IN_USE)) {
1011 ctdbd_passed_ips(cconn, &s->srv, &s->clnt, release_ip, s);
1013 ctdbd_unregister_ips(cconn, &s->srv, &s->clnt, release_ip, s);
1019 static void smbd_release_ip_immediate(struct tevent_context *ctx,
1020 struct tevent_immediate *im,
1023 struct smbd_release_ip_state *state =
1024 talloc_get_type_abort(private_data,
1025 struct smbd_release_ip_state);
1026 struct smbXsrv_connection *xconn = state->xconn;
1028 if (!NT_STATUS_EQUAL(xconn->transport.status, NT_STATUS_ADDRESS_CLOSED)) {
1030 * smbd_server_connection_terminate() already triggered ?
1035 smbd_server_connection_terminate(xconn, "CTDB_SRVID_RELEASE_IP");
1038 /****************************************************************************
1039 received when we should release a specific IP
1040 ****************************************************************************/
1041 static int release_ip(struct tevent_context *ev,
1042 uint32_t src_vnn, uint32_t dst_vnn,
1044 const uint8_t *msg, size_t msglen,
1047 struct smbd_release_ip_state *state =
1048 talloc_get_type_abort(private_data,
1049 struct smbd_release_ip_state);
1050 struct smbXsrv_connection *xconn = state->xconn;
1052 const char *addr = state->addr;
1053 const char *p = addr;
1058 if (msg[msglen-1] != '\0') {
1062 ip = (const char *)msg;
1064 if (!NT_STATUS_IS_OK(xconn->transport.status)) {
1065 /* avoid recursion */
1069 if (strncmp("::ffff:", addr, 7) == 0) {
1073 DEBUG(10, ("Got release IP message for %s, "
1074 "our address is %s\n", ip, p));
1076 if ((strcmp(p, ip) == 0) || ((p != addr) && strcmp(addr, ip) == 0)) {
1077 DEBUG(0,("Got release IP message for our IP %s - exiting immediately\n",
1080 * With SMB2 we should do a clean disconnect,
1081 * the previous_session_id in the session setup
1082 * will cleanup the old session, tcons and opens.
1084 * A clean disconnect is needed in order to support
1087 * Note: typically this is never triggered
1088 * as we got a TCP RST (triggered by ctdb event scripts)
1089 * before we get CTDB_SRVID_RELEASE_IP.
1091 * We used to call _exit(1) here, but as this was mostly never
1092 * triggered and has implication on our process model,
1093 * we can just use smbd_server_connection_terminate()
1096 * We don't call smbd_server_connection_terminate() directly
1097 * as we might be called from within ctdbd_migrate(),
1098 * we need to defer our action to the next event loop
1100 tevent_schedule_immediate(state->im,
1101 xconn->client->raw_ev_ctx,
1102 smbd_release_ip_immediate,
1106 * Make sure we don't get any io on the connection.
1108 xconn->transport.status = NT_STATUS_ADDRESS_CLOSED;
1109 return EADDRNOTAVAIL;
1115 static int match_cluster_movable_ip(uint32_t total_ip_count,
1116 const struct sockaddr_storage *ip,
1120 const struct sockaddr_storage *srv = private_data;
1121 struct samba_sockaddr pub_ip = {
1126 struct samba_sockaddr srv_ip = {
1132 if (is_movable_ip && sockaddr_equal(&pub_ip.u.sa, &srv_ip.u.sa)) {
1133 return EADDRNOTAVAIL;
1139 static NTSTATUS smbd_register_ips(struct smbXsrv_connection *xconn,
1140 struct sockaddr_storage *srv,
1141 struct sockaddr_storage *clnt)
1143 struct smbd_release_ip_state *state;
1144 struct ctdbd_connection *cconn;
1147 cconn = messaging_ctdb_connection();
1148 if (cconn == NULL) {
1149 return NT_STATUS_NO_MEMORY;
1152 state = talloc_zero(xconn, struct smbd_release_ip_state);
1153 if (state == NULL) {
1154 return NT_STATUS_NO_MEMORY;
1156 state->xconn = xconn;
1157 state->im = tevent_create_immediate(state);
1158 if (state->im == NULL) {
1159 return NT_STATUS_NO_MEMORY;
1162 state->clnt = *clnt;
1163 if (print_sockaddr(state->addr, sizeof(state->addr), srv) == NULL) {
1164 return NT_STATUS_NO_MEMORY;
1167 if (xconn->client->server_multi_channel_enabled) {
1168 ret = ctdbd_public_ip_foreach(cconn,
1169 match_cluster_movable_ip,
1171 if (ret == EADDRNOTAVAIL) {
1172 xconn->has_cluster_movable_ip = true;
1173 DBG_DEBUG("cluster movable IP on %s\n",
1174 smbXsrv_connection_dbg(xconn));
1175 } else if (ret != 0) {
1176 DBG_ERR("failed to iterate cluster IPs: %s\n",
1178 return NT_STATUS_INTERNAL_ERROR;
1182 ret = ctdbd_register_ips(cconn, srv, clnt, release_ip, state);
1184 return map_nt_error_from_unix(ret);
1187 talloc_set_destructor(state, smbd_release_ip_state_destructor);
1189 return NT_STATUS_OK;
1192 static int smbXsrv_connection_destructor(struct smbXsrv_connection *xconn)
1194 DBG_DEBUG("xconn[%s]\n", smbXsrv_connection_dbg(xconn));
1198 NTSTATUS smbd_add_connection(struct smbXsrv_client *client, int sock_fd,
1199 NTTIME now, struct smbXsrv_connection **_xconn)
1201 TALLOC_CTX *frame = talloc_stackframe();
1202 struct smbXsrv_connection *xconn;
1203 struct sockaddr_storage ss_srv;
1204 void *sp_srv = (void *)&ss_srv;
1205 struct sockaddr *sa_srv = (struct sockaddr *)sp_srv;
1206 struct sockaddr_storage ss_clnt;
1207 void *sp_clnt = (void *)&ss_clnt;
1208 struct sockaddr *sa_clnt = (struct sockaddr *)sp_clnt;
1209 socklen_t sa_socklen;
1210 struct tsocket_address *local_address = NULL;
1211 struct tsocket_address *remote_address = NULL;
1212 const char *remaddr = NULL;
1214 const char *rhost = NULL;
1220 DO_PROFILE_INC(connect);
1222 xconn = talloc_zero(client, struct smbXsrv_connection);
1223 if (xconn == NULL) {
1224 DEBUG(0,("talloc_zero(struct smbXsrv_connection)\n"));
1226 return NT_STATUS_NO_MEMORY;
1228 talloc_set_destructor(xconn, smbXsrv_connection_destructor);
1229 talloc_steal(frame, xconn);
1230 xconn->client = client;
1231 xconn->connect_time = now;
1232 if (client->next_channel_id != 0) {
1233 xconn->channel_id = client->next_channel_id++;
1236 xconn->transport.sock = sock_fd;
1237 #if defined(WITH_SMB1SERVER)
1238 smbd_echo_init(xconn);
1240 xconn->protocol = PROTOCOL_NONE;
1242 /* Ensure child is set to blocking mode */
1243 set_blocking(sock_fd,True);
1245 set_socket_options(sock_fd, "SO_KEEPALIVE");
1246 set_socket_options(sock_fd, lp_socket_options());
1248 sa_socklen = sizeof(ss_clnt);
1249 ret = getpeername(sock_fd, sa_clnt, &sa_socklen);
1251 int saved_errno = errno;
1252 int level = (errno == ENOTCONN)?2:0;
1253 DEBUG(level,("getpeername() failed - %s\n",
1254 strerror(saved_errno)));
1256 return map_nt_error_from_unix_common(saved_errno);
1258 ret = tsocket_address_bsd_from_sockaddr(xconn,
1259 sa_clnt, sa_socklen,
1262 int saved_errno = errno;
1263 DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
1264 __location__, strerror(saved_errno)));
1266 return map_nt_error_from_unix_common(saved_errno);
1269 sa_socklen = sizeof(ss_srv);
1270 ret = getsockname(sock_fd, sa_srv, &sa_socklen);
1272 int saved_errno = errno;
1273 int level = (errno == ENOTCONN)?2:0;
1274 DEBUG(level,("getsockname() failed - %s\n",
1275 strerror(saved_errno)));
1277 return map_nt_error_from_unix_common(saved_errno);
1279 ret = tsocket_address_bsd_from_sockaddr(xconn,
1283 int saved_errno = errno;
1284 DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
1285 __location__, strerror(saved_errno)));
1287 return map_nt_error_from_unix_common(saved_errno);
1290 if (tsocket_address_is_inet(remote_address, "ip")) {
1291 remaddr = tsocket_address_inet_addr_string(remote_address,
1293 if (remaddr == NULL) {
1294 DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
1295 __location__, strerror(errno)));
1297 return NT_STATUS_NO_MEMORY;
1300 remaddr = "0.0.0.0";
1304 * Before the first packet, check the global hosts allow/ hosts deny
1305 * parameters before doing any parsing of packets passed to us by the
1306 * client. This prevents attacks on our parsing code from hosts not in
1307 * the hosts allow list.
1310 ret = get_remote_hostname(remote_address,
1313 int saved_errno = errno;
1314 DEBUG(0,("%s: get_remote_hostname failed - %s\n",
1315 __location__, strerror(saved_errno)));
1317 return map_nt_error_from_unix_common(saved_errno);
1320 if (strequal(rhost, "UNKNOWN")) {
1324 xconn->local_address = local_address;
1325 xconn->remote_address = remote_address;
1326 xconn->remote_hostname = talloc_strdup(xconn, rhost);
1327 if (xconn->remote_hostname == NULL) {
1328 return NT_STATUS_NO_MEMORY;
1331 if (!srv_init_signing(xconn)) {
1332 DEBUG(0, ("Failed to init smb_signing\n"));
1334 return NT_STATUS_INTERNAL_ERROR;
1337 if (!allow_access(lp_hosts_deny(-1), lp_hosts_allow(-1),
1338 xconn->remote_hostname,
1340 DEBUG( 1, ("Connection denied from %s to %s\n",
1341 tsocket_address_string(remote_address, talloc_tos()),
1342 tsocket_address_string(local_address, talloc_tos())));
1345 * We return a valid xconn
1346 * so that the caller can return an error message
1349 DLIST_ADD_END(client->connections, xconn);
1350 talloc_steal(client, xconn);
1354 return NT_STATUS_NETWORK_ACCESS_DENIED;
1357 DEBUG(10, ("Connection allowed from %s to %s\n",
1358 tsocket_address_string(remote_address, talloc_tos()),
1359 tsocket_address_string(local_address, talloc_tos())));
1361 if (lp_clustering()) {
1363 * We need to tell ctdb about our client's TCP
1364 * connection, so that for failover ctdbd can send
1365 * tickle acks, triggering a reconnection by the
1370 status = smbd_register_ips(xconn, &ss_srv, &ss_clnt);
1371 if (!NT_STATUS_IS_OK(status)) {
1372 DEBUG(0, ("ctdbd_register_ips failed: %s\n",
1373 nt_errstr(status)));
1377 tmp = lp_max_xmit();
1378 tmp = MAX(tmp, SMB_BUFFER_SIZE_MIN);
1379 tmp = MIN(tmp, SMB_BUFFER_SIZE_MAX);
1381 #if defined(WITH_SMB1SERVER)
1382 xconn->smb1.negprot.max_recv = tmp;
1384 xconn->smb1.sessions.done_sesssetup = false;
1385 xconn->smb1.sessions.max_send = SMB_BUFFER_SIZE_MAX;
1388 xconn->transport.fde = tevent_add_fd(client->raw_ev_ctx,
1392 smbd_server_connection_handler,
1394 if (!xconn->transport.fde) {
1396 return NT_STATUS_NO_MEMORY;
1398 tevent_fd_set_auto_close(xconn->transport.fde);
1400 /* for now we only have one connection */
1401 DLIST_ADD_END(client->connections, xconn);
1402 talloc_steal(client, xconn);
1406 return NT_STATUS_OK;
1409 static bool uid_in_use(struct auth_session_info *session_info,
1412 if (session_info->unix_token->uid == uid) {
1418 static bool gid_in_use(struct auth_session_info *session_info,
1422 struct security_unix_token *utok = NULL;
1424 utok = session_info->unix_token;
1425 if (utok->gid == gid) {
1429 for(i = 0; i < utok->ngroups; i++) {
1430 if (utok->groups[i] == gid) {
1437 static bool sid_in_use(struct auth_session_info *session_info,
1438 const struct dom_sid *psid)
1440 struct security_token *tok = NULL;
1442 tok = session_info->security_token;
1445 * Not sure session_info->security_token can
1446 * ever be NULL. This check might be not
1451 if (security_token_has_sid(tok, psid)) {
1457 struct id_in_use_state {
1458 const struct id_cache_ref *id;
1462 static int id_in_use_cb(struct smbXsrv_session *session,
1465 struct id_in_use_state *state = (struct id_in_use_state *)
1467 struct auth_session_info *session_info =
1468 session->global->auth_session_info;
1470 switch(state->id->type) {
1472 state->match = uid_in_use(session_info, state->id->id.uid);
1475 state->match = gid_in_use(session_info, state->id->id.gid);
1478 state->match = sid_in_use(session_info, &state->id->id.sid);
1481 state->match = false;
1490 static bool id_in_use(struct smbd_server_connection *sconn,
1491 const struct id_cache_ref *id)
1493 struct id_in_use_state state;
1496 state = (struct id_in_use_state) {
1501 status = smbXsrv_session_local_traverse(sconn->client,
1504 if (!NT_STATUS_IS_OK(status)) {
1511 /****************************************************************************
1512 Check if services need reloading.
1513 ****************************************************************************/
1515 static void check_reload(struct smbd_server_connection *sconn, time_t t)
1518 if (last_smb_conf_reload_time == 0) {
1519 last_smb_conf_reload_time = t;
1522 if (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK) {
1523 reload_services(sconn, conn_snum_used, true);
1524 last_smb_conf_reload_time = t;
1528 static void msg_kill_client_ip(struct messaging_context *msg_ctx,
1529 void *private_data, uint32_t msg_type,
1530 struct server_id server_id, DATA_BLOB *data)
1532 struct smbd_server_connection *sconn = talloc_get_type_abort(
1533 private_data, struct smbd_server_connection);
1534 const char *ip = (char *) data->data;
1537 DBG_DEBUG("Got kill request for client IP %s\n", ip);
1539 client_ip = tsocket_address_inet_addr_string(sconn->remote_address,
1541 if (client_ip == NULL) {
1545 if (strequal(ip, client_ip)) {
1546 DBG_WARNING("Got kill client message for %s - "
1547 "exiting immediately\n", ip);
1548 exit_server_cleanly("Forced disconnect for client");
1551 TALLOC_FREE(client_ip);
1555 * Do the recurring check if we're idle
1557 static bool deadtime_fn(const struct timeval *now, void *private_data)
1559 struct smbd_server_connection *sconn =
1560 (struct smbd_server_connection *)private_data;
1562 if ((conn_num_open(sconn) == 0)
1563 || (conn_idle_all(sconn, now->tv_sec))) {
1564 DEBUG( 2, ( "Closing idle connection\n" ) );
1565 messaging_send(sconn->msg_ctx,
1566 messaging_server_id(sconn->msg_ctx),
1567 MSG_SHUTDOWN, &data_blob_null);
1575 * Do the recurring log file and smb.conf reload checks.
1578 static bool housekeeping_fn(const struct timeval *now, void *private_data)
1580 struct smbd_server_connection *sconn = talloc_get_type_abort(
1581 private_data, struct smbd_server_connection);
1583 DEBUG(5, ("housekeeping\n"));
1585 change_to_root_user();
1587 /* check if we need to reload services */
1588 check_reload(sconn, time_mono(NULL));
1591 * Force a log file check.
1593 force_check_log_size();
1598 static void smbd_sig_term_handler(struct tevent_context *ev,
1599 struct tevent_signal *se,
1605 exit_server_cleanly("termination signal");
1608 static void smbd_setup_sig_term_handler(struct smbd_server_connection *sconn)
1610 struct tevent_signal *se;
1612 se = tevent_add_signal(sconn->ev_ctx,
1615 smbd_sig_term_handler,
1618 exit_server("failed to setup SIGTERM handler");
1622 static void smbd_sig_hup_handler(struct tevent_context *ev,
1623 struct tevent_signal *se,
1629 struct smbd_server_connection *sconn =
1630 talloc_get_type_abort(private_data,
1631 struct smbd_server_connection);
1633 change_to_root_user();
1634 DEBUG(1,("Reloading services after SIGHUP\n"));
1635 reload_services(sconn, conn_snum_used, false);
1638 static void smbd_setup_sig_hup_handler(struct smbd_server_connection *sconn)
1640 struct tevent_signal *se;
1642 se = tevent_add_signal(sconn->ev_ctx,
1645 smbd_sig_hup_handler,
1648 exit_server("failed to setup SIGHUP handler");
1652 static void smbd_conf_updated(struct messaging_context *msg,
1655 struct server_id server_id,
1658 struct smbd_server_connection *sconn =
1659 talloc_get_type_abort(private_data,
1660 struct smbd_server_connection);
1662 DEBUG(10,("smbd_conf_updated: Got message saying smb.conf was "
1663 "updated. Reloading.\n"));
1664 change_to_root_user();
1665 reload_services(sconn, conn_snum_used, false);
1668 static void smbd_id_cache_kill(struct messaging_context *msg_ctx,
1671 struct server_id server_id,
1674 const char *msg = (data && data->data)
1675 ? (const char *)data->data : "<NULL>";
1676 struct id_cache_ref id;
1677 struct smbd_server_connection *sconn =
1678 talloc_get_type_abort(private_data,
1679 struct smbd_server_connection);
1681 if (!id_cache_ref_parse(msg, &id)) {
1682 DEBUG(0, ("Invalid ?ID: %s\n", msg));
1686 if (id_in_use(sconn, &id)) {
1687 exit_server_cleanly(msg);
1689 id_cache_delete_from_cache(&id);
1692 struct smbd_tevent_trace_state {
1693 struct tevent_context *ev;
1695 SMBPROFILE_BASIC_ASYNC_STATE(profile_idle);
1698 static inline void smbd_tevent_trace_callback_before_loop_once(
1699 struct smbd_tevent_trace_state *state)
1701 talloc_free(state->frame);
1702 state->frame = talloc_stackframe_pool(8192);
1705 static inline void smbd_tevent_trace_callback_after_loop_once(
1706 struct smbd_tevent_trace_state *state)
1708 TALLOC_FREE(state->frame);
1711 static void smbd_tevent_trace_callback(enum tevent_trace_point point,
1714 struct smbd_tevent_trace_state *state =
1715 (struct smbd_tevent_trace_state *)private_data;
1718 case TEVENT_TRACE_BEFORE_WAIT:
1720 case TEVENT_TRACE_AFTER_WAIT:
1722 case TEVENT_TRACE_BEFORE_LOOP_ONCE:
1723 smbd_tevent_trace_callback_before_loop_once(state);
1725 case TEVENT_TRACE_AFTER_LOOP_ONCE:
1726 smbd_tevent_trace_callback_after_loop_once(state);
1733 static void smbd_tevent_trace_callback_profile(enum tevent_trace_point point,
1736 struct smbd_tevent_trace_state *state =
1737 (struct smbd_tevent_trace_state *)private_data;
1740 case TEVENT_TRACE_BEFORE_WAIT:
1741 if (!smbprofile_dump_pending()) {
1743 * If there's no dump pending
1744 * we don't want to schedule a new 1 sec timer.
1746 * Instead we want to sleep as long as nothing happens.
1748 smbprofile_dump_setup(NULL);
1750 SMBPROFILE_BASIC_ASYNC_START(idle, profile_p, state->profile_idle);
1752 case TEVENT_TRACE_AFTER_WAIT:
1753 SMBPROFILE_BASIC_ASYNC_END(state->profile_idle);
1754 if (!smbprofile_dump_pending()) {
1756 * We need to flush our state after sleeping
1757 * (hopefully a long time).
1761 * future profiling events should trigger timers
1762 * on our main event context.
1764 smbprofile_dump_setup(state->ev);
1767 case TEVENT_TRACE_BEFORE_LOOP_ONCE:
1768 smbd_tevent_trace_callback_before_loop_once(state);
1770 case TEVENT_TRACE_AFTER_LOOP_ONCE:
1771 smbd_tevent_trace_callback_after_loop_once(state);
1778 /****************************************************************************
1779 Process commands from the client
1780 ****************************************************************************/
1782 void smbd_process(struct tevent_context *ev_ctx,
1783 struct messaging_context *msg_ctx,
1787 struct smbd_tevent_trace_state trace_state = {
1789 .frame = talloc_stackframe(),
1791 const struct loadparm_substitution *lp_sub =
1792 loadparm_s3_global_substitution();
1793 struct smbXsrv_client *client = NULL;
1794 struct smbd_server_connection *sconn = NULL;
1795 struct smbXsrv_connection *xconn = NULL;
1796 const char *locaddr = NULL;
1797 const char *remaddr = NULL;
1800 struct timeval tv = timeval_current();
1801 NTTIME now = timeval_to_nttime(&tv);
1802 char *chroot_dir = NULL;
1805 status = smbXsrv_client_create(ev_ctx, ev_ctx, msg_ctx, now, &client);
1806 if (!NT_STATUS_IS_OK(status)) {
1807 DBG_ERR("smbXsrv_client_create(): %s\n", nt_errstr(status));
1808 exit_server_cleanly("talloc_zero(struct smbXsrv_client).\n");
1812 * TODO: remove this...:-)
1814 global_smbXsrv_client = client;
1816 sconn = talloc_zero(client, struct smbd_server_connection);
1817 if (sconn == NULL) {
1818 exit_server("failed to create smbd_server_connection");
1821 client->sconn = sconn;
1822 sconn->client = client;
1824 sconn->ev_ctx = ev_ctx;
1825 sconn->msg_ctx = msg_ctx;
1827 ret = pthreadpool_tevent_init(sconn, lp_aio_max_threads(),
1830 exit_server("pthreadpool_tevent_init() failed.");
1833 #if defined(WITH_SMB1SERVER)
1834 if (lp_server_max_protocol() >= PROTOCOL_SMB2_02) {
1837 * We're not making the decision here,
1838 * we're just allowing the client
1839 * to decide between SMB1 and SMB2
1840 * with the first negprot
1843 sconn->using_smb2 = true;
1844 #if defined(WITH_SMB1SERVER)
1849 smbd_setup_sig_term_handler(sconn);
1850 smbd_setup_sig_hup_handler(sconn);
1853 status = smbd_add_connection(client, sock_fd, now, &xconn);
1854 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
1856 * send a negative session response "not listening on calling
1859 unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
1860 (void)smb1_srv_send(xconn, (char *)buf, false, 0, false);
1861 exit_server_cleanly("connection denied");
1862 } else if (!NT_STATUS_IS_OK(status)) {
1863 exit_server_cleanly(nt_errstr(status));
1866 sconn->local_address =
1867 tsocket_address_copy(xconn->local_address, sconn);
1868 if (sconn->local_address == NULL) {
1869 exit_server_cleanly("tsocket_address_copy() failed");
1871 sconn->remote_address =
1872 tsocket_address_copy(xconn->remote_address, sconn);
1873 if (sconn->remote_address == NULL) {
1874 exit_server_cleanly("tsocket_address_copy() failed");
1876 sconn->remote_hostname =
1877 talloc_strdup(sconn, xconn->remote_hostname);
1878 if (sconn->remote_hostname == NULL) {
1879 exit_server_cleanly("tsocket_strdup() failed");
1882 client->global->local_address =
1883 tsocket_address_string(sconn->local_address,
1885 if (client->global->local_address == NULL) {
1886 exit_server_cleanly("tsocket_address_string() failed");
1888 client->global->remote_address =
1889 tsocket_address_string(sconn->remote_address,
1891 if (client->global->remote_address == NULL) {
1892 exit_server_cleanly("tsocket_address_string() failed");
1894 client->global->remote_name =
1895 talloc_strdup(client->global, sconn->remote_hostname);
1896 if (client->global->remote_name == NULL) {
1897 exit_server_cleanly("tsocket_strdup() failed");
1900 if (tsocket_address_is_inet(sconn->local_address, "ip")) {
1901 locaddr = tsocket_address_inet_addr_string(
1902 sconn->local_address,
1904 if (locaddr == NULL) {
1905 DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
1906 __location__, strerror(errno)));
1907 exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
1910 locaddr = "0.0.0.0";
1913 if (tsocket_address_is_inet(sconn->remote_address, "ip")) {
1914 remaddr = tsocket_address_inet_addr_string(
1915 sconn->remote_address,
1917 if (remaddr == NULL) {
1918 DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
1919 __location__, strerror(errno)));
1920 exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
1923 remaddr = "0.0.0.0";
1926 /* this is needed so that we get decent entries
1927 in smbstatus for port 445 connects */
1928 set_remote_machine_name(remaddr, false);
1929 reload_services(sconn, conn_snum_used, true);
1930 sub_set_socket_ids(remaddr,
1931 sconn->remote_hostname,
1934 if (lp_preload_modules()) {
1935 smb_load_all_modules_absoute_path(lp_preload_modules());
1938 if (!init_account_policy()) {
1939 exit_server("Could not open account policy tdb.\n");
1942 chroot_dir = lp_root_directory(talloc_tos(), lp_sub);
1943 if (chroot_dir[0] != '\0') {
1944 rc = chdir(chroot_dir);
1946 DBG_ERR("Failed to chdir to %s\n", chroot_dir);
1947 exit_server("Failed to chdir()");
1950 rc = chroot(chroot_dir);
1952 DBG_ERR("Failed to change root to %s\n", chroot_dir);
1953 exit_server("Failed to chroot()");
1955 DBG_WARNING("Changed root to %s\n", chroot_dir);
1957 TALLOC_FREE(chroot_dir);
1960 if (!file_init(sconn)) {
1961 exit_server("file_init() failed");
1965 if (!init_oplocks(sconn))
1966 exit_server("Failed to init oplocks");
1968 /* register our message handlers */
1969 messaging_register(sconn->msg_ctx, sconn,
1970 MSG_SMB_FORCE_TDIS, msg_force_tdis);
1974 MSG_SMB_FORCE_TDIS_DENIED,
1975 msg_force_tdis_denied);
1976 messaging_register(sconn->msg_ctx, sconn,
1977 MSG_SMB_CLOSE_FILE, msg_close_file);
1978 messaging_register(sconn->msg_ctx, sconn,
1979 MSG_SMB_FILE_RENAME, msg_file_was_renamed);
1981 id_cache_register_msgs(sconn->msg_ctx);
1982 messaging_deregister(sconn->msg_ctx, ID_CACHE_KILL, NULL);
1983 messaging_register(sconn->msg_ctx, sconn,
1984 ID_CACHE_KILL, smbd_id_cache_kill);
1986 messaging_deregister(sconn->msg_ctx,
1987 MSG_SMB_CONF_UPDATED, sconn->ev_ctx);
1988 messaging_register(sconn->msg_ctx, sconn,
1989 MSG_SMB_CONF_UPDATED, smbd_conf_updated);
1991 messaging_deregister(sconn->msg_ctx, MSG_SMB_KILL_CLIENT_IP,
1993 messaging_register(sconn->msg_ctx, sconn,
1994 MSG_SMB_KILL_CLIENT_IP,
1995 msg_kill_client_ip);
1997 messaging_deregister(sconn->msg_ctx, MSG_SMB_TELL_NUM_CHILDREN, NULL);
2000 * Use the default MSG_DEBUG handler to avoid rebroadcasting
2001 * MSGs to all child processes
2003 messaging_deregister(sconn->msg_ctx,
2005 messaging_register(sconn->msg_ctx, NULL,
2006 MSG_DEBUG, debug_message);
2008 #if defined(WITH_SMB1SERVER)
2009 if ((lp_keepalive() != 0)
2010 && !(event_add_idle(ev_ctx, NULL,
2011 timeval_set(lp_keepalive(), 0),
2012 "keepalive", keepalive_fn,
2014 DEBUG(0, ("Could not add keepalive event\n"));
2019 if (!(event_add_idle(ev_ctx, NULL,
2020 timeval_set(IDLE_CLOSED_TIMEOUT, 0),
2021 "deadtime", deadtime_fn, sconn))) {
2022 DEBUG(0, ("Could not add deadtime event\n"));
2026 if (!(event_add_idle(ev_ctx, NULL,
2027 timeval_set(SMBD_HOUSEKEEPING_INTERVAL, 0),
2028 "housekeeping", housekeeping_fn, sconn))) {
2029 DEBUG(0, ("Could not add housekeeping event\n"));
2033 smbprofile_dump_setup(ev_ctx);
2035 if (!init_dptrs(sconn)) {
2036 exit_server("init_dptrs() failed");
2039 TALLOC_FREE(trace_state.frame);
2041 if (smbprofile_active()) {
2042 tevent_set_trace_callback(ev_ctx,
2043 smbd_tevent_trace_callback_profile,
2046 tevent_set_trace_callback(ev_ctx,
2047 smbd_tevent_trace_callback,
2051 ret = tevent_loop_wait(ev_ctx);
2053 DEBUG(1, ("tevent_loop_wait failed: %d, %s,"
2054 " exiting\n", ret, strerror(errno)));
2057 TALLOC_FREE(trace_state.frame);
2059 exit_server_cleanly(NULL);