s3: smbd: Make extract_snapshot_token() a wrapper for extract_snapshot_token_internal().
[Samba.git] / source3 / smbd / smb2_process.c
blobad4386e08a40246e764a2bff249a609473a8ad3d
1 /*
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/>.
21 #include "includes.h"
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"
33 #include "passdb.h"
34 #include "auth.h"
35 #include "messages.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"
51 /* Internal message queue for deferred opens. */
52 struct pending_message_list {
53 struct pending_message_list *next, *prev;
54 struct timeval request_time; /* When was this first issued? */
55 struct smbd_server_connection *sconn;
56 struct smbXsrv_connection *xconn;
57 struct tevent_timer *te;
58 struct smb_perfcount_data pcd;
59 uint32_t seqnum;
60 bool encrypted;
61 bool processed;
62 DATA_BLOB buf;
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 bool smb2_srv_send(struct smbXsrv_connection *xconn, char *buffer,
70 bool do_signing, uint32_t seqnum,
71 bool do_encrypt,
72 struct smb_perfcount_data *pcd)
74 size_t len = 0;
75 ssize_t ret;
76 char *buf_out = buffer;
78 if (!NT_STATUS_IS_OK(xconn->transport.status)) {
80 * we're not supposed to do any io
82 return true;
85 len = smb_len_large(buf_out) + 4;
87 ret = write_data(xconn->transport.sock, buf_out, len);
88 if (ret <= 0) {
89 int saved_errno = errno;
91 * Try and give an error message saying what
92 * client failed.
94 DEBUG(1,("pid[%d] Error writing %d bytes to client %s. %d. (%s)\n",
95 (int)getpid(), (int)len,
96 smbXsrv_connection_dbg(xconn),
97 (int)ret, strerror(saved_errno)));
98 errno = saved_errno;
100 srv_free_enc_buffer(xconn, buf_out);
101 goto out;
104 SMB_PERFCOUNT_SET_MSGLEN_OUT(pcd, len);
105 srv_free_enc_buffer(xconn, buf_out);
106 out:
107 SMB_PERFCOUNT_END(pcd);
109 return (ret > 0);
112 #if !defined(WITH_SMB1SERVER)
113 bool smb1_srv_send(struct smbXsrv_connection *xconn, char *buffer,
114 bool do_signing, uint32_t seqnum,
115 bool do_encrypt,
116 struct smb_perfcount_data *pcd)
118 size_t len = 0;
119 ssize_t ret;
120 len = smb_len_large(buffer) + 4;
121 ret = write_data(xconn->transport.sock, buffer, len);
122 return (ret > 0);
124 #endif
126 /*******************************************************************
127 Setup the word count and byte count for a smb1 message.
128 ********************************************************************/
130 size_t srv_smb1_set_message(char *buf,
131 size_t num_words,
132 size_t num_bytes,
133 bool zero)
135 if (zero && (num_words || num_bytes)) {
136 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
138 SCVAL(buf,smb_wct,num_words);
139 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
140 smb_setlen(buf,(smb_size + num_words*2 + num_bytes - 4));
141 return (smb_size + num_words*2 + num_bytes);
144 NTSTATUS read_packet_remainder(int fd, char *buffer,
145 unsigned int timeout, ssize_t len)
147 NTSTATUS status;
149 if (len <= 0) {
150 return NT_STATUS_OK;
153 status = read_fd_with_timeout(fd, buffer, len, len, timeout, NULL);
154 if (!NT_STATUS_IS_OK(status)) {
155 char addr[INET6_ADDRSTRLEN];
156 DEBUG(0, ("read_fd_with_timeout failed for client %s read "
157 "error = %s.\n",
158 get_peer_addr(fd, addr, sizeof(addr)),
159 nt_errstr(status)));
161 return status;
164 #if !defined(WITH_SMB1SERVER)
165 static NTSTATUS smb2_receive_raw_talloc(TALLOC_CTX *mem_ctx,
166 struct smbXsrv_connection *xconn,
167 int sock,
168 char **buffer, unsigned int timeout,
169 size_t *p_unread, size_t *plen)
171 char lenbuf[4];
172 size_t len;
173 NTSTATUS status;
175 *p_unread = 0;
177 status = read_smb_length_return_keepalive(sock, lenbuf, timeout,
178 &len);
179 if (!NT_STATUS_IS_OK(status)) {
180 return status;
184 * The +4 here can't wrap, we've checked the length above already.
187 *buffer = talloc_array(mem_ctx, char, len+4);
189 if (*buffer == NULL) {
190 DEBUG(0, ("Could not allocate inbuf of length %d\n",
191 (int)len+4));
192 return NT_STATUS_NO_MEMORY;
195 memcpy(*buffer, lenbuf, sizeof(lenbuf));
197 status = read_packet_remainder(sock, (*buffer)+4, timeout, len);
198 if (!NT_STATUS_IS_OK(status)) {
199 return status;
202 *plen = len + 4;
203 return NT_STATUS_OK;
206 static NTSTATUS smb2_receive_talloc(TALLOC_CTX *mem_ctx,
207 struct smbXsrv_connection *xconn,
208 int sock,
209 char **buffer, unsigned int timeout,
210 size_t *p_unread, bool *p_encrypted,
211 size_t *p_len,
212 uint32_t *seqnum,
213 bool trusted_channel)
215 size_t len = 0;
216 NTSTATUS status;
218 *p_encrypted = false;
220 status = smb2_receive_raw_talloc(mem_ctx, xconn, sock, buffer, timeout,
221 p_unread, &len);
222 if (!NT_STATUS_IS_OK(status)) {
223 DEBUG(NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)?5:1,
224 ("smb2_receive_raw_talloc failed for client %s "
225 "read error = %s.\n",
226 smbXsrv_connection_dbg(xconn),
227 nt_errstr(status)) );
228 return status;
231 *p_len = len;
232 return NT_STATUS_OK;
234 #endif
236 NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,
237 struct smbXsrv_connection *xconn,
238 int sock,
239 char **buffer, unsigned int timeout,
240 size_t *p_unread, bool *p_encrypted,
241 size_t *p_len,
242 uint32_t *seqnum,
243 bool trusted_channel)
245 #if defined(WITH_SMB1SERVER)
246 return smb1_receive_talloc(mem_ctx, xconn, sock, buffer, timeout,
247 p_unread, p_encrypted, p_len, seqnum,
248 trusted_channel);
249 #else
250 return smb2_receive_talloc(mem_ctx, xconn, sock, buffer, timeout,
251 p_unread, p_encrypted, p_len, seqnum,
252 trusted_channel);
253 #endif
256 /****************************************************************************
257 Function to delete a sharing violation open message by mid.
258 ****************************************************************************/
260 void remove_deferred_open_message_smb(struct smbXsrv_connection *xconn,
261 uint64_t mid)
263 struct smbd_server_connection *sconn = xconn->client->sconn;
264 struct pending_message_list *pml;
266 if (sconn->using_smb2) {
267 remove_deferred_open_message_smb2(xconn, mid);
268 return;
271 for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
272 if (mid == (uint64_t)SVAL(pml->buf.data,smb_mid)) {
273 DEBUG(10,("remove_deferred_open_message_smb: "
274 "deleting mid %llu len %u\n",
275 (unsigned long long)mid,
276 (unsigned int)pml->buf.length ));
277 DLIST_REMOVE(sconn->deferred_open_queue, pml);
278 TALLOC_FREE(pml);
279 return;
284 static void smbd_deferred_open_timer(struct tevent_context *ev,
285 struct tevent_timer *te,
286 struct timeval _tval,
287 void *private_data)
289 struct pending_message_list *msg = talloc_get_type(private_data,
290 struct pending_message_list);
291 struct smbd_server_connection *sconn = msg->sconn;
292 struct smbXsrv_connection *xconn = msg->xconn;
293 TALLOC_CTX *mem_ctx = talloc_tos();
294 uint64_t mid = (uint64_t)SVAL(msg->buf.data,smb_mid);
295 uint8_t *inbuf;
297 inbuf = (uint8_t *)talloc_memdup(mem_ctx, msg->buf.data,
298 msg->buf.length);
299 if (inbuf == NULL) {
300 exit_server("smbd_deferred_open_timer: talloc failed\n");
301 return;
304 /* We leave this message on the queue so the open code can
305 know this is a retry. */
306 DEBUG(5,("smbd_deferred_open_timer: trigger mid %llu.\n",
307 (unsigned long long)mid ));
309 /* Mark the message as processed so this is not
310 * re-processed in error. */
311 msg->processed = true;
313 process_smb(xconn, inbuf,
314 msg->buf.length, 0,
315 msg->seqnum, msg->encrypted, &msg->pcd);
317 /* If it's still there and was processed, remove it. */
318 msg = get_deferred_open_message_smb(sconn, mid);
319 if (msg && msg->processed) {
320 remove_deferred_open_message_smb(xconn, mid);
324 /****************************************************************************
325 Move a sharing violation open retry message to the front of the list and
326 schedule it for immediate processing.
327 ****************************************************************************/
329 bool schedule_deferred_open_message_smb(struct smbXsrv_connection *xconn,
330 uint64_t mid)
332 struct smbd_server_connection *sconn = xconn->client->sconn;
333 struct pending_message_list *pml;
334 int i = 0;
336 if (sconn->using_smb2) {
337 return schedule_deferred_open_message_smb2(xconn, mid);
340 for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
341 uint64_t msg_mid = (uint64_t)SVAL(pml->buf.data,smb_mid);
343 DEBUG(10,("schedule_deferred_open_message_smb: [%d] "
344 "msg_mid = %llu\n",
345 i++,
346 (unsigned long long)msg_mid ));
348 if (mid == msg_mid) {
349 struct tevent_timer *te;
351 if (pml->processed) {
352 /* A processed message should not be
353 * rescheduled. */
354 DEBUG(0,("schedule_deferred_open_message_smb: LOGIC ERROR "
355 "message mid %llu was already processed\n",
356 (unsigned long long)msg_mid ));
357 continue;
360 DEBUG(10,("schedule_deferred_open_message_smb: "
361 "scheduling mid %llu\n",
362 (unsigned long long)mid ));
365 * smbd_deferred_open_timer() calls
366 * process_smb() to redispatch the request
367 * including the required impersonation.
369 * So we can just use the raw tevent_context.
371 te = tevent_add_timer(xconn->client->raw_ev_ctx,
372 pml,
373 timeval_zero(),
374 smbd_deferred_open_timer,
375 pml);
376 if (!te) {
377 DEBUG(10,("schedule_deferred_open_message_smb: "
378 "event_add_timed() failed, "
379 "skipping mid %llu\n",
380 (unsigned long long)msg_mid ));
383 TALLOC_FREE(pml->te);
384 pml->te = te;
385 DLIST_PROMOTE(sconn->deferred_open_queue, pml);
386 return true;
390 DEBUG(10,("schedule_deferred_open_message_smb: failed to "
391 "find message mid %llu\n",
392 (unsigned long long)mid ));
394 return false;
397 /****************************************************************************
398 Return true if this mid is on the deferred queue and was not yet processed.
399 ****************************************************************************/
401 bool open_was_deferred(struct smbXsrv_connection *xconn, uint64_t mid)
403 struct smbd_server_connection *sconn = xconn->client->sconn;
404 struct pending_message_list *pml;
406 if (sconn->using_smb2) {
407 return open_was_deferred_smb2(xconn, mid);
410 for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
411 if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid && !pml->processed) {
412 return True;
415 return False;
418 /****************************************************************************
419 Return the message queued by this mid.
420 ****************************************************************************/
422 static struct pending_message_list *get_deferred_open_message_smb(
423 struct smbd_server_connection *sconn, uint64_t mid)
425 struct pending_message_list *pml;
427 for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
428 if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid) {
429 return pml;
432 return NULL;
435 /****************************************************************************
436 Get the state data queued by this mid.
437 ****************************************************************************/
439 bool get_deferred_open_message_state(struct smb_request *smbreq,
440 struct timeval *p_request_time,
441 struct deferred_open_record **open_rec)
443 struct pending_message_list *pml;
445 if (smbreq->sconn->using_smb2) {
446 return get_deferred_open_message_state_smb2(smbreq->smb2req,
447 p_request_time,
448 open_rec);
451 pml = get_deferred_open_message_smb(smbreq->sconn, smbreq->mid);
452 if (!pml) {
453 return false;
455 if (p_request_time) {
456 *p_request_time = pml->request_time;
458 if (open_rec != NULL) {
459 *open_rec = pml->open_rec;
461 return true;
464 bool push_deferred_open_message_smb(struct smb_request *req,
465 struct timeval timeout,
466 struct file_id id,
467 struct deferred_open_record *open_rec)
469 #if defined(WITH_SMB1SERVER)
470 if (req->smb2req) {
471 #endif
472 return push_deferred_open_message_smb2(req->smb2req,
473 req->request_time,
474 timeout,
476 open_rec);
477 #if defined(WITH_SMB1SERVER)
478 } else {
479 return push_deferred_open_message_smb1(req, timeout,
480 id, open_rec);
482 #endif
485 static void construct_smb1_reply_common(uint8_t cmd, const uint8_t *inbuf,
486 char *outbuf)
488 uint16_t in_flags2 = SVAL(inbuf,smb_flg2);
489 uint16_t out_flags2 = common_flags2;
491 out_flags2 |= in_flags2 & FLAGS2_UNICODE_STRINGS;
492 out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES;
493 out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES_REQUIRED;
495 srv_smb1_set_message(outbuf,0,0,false);
497 SCVAL(outbuf, smb_com, cmd);
498 SIVAL(outbuf,smb_rcls,0);
499 SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES));
500 SSVAL(outbuf,smb_flg2, out_flags2);
501 memset(outbuf+smb_pidhigh,'\0',(smb_tid-smb_pidhigh));
502 memcpy(outbuf+smb_ss_field, inbuf+smb_ss_field, 8);
504 SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
505 SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
506 SSVAL(outbuf,smb_pidhigh,SVAL(inbuf,smb_pidhigh));
507 SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
508 SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
511 void construct_smb1_reply_common_req(struct smb_request *req, char *outbuf)
513 construct_smb1_reply_common(req->cmd, req->inbuf, outbuf);
516 /*******************************************************************
517 allocate and initialize a reply packet
518 ********************************************************************/
520 bool create_smb1_outbuf(TALLOC_CTX *mem_ctx, struct smb_request *req,
521 const uint8_t *inbuf, char **outbuf,
522 uint8_t num_words, uint32_t num_bytes)
524 size_t smb_len = MIN_SMB_SIZE + VWV(num_words) + num_bytes;
527 * Protect against integer wrap.
528 * The SMB layer reply can be up to 0xFFFFFF bytes.
530 if ((num_bytes > 0xffffff) || (smb_len > 0xffffff)) {
531 char *msg;
532 if (asprintf(&msg, "num_bytes too large: %u",
533 (unsigned)num_bytes) == -1) {
534 msg = discard_const_p(char, "num_bytes too large");
536 smb_panic(msg);
540 * Here we include the NBT header for now.
542 *outbuf = talloc_array(mem_ctx, char,
543 NBT_HDR_SIZE + smb_len);
544 if (*outbuf == NULL) {
545 return false;
548 construct_smb1_reply_common(req->cmd, inbuf, *outbuf);
549 srv_smb1_set_message(*outbuf, num_words, num_bytes, false);
551 * Zero out the word area, the caller has to take care of the bcc area
552 * himself
554 if (num_words != 0) {
555 memset(*outbuf + (NBT_HDR_SIZE + HDR_VWV), 0, VWV(num_words));
558 return true;
561 void reply_smb1_outbuf(struct smb_request *req, uint8_t num_words, uint32_t num_bytes)
563 char *outbuf;
564 if (!create_smb1_outbuf(req, req, req->inbuf, &outbuf, num_words,
565 num_bytes)) {
566 smb_panic("could not allocate output buffer\n");
568 req->outbuf = (uint8_t *)outbuf;
571 bool valid_smb1_header(const uint8_t *inbuf)
573 if (is_encrypted_packet(inbuf)) {
574 return true;
577 * This used to be (strncmp(smb_base(inbuf),"\377SMB",4) == 0)
578 * but it just looks weird to call strncmp for this one.
580 return (IVAL(smb_base(inbuf), 0) == 0x424D53FF);
583 /****************************************************************************
584 Process an smb from the client
585 ****************************************************************************/
587 static void process_smb2(struct smbXsrv_connection *xconn,
588 uint8_t *inbuf, size_t nread, size_t unread_bytes,
589 uint32_t seqnum, bool encrypted,
590 struct smb_perfcount_data *deferred_pcd)
592 const uint8_t *inpdu = inbuf + NBT_HDR_SIZE;
593 size_t pdulen = nread - NBT_HDR_SIZE;
594 NTSTATUS status = smbd_smb2_process_negprot(xconn, 0, inpdu, pdulen);
595 if (!NT_STATUS_IS_OK(status)) {
596 exit_server_cleanly("SMB2 negprot fail");
600 void process_smb(struct smbXsrv_connection *xconn,
601 uint8_t *inbuf, size_t nread, size_t unread_bytes,
602 uint32_t seqnum, bool encrypted,
603 struct smb_perfcount_data *deferred_pcd)
605 struct smbd_server_connection *sconn = xconn->client->sconn;
606 int msg_type = CVAL(inbuf,0);
608 DO_PROFILE_INC(request);
610 DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type,
611 smb_len(inbuf) ) );
612 DEBUG(3, ("Transaction %d of length %d (%u toread)\n",
613 sconn->trans_num, (int)nread, (unsigned int)unread_bytes));
615 if (msg_type != NBSSmessage) {
617 * NetBIOS session request, keepalive, etc.
619 reply_special(xconn, (char *)inbuf, nread);
620 goto done;
623 #if defined(WITH_SMB1SERVER)
624 if (sconn->using_smb2) {
625 /* At this point we're not really using smb2,
626 * we make the decision here.. */
627 if (smbd_is_smb2_header(inbuf, nread)) {
628 #endif
629 process_smb2(xconn, inbuf, nread, unread_bytes, seqnum,
630 encrypted, deferred_pcd);
631 return;
632 #if defined(WITH_SMB1SERVER)
634 if (nread >= smb_size && valid_smb1_header(inbuf)
635 && CVAL(inbuf, smb_com) != 0x72) {
636 /* This is a non-negprot SMB1 packet.
637 Disable SMB2 from now on. */
638 sconn->using_smb2 = false;
641 process_smb1(xconn, inbuf, nread, unread_bytes, seqnum, encrypted,
642 deferred_pcd);
643 #endif
645 done:
646 sconn->num_requests++;
648 /* The timeout_processing function isn't run nearly
649 often enough to implement 'max log size' without
650 overrunning the size of the file by many megabytes.
651 This is especially true if we are running at debug
652 level 10. Checking every 50 SMBs is a nice
653 tradeoff of performance vs log file size overrun. */
655 if ((sconn->num_requests % 50) == 0 &&
656 need_to_check_log_size()) {
657 change_to_root_user();
658 check_log_size();
662 NTSTATUS smbXsrv_connection_init_tables(struct smbXsrv_connection *conn,
663 enum protocol_types protocol)
665 NTSTATUS status;
667 conn->protocol = protocol;
669 if (conn->client->session_table != NULL) {
670 return NT_STATUS_OK;
673 if (protocol >= PROTOCOL_SMB2_02) {
674 status = smb2srv_session_table_init(conn);
675 if (!NT_STATUS_IS_OK(status)) {
676 conn->protocol = PROTOCOL_NONE;
677 return status;
680 status = smb2srv_open_table_init(conn);
681 if (!NT_STATUS_IS_OK(status)) {
682 conn->protocol = PROTOCOL_NONE;
683 return status;
685 } else {
686 #if defined(WITH_SMB1SERVER)
687 status = smb1srv_session_table_init(conn);
688 if (!NT_STATUS_IS_OK(status)) {
689 conn->protocol = PROTOCOL_NONE;
690 return status;
693 status = smb1srv_tcon_table_init(conn);
694 if (!NT_STATUS_IS_OK(status)) {
695 conn->protocol = PROTOCOL_NONE;
696 return status;
699 status = smb1srv_open_table_init(conn);
700 if (!NT_STATUS_IS_OK(status)) {
701 conn->protocol = PROTOCOL_NONE;
702 return status;
704 #else
705 conn->protocol = PROTOCOL_NONE;
706 return NT_STATUS_INVALID_NETWORK_RESPONSE;
707 #endif
710 set_Protocol(protocol);
711 return NT_STATUS_OK;
715 * Create a debug string for the connection
717 * This is allocated to talloc_tos() or a string constant
718 * in certain corner cases. The returned string should
719 * hence not be free'd directly but only via the talloc stack.
721 const char *smbXsrv_connection_dbg(const struct smbXsrv_connection *xconn)
723 const char *ret;
724 char *addr;
726 * TODO: this can be improved later
727 * maybe including the client guid or more
729 addr = tsocket_address_string(xconn->remote_address, talloc_tos());
730 if (addr == NULL) {
731 return "<tsocket_address_string() failed>";
734 ret = talloc_asprintf(talloc_tos(), "ptr=%p,id=%llu,addr=%s",
735 xconn, (unsigned long long)xconn->channel_id, addr);
736 TALLOC_FREE(addr);
737 if (ret == NULL) {
738 return "<talloc_asprintf() failed>";
741 return ret;
745 * Initialize a struct smb_request from an inbuf
748 bool init_smb1_request(struct smb_request *req,
749 struct smbd_server_connection *sconn,
750 struct smbXsrv_connection *xconn,
751 const uint8_t *inbuf,
752 size_t unread_bytes, bool encrypted,
753 uint32_t seqnum)
755 struct smbXsrv_tcon *tcon;
756 NTSTATUS status;
757 NTTIME now;
758 size_t req_size = smb_len(inbuf) + 4;
760 /* Ensure we have at least smb_size bytes. */
761 if (req_size < smb_size) {
762 DEBUG(0,("init_smb1_request: invalid request size %u\n",
763 (unsigned int)req_size ));
764 return false;
767 req->request_time = timeval_current();
768 now = timeval_to_nttime(&req->request_time);
770 req->cmd = CVAL(inbuf, smb_com);
771 req->flags2 = SVAL(inbuf, smb_flg2);
772 req->smbpid = SVAL(inbuf, smb_pid);
773 req->mid = (uint64_t)SVAL(inbuf, smb_mid);
774 req->seqnum = seqnum;
775 req->vuid = SVAL(inbuf, smb_uid);
776 req->tid = SVAL(inbuf, smb_tid);
777 req->wct = CVAL(inbuf, smb_wct);
778 req->vwv = (const uint16_t *)(inbuf+smb_vwv);
779 req->buflen = smb_buflen(inbuf);
780 req->buf = (const uint8_t *)smb_buf_const(inbuf);
781 req->unread_bytes = unread_bytes;
782 req->encrypted = encrypted;
783 req->sconn = sconn;
784 req->xconn = xconn;
785 req->conn = NULL;
786 if (xconn != NULL) {
787 status = smb1srv_tcon_lookup(xconn, req->tid, now, &tcon);
788 if (NT_STATUS_IS_OK(status)) {
789 req->conn = tcon->compat;
792 req->chain_fsp = NULL;
793 req->smb2req = NULL;
794 req->chain = NULL;
795 req->posix_pathnames = lp_posix_pathnames();
796 smb_init_perfcount_data(&req->pcd);
798 /* Ensure we have at least wct words and 2 bytes of bcc. */
799 if (smb_size + req->wct*2 > req_size) {
800 DEBUG(0,("init_smb1_request: invalid wct number %u (size %u)\n",
801 (unsigned int)req->wct,
802 (unsigned int)req_size));
803 return false;
805 /* Ensure bcc is correct. */
806 if (((const uint8_t *)smb_buf_const(inbuf)) + req->buflen > inbuf + req_size) {
807 DEBUG(0,("init_smb1_request: invalid bcc number %u "
808 "(wct = %u, size %u)\n",
809 (unsigned int)req->buflen,
810 (unsigned int)req->wct,
811 (unsigned int)req_size));
812 return false;
815 req->outbuf = NULL;
816 return true;
819 /****************************************************************************
820 Construct a reply to the incoming packet.
821 ****************************************************************************/
823 static void construct_reply_smb1negprot(struct smbXsrv_connection *xconn,
824 char *inbuf, int size,
825 size_t unread_bytes)
827 struct smbd_server_connection *sconn = xconn->client->sconn;
828 struct smb_request *req;
829 NTSTATUS status;
831 if (!(req = talloc(talloc_tos(), struct smb_request))) {
832 smb_panic("could not allocate smb_request");
835 if (!init_smb1_request(req, sconn, xconn, (uint8_t *)inbuf, unread_bytes,
836 false, 0)) {
837 exit_server_cleanly("Invalid SMB request");
840 req->inbuf = (uint8_t *)talloc_move(req, &inbuf);
842 status = smb2_multi_protocol_reply_negprot(req);
843 if (req->outbuf == NULL) {
845 * req->outbuf == NULL means we bootstrapped into SMB2.
847 return;
849 if (!NT_STATUS_IS_OK(status)) {
850 if (!smb1_srv_send(req->xconn,
851 (char *)req->outbuf,
852 true, req->seqnum+1,
853 IS_CONN_ENCRYPTED(req->conn)||req->encrypted,
854 &req->pcd)) {
855 exit_server_cleanly("construct_reply_smb1negprot: "
856 "smb1_srv_send failed.");
858 TALLOC_FREE(req);
859 } else {
860 /* This code path should only *ever* bootstrap into SMB2. */
861 exit_server_cleanly("Internal error SMB1negprot didn't reply "
862 "with an SMB2 packet");
866 static void smbd_server_connection_write_handler(
867 struct smbXsrv_connection *xconn)
869 /* TODO: make write nonblocking */
872 static void smbd_smb2_server_connection_read_handler(
873 struct smbXsrv_connection *xconn, int fd)
875 char lenbuf[NBT_HDR_SIZE];
876 size_t len = 0;
877 uint8_t *buffer = NULL;
878 size_t bufferlen = 0;
879 NTSTATUS status;
880 uint8_t msg_type = 0;
882 /* Read the first 4 bytes - contains length of remainder. */
883 status = read_smb_length_return_keepalive(fd, lenbuf, 0, &len);
884 if (!NT_STATUS_IS_OK(status)) {
885 exit_server_cleanly("failed to receive request length");
886 return;
889 /* Integer wrap check. */
890 if (len + NBT_HDR_SIZE < len) {
891 exit_server_cleanly("Invalid length on initial request");
892 return;
896 * The +4 here can't wrap, we've checked the length above already.
898 bufferlen = len+NBT_HDR_SIZE;
900 buffer = talloc_array(talloc_tos(), uint8_t, bufferlen);
901 if (buffer == NULL) {
902 DBG_ERR("Could not allocate request inbuf of length %zu\n",
903 bufferlen);
904 exit_server_cleanly("talloc fail");
905 return;
908 /* Copy the NBT_HDR_SIZE length. */
909 memcpy(buffer, lenbuf, sizeof(lenbuf));
911 status = read_packet_remainder(fd, (char *)buffer+NBT_HDR_SIZE, 0, len);
912 if (!NT_STATUS_IS_OK(status)) {
913 exit_server_cleanly("Failed to read remainder of initial request");
914 return;
917 /* Check the message type. */
918 msg_type = PULL_LE_U8(buffer,0);
919 if (msg_type == NBSSrequest) {
921 * clients can send this request before
922 * bootstrapping into SMB2. Cope with this
923 * message only, don't allow any other strange
924 * NBSS types.
926 reply_special(xconn, (char *)buffer, bufferlen);
927 xconn->client->sconn->num_requests++;
928 return;
931 /* Only a 'normal' message type allowed now. */
932 if (msg_type != NBSSmessage) {
933 DBG_ERR("Invalid message type %d\n", msg_type);
934 exit_server_cleanly("Invalid message type for initial request");
935 return;
938 /* Could this be an SMB1 negprot bootstrap into SMB2 ? */
939 if (bufferlen < smb_size) {
940 exit_server_cleanly("Invalid initial SMB1 or SMB2 packet");
941 return;
943 if (valid_smb1_header(buffer)) {
944 /* Can *only* allow an SMB1 negprot here. */
945 uint8_t cmd = PULL_LE_U8(buffer, smb_com);
946 if (cmd != SMBnegprot) {
947 DBG_ERR("Incorrect SMB1 command 0x%hhx, "
948 "should be SMBnegprot (0x72)\n",
949 cmd);
950 exit_server_cleanly("Invalid initial SMB1 packet");
952 /* Minimal process_smb(). */
953 show_msg((char *)buffer);
954 construct_reply_smb1negprot(xconn, (char *)buffer,
955 bufferlen, 0);
956 xconn->client->sconn->trans_num++;
957 xconn->client->sconn->num_requests++;
958 return;
960 } else if (!smbd_is_smb2_header(buffer, bufferlen)) {
961 exit_server_cleanly("Invalid initial SMB2 packet");
962 return;
965 /* Here we know we're a valid SMB2 packet. */
968 * Point at the start of the SMB2 PDU.
969 * len is the length of the SMB2 PDU.
972 status = smbd_smb2_process_negprot(xconn,
974 (const uint8_t *)buffer+NBT_HDR_SIZE,
975 len);
976 if (!NT_STATUS_IS_OK(status)) {
977 exit_server_cleanly("SMB2 negprot fail");
979 return;
982 static void smbd_server_connection_handler(struct tevent_context *ev,
983 struct tevent_fd *fde,
984 uint16_t flags,
985 void *private_data)
987 struct smbXsrv_connection *xconn =
988 talloc_get_type_abort(private_data,
989 struct smbXsrv_connection);
991 if (!NT_STATUS_IS_OK(xconn->transport.status)) {
993 * we're not supposed to do any io
995 TEVENT_FD_NOT_READABLE(xconn->transport.fde);
996 TEVENT_FD_NOT_WRITEABLE(xconn->transport.fde);
997 return;
1000 if (flags & TEVENT_FD_WRITE) {
1001 smbd_server_connection_write_handler(xconn);
1002 return;
1004 if (flags & TEVENT_FD_READ) {
1005 #if defined(WITH_SMB1SERVER)
1006 if (lp_server_min_protocol() > PROTOCOL_NT1) {
1007 #endif
1008 smbd_smb2_server_connection_read_handler(xconn,
1009 xconn->transport.sock);
1010 #if defined(WITH_SMB1SERVER)
1011 } else {
1012 smbd_smb1_server_connection_read_handler(xconn,
1013 xconn->transport.sock);
1015 #endif
1016 return;
1020 struct smbd_release_ip_state {
1021 struct smbXsrv_connection *xconn;
1022 struct tevent_immediate *im;
1023 char addr[INET6_ADDRSTRLEN];
1026 static void smbd_release_ip_immediate(struct tevent_context *ctx,
1027 struct tevent_immediate *im,
1028 void *private_data)
1030 struct smbd_release_ip_state *state =
1031 talloc_get_type_abort(private_data,
1032 struct smbd_release_ip_state);
1033 struct smbXsrv_connection *xconn = state->xconn;
1035 if (!NT_STATUS_EQUAL(xconn->transport.status, NT_STATUS_ADDRESS_CLOSED)) {
1037 * smbd_server_connection_terminate() already triggered ?
1039 return;
1042 smbd_server_connection_terminate(xconn, "CTDB_SRVID_RELEASE_IP");
1045 /****************************************************************************
1046 received when we should release a specific IP
1047 ****************************************************************************/
1048 static int release_ip(struct tevent_context *ev,
1049 uint32_t src_vnn, uint32_t dst_vnn,
1050 uint64_t dst_srvid,
1051 const uint8_t *msg, size_t msglen,
1052 void *private_data)
1054 struct smbd_release_ip_state *state =
1055 talloc_get_type_abort(private_data,
1056 struct smbd_release_ip_state);
1057 struct smbXsrv_connection *xconn = state->xconn;
1058 const char *ip;
1059 const char *addr = state->addr;
1060 const char *p = addr;
1062 if (msglen == 0) {
1063 return 0;
1065 if (msg[msglen-1] != '\0') {
1066 return 0;
1069 ip = (const char *)msg;
1071 if (!NT_STATUS_IS_OK(xconn->transport.status)) {
1072 /* avoid recursion */
1073 return 0;
1076 if (strncmp("::ffff:", addr, 7) == 0) {
1077 p = addr + 7;
1080 DEBUG(10, ("Got release IP message for %s, "
1081 "our address is %s\n", ip, p));
1083 if ((strcmp(p, ip) == 0) || ((p != addr) && strcmp(addr, ip) == 0)) {
1084 DEBUG(0,("Got release IP message for our IP %s - exiting immediately\n",
1085 ip));
1087 * With SMB2 we should do a clean disconnect,
1088 * the previous_session_id in the session setup
1089 * will cleanup the old session, tcons and opens.
1091 * A clean disconnect is needed in order to support
1092 * durable handles.
1094 * Note: typically this is never triggered
1095 * as we got a TCP RST (triggered by ctdb event scripts)
1096 * before we get CTDB_SRVID_RELEASE_IP.
1098 * We used to call _exit(1) here, but as this was mostly never
1099 * triggered and has implication on our process model,
1100 * we can just use smbd_server_connection_terminate()
1101 * (also for SMB1).
1103 * We don't call smbd_server_connection_terminate() directly
1104 * as we might be called from within ctdbd_migrate(),
1105 * we need to defer our action to the next event loop
1107 tevent_schedule_immediate(state->im,
1108 xconn->client->raw_ev_ctx,
1109 smbd_release_ip_immediate,
1110 state);
1113 * Make sure we don't get any io on the connection.
1115 xconn->transport.status = NT_STATUS_ADDRESS_CLOSED;
1116 return EADDRNOTAVAIL;
1119 return 0;
1122 static int match_cluster_movable_ip(uint32_t total_ip_count,
1123 const struct sockaddr_storage *ip,
1124 bool is_movable_ip,
1125 void *private_data)
1127 const struct sockaddr_storage *srv = private_data;
1128 struct samba_sockaddr pub_ip = {
1129 .u = {
1130 .ss = *ip,
1133 struct samba_sockaddr srv_ip = {
1134 .u = {
1135 .ss = *srv,
1139 if (is_movable_ip && sockaddr_equal(&pub_ip.u.sa, &srv_ip.u.sa)) {
1140 return EADDRNOTAVAIL;
1143 return 0;
1146 static NTSTATUS smbd_register_ips(struct smbXsrv_connection *xconn,
1147 struct sockaddr_storage *srv,
1148 struct sockaddr_storage *clnt)
1150 struct smbd_release_ip_state *state;
1151 struct ctdbd_connection *cconn;
1152 int ret;
1154 cconn = messaging_ctdb_connection();
1155 if (cconn == NULL) {
1156 return NT_STATUS_NO_MEMORY;
1159 state = talloc_zero(xconn, struct smbd_release_ip_state);
1160 if (state == NULL) {
1161 return NT_STATUS_NO_MEMORY;
1163 state->xconn = xconn;
1164 state->im = tevent_create_immediate(state);
1165 if (state->im == NULL) {
1166 return NT_STATUS_NO_MEMORY;
1168 if (print_sockaddr(state->addr, sizeof(state->addr), srv) == NULL) {
1169 return NT_STATUS_NO_MEMORY;
1172 if (xconn->client->server_multi_channel_enabled) {
1173 ret = ctdbd_public_ip_foreach(cconn,
1174 match_cluster_movable_ip,
1175 srv);
1176 if (ret == EADDRNOTAVAIL) {
1177 xconn->has_cluster_movable_ip = true;
1178 DBG_DEBUG("cluster movable IP on %s\n",
1179 smbXsrv_connection_dbg(xconn));
1180 } else if (ret != 0) {
1181 DBG_ERR("failed to iterate cluster IPs: %s\n",
1182 strerror(ret));
1183 return NT_STATUS_INTERNAL_ERROR;
1187 ret = ctdbd_register_ips(cconn, srv, clnt, release_ip, state);
1188 if (ret != 0) {
1189 return map_nt_error_from_unix(ret);
1191 return NT_STATUS_OK;
1194 static int smbXsrv_connection_destructor(struct smbXsrv_connection *xconn)
1196 DBG_DEBUG("xconn[%s]\n", smbXsrv_connection_dbg(xconn));
1197 return 0;
1200 NTSTATUS smbd_add_connection(struct smbXsrv_client *client, int sock_fd,
1201 NTTIME now, struct smbXsrv_connection **_xconn)
1203 TALLOC_CTX *frame = talloc_stackframe();
1204 struct smbXsrv_connection *xconn;
1205 struct sockaddr_storage ss_srv;
1206 void *sp_srv = (void *)&ss_srv;
1207 struct sockaddr *sa_srv = (struct sockaddr *)sp_srv;
1208 struct sockaddr_storage ss_clnt;
1209 void *sp_clnt = (void *)&ss_clnt;
1210 struct sockaddr *sa_clnt = (struct sockaddr *)sp_clnt;
1211 socklen_t sa_socklen;
1212 struct tsocket_address *local_address = NULL;
1213 struct tsocket_address *remote_address = NULL;
1214 const char *remaddr = NULL;
1215 char *p;
1216 const char *rhost = NULL;
1217 int ret;
1218 int tmp;
1220 *_xconn = NULL;
1222 DO_PROFILE_INC(connect);
1224 xconn = talloc_zero(client, struct smbXsrv_connection);
1225 if (xconn == NULL) {
1226 DEBUG(0,("talloc_zero(struct smbXsrv_connection)\n"));
1227 TALLOC_FREE(frame);
1228 return NT_STATUS_NO_MEMORY;
1230 talloc_set_destructor(xconn, smbXsrv_connection_destructor);
1231 talloc_steal(frame, xconn);
1232 xconn->client = client;
1233 xconn->connect_time = now;
1234 if (client->next_channel_id != 0) {
1235 xconn->channel_id = client->next_channel_id++;
1238 xconn->transport.sock = sock_fd;
1239 #if defined(WITH_SMB1SERVER)
1240 smbd_echo_init(xconn);
1241 #endif
1242 xconn->protocol = PROTOCOL_NONE;
1244 /* Ensure child is set to blocking mode */
1245 set_blocking(sock_fd,True);
1247 set_socket_options(sock_fd, "SO_KEEPALIVE");
1248 set_socket_options(sock_fd, lp_socket_options());
1250 sa_socklen = sizeof(ss_clnt);
1251 ret = getpeername(sock_fd, sa_clnt, &sa_socklen);
1252 if (ret != 0) {
1253 int saved_errno = errno;
1254 int level = (errno == ENOTCONN)?2:0;
1255 DEBUG(level,("getpeername() failed - %s\n",
1256 strerror(saved_errno)));
1257 TALLOC_FREE(frame);
1258 return map_nt_error_from_unix_common(saved_errno);
1260 ret = tsocket_address_bsd_from_sockaddr(xconn,
1261 sa_clnt, sa_socklen,
1262 &remote_address);
1263 if (ret != 0) {
1264 int saved_errno = errno;
1265 DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
1266 __location__, strerror(saved_errno)));
1267 TALLOC_FREE(frame);
1268 return map_nt_error_from_unix_common(saved_errno);
1271 sa_socklen = sizeof(ss_srv);
1272 ret = getsockname(sock_fd, sa_srv, &sa_socklen);
1273 if (ret != 0) {
1274 int saved_errno = errno;
1275 int level = (errno == ENOTCONN)?2:0;
1276 DEBUG(level,("getsockname() failed - %s\n",
1277 strerror(saved_errno)));
1278 TALLOC_FREE(frame);
1279 return map_nt_error_from_unix_common(saved_errno);
1281 ret = tsocket_address_bsd_from_sockaddr(xconn,
1282 sa_srv, sa_socklen,
1283 &local_address);
1284 if (ret != 0) {
1285 int saved_errno = errno;
1286 DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
1287 __location__, strerror(saved_errno)));
1288 TALLOC_FREE(frame);
1289 return map_nt_error_from_unix_common(saved_errno);
1292 if (tsocket_address_is_inet(remote_address, "ip")) {
1293 remaddr = tsocket_address_inet_addr_string(remote_address,
1294 talloc_tos());
1295 if (remaddr == NULL) {
1296 DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
1297 __location__, strerror(errno)));
1298 TALLOC_FREE(frame);
1299 return NT_STATUS_NO_MEMORY;
1301 } else {
1302 remaddr = "0.0.0.0";
1306 * Before the first packet, check the global hosts allow/ hosts deny
1307 * parameters before doing any parsing of packets passed to us by the
1308 * client. This prevents attacks on our parsing code from hosts not in
1309 * the hosts allow list.
1312 ret = get_remote_hostname(remote_address,
1313 &p, talloc_tos());
1314 if (ret < 0) {
1315 int saved_errno = errno;
1316 DEBUG(0,("%s: get_remote_hostname failed - %s\n",
1317 __location__, strerror(saved_errno)));
1318 TALLOC_FREE(frame);
1319 return map_nt_error_from_unix_common(saved_errno);
1321 rhost = p;
1322 if (strequal(rhost, "UNKNOWN")) {
1323 rhost = remaddr;
1326 xconn->local_address = local_address;
1327 xconn->remote_address = remote_address;
1328 xconn->remote_hostname = talloc_strdup(xconn, rhost);
1329 if (xconn->remote_hostname == NULL) {
1330 return NT_STATUS_NO_MEMORY;
1333 if (!srv_init_signing(xconn)) {
1334 DEBUG(0, ("Failed to init smb_signing\n"));
1335 TALLOC_FREE(frame);
1336 return NT_STATUS_INTERNAL_ERROR;
1339 if (!allow_access(lp_hosts_deny(-1), lp_hosts_allow(-1),
1340 xconn->remote_hostname,
1341 remaddr)) {
1342 DEBUG( 1, ("Connection denied from %s to %s\n",
1343 tsocket_address_string(remote_address, talloc_tos()),
1344 tsocket_address_string(local_address, talloc_tos())));
1347 * We return a valid xconn
1348 * so that the caller can return an error message
1349 * to the client
1351 DLIST_ADD_END(client->connections, xconn);
1352 talloc_steal(client, xconn);
1354 *_xconn = xconn;
1355 TALLOC_FREE(frame);
1356 return NT_STATUS_NETWORK_ACCESS_DENIED;
1359 DEBUG(10, ("Connection allowed from %s to %s\n",
1360 tsocket_address_string(remote_address, talloc_tos()),
1361 tsocket_address_string(local_address, talloc_tos())));
1363 if (lp_clustering()) {
1365 * We need to tell ctdb about our client's TCP
1366 * connection, so that for failover ctdbd can send
1367 * tickle acks, triggering a reconnection by the
1368 * client.
1370 NTSTATUS status;
1372 status = smbd_register_ips(xconn, &ss_srv, &ss_clnt);
1373 if (!NT_STATUS_IS_OK(status)) {
1374 DEBUG(0, ("ctdbd_register_ips failed: %s\n",
1375 nt_errstr(status)));
1379 tmp = lp_max_xmit();
1380 tmp = MAX(tmp, SMB_BUFFER_SIZE_MIN);
1381 tmp = MIN(tmp, SMB_BUFFER_SIZE_MAX);
1383 #if defined(WITH_SMB1SERVER)
1384 xconn->smb1.negprot.max_recv = tmp;
1386 xconn->smb1.sessions.done_sesssetup = false;
1387 xconn->smb1.sessions.max_send = SMB_BUFFER_SIZE_MAX;
1388 #endif
1390 xconn->transport.fde = tevent_add_fd(client->raw_ev_ctx,
1391 xconn,
1392 sock_fd,
1393 TEVENT_FD_READ,
1394 smbd_server_connection_handler,
1395 xconn);
1396 if (!xconn->transport.fde) {
1397 TALLOC_FREE(frame);
1398 return NT_STATUS_NO_MEMORY;
1400 tevent_fd_set_auto_close(xconn->transport.fde);
1402 /* for now we only have one connection */
1403 DLIST_ADD_END(client->connections, xconn);
1404 talloc_steal(client, xconn);
1406 *_xconn = xconn;
1407 TALLOC_FREE(frame);
1408 return NT_STATUS_OK;
1411 static bool uid_in_use(struct auth_session_info *session_info,
1412 uid_t uid)
1414 if (session_info->unix_token->uid == uid) {
1415 return true;
1417 return false;
1420 static bool gid_in_use(struct auth_session_info *session_info,
1421 gid_t gid)
1423 uint32_t i;
1424 struct security_unix_token *utok = NULL;
1426 utok = session_info->unix_token;
1427 if (utok->gid == gid) {
1428 return true;
1431 for(i = 0; i < utok->ngroups; i++) {
1432 if (utok->groups[i] == gid) {
1433 return true;
1436 return false;
1439 static bool sid_in_use(struct auth_session_info *session_info,
1440 const struct dom_sid *psid)
1442 struct security_token *tok = NULL;
1444 tok = session_info->security_token;
1445 if (tok == NULL) {
1447 * Not sure session_info->security_token can
1448 * ever be NULL. This check might be not
1449 * necessary.
1451 return false;
1453 if (security_token_has_sid(tok, psid)) {
1454 return true;
1456 return false;
1459 struct id_in_use_state {
1460 const struct id_cache_ref *id;
1461 bool match;
1464 static int id_in_use_cb(struct smbXsrv_session *session,
1465 void *private_data)
1467 struct id_in_use_state *state = (struct id_in_use_state *)
1468 private_data;
1469 struct auth_session_info *session_info =
1470 session->global->auth_session_info;
1472 switch(state->id->type) {
1473 case UID:
1474 state->match = uid_in_use(session_info, state->id->id.uid);
1475 break;
1476 case GID:
1477 state->match = gid_in_use(session_info, state->id->id.gid);
1478 break;
1479 case SID:
1480 state->match = sid_in_use(session_info, &state->id->id.sid);
1481 break;
1482 default:
1483 state->match = false;
1484 break;
1486 if (state->match) {
1487 return -1;
1489 return 0;
1492 static bool id_in_use(struct smbd_server_connection *sconn,
1493 const struct id_cache_ref *id)
1495 struct id_in_use_state state;
1496 NTSTATUS status;
1498 state = (struct id_in_use_state) {
1499 .id = id,
1500 .match = false,
1503 status = smbXsrv_session_local_traverse(sconn->client,
1504 id_in_use_cb,
1505 &state);
1506 if (!NT_STATUS_IS_OK(status)) {
1507 return false;
1510 return state.match;
1513 /****************************************************************************
1514 Check if services need reloading.
1515 ****************************************************************************/
1517 static void check_reload(struct smbd_server_connection *sconn, time_t t)
1520 if (last_smb_conf_reload_time == 0) {
1521 last_smb_conf_reload_time = t;
1524 if (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK) {
1525 reload_services(sconn, conn_snum_used, true);
1526 last_smb_conf_reload_time = t;
1530 static void msg_kill_client_ip(struct messaging_context *msg_ctx,
1531 void *private_data, uint32_t msg_type,
1532 struct server_id server_id, DATA_BLOB *data)
1534 struct smbd_server_connection *sconn = talloc_get_type_abort(
1535 private_data, struct smbd_server_connection);
1536 const char *ip = (char *) data->data;
1537 char *client_ip;
1539 DBG_DEBUG("Got kill request for client IP %s\n", ip);
1541 client_ip = tsocket_address_inet_addr_string(sconn->remote_address,
1542 talloc_tos());
1543 if (client_ip == NULL) {
1544 return;
1547 if (strequal(ip, client_ip)) {
1548 DBG_WARNING("Got kill client message for %s - "
1549 "exiting immediately\n", ip);
1550 exit_server_cleanly("Forced disconnect for client");
1553 TALLOC_FREE(client_ip);
1557 * Do the recurring check if we're idle
1559 static bool deadtime_fn(const struct timeval *now, void *private_data)
1561 struct smbd_server_connection *sconn =
1562 (struct smbd_server_connection *)private_data;
1564 if ((conn_num_open(sconn) == 0)
1565 || (conn_idle_all(sconn, now->tv_sec))) {
1566 DEBUG( 2, ( "Closing idle connection\n" ) );
1567 messaging_send(sconn->msg_ctx,
1568 messaging_server_id(sconn->msg_ctx),
1569 MSG_SHUTDOWN, &data_blob_null);
1570 return False;
1573 return True;
1577 * Do the recurring log file and smb.conf reload checks.
1580 static bool housekeeping_fn(const struct timeval *now, void *private_data)
1582 struct smbd_server_connection *sconn = talloc_get_type_abort(
1583 private_data, struct smbd_server_connection);
1585 DEBUG(5, ("housekeeping\n"));
1587 change_to_root_user();
1589 /* check if we need to reload services */
1590 check_reload(sconn, time_mono(NULL));
1593 * Force a log file check.
1595 force_check_log_size();
1596 check_log_size();
1597 return true;
1600 static void smbd_sig_term_handler(struct tevent_context *ev,
1601 struct tevent_signal *se,
1602 int signum,
1603 int count,
1604 void *siginfo,
1605 void *private_data)
1607 exit_server_cleanly("termination signal");
1610 static void smbd_setup_sig_term_handler(struct smbd_server_connection *sconn)
1612 struct tevent_signal *se;
1614 se = tevent_add_signal(sconn->ev_ctx,
1615 sconn,
1616 SIGTERM, 0,
1617 smbd_sig_term_handler,
1618 sconn);
1619 if (!se) {
1620 exit_server("failed to setup SIGTERM handler");
1624 static void smbd_sig_hup_handler(struct tevent_context *ev,
1625 struct tevent_signal *se,
1626 int signum,
1627 int count,
1628 void *siginfo,
1629 void *private_data)
1631 struct smbd_server_connection *sconn =
1632 talloc_get_type_abort(private_data,
1633 struct smbd_server_connection);
1635 change_to_root_user();
1636 DEBUG(1,("Reloading services after SIGHUP\n"));
1637 reload_services(sconn, conn_snum_used, false);
1640 static void smbd_setup_sig_hup_handler(struct smbd_server_connection *sconn)
1642 struct tevent_signal *se;
1644 se = tevent_add_signal(sconn->ev_ctx,
1645 sconn,
1646 SIGHUP, 0,
1647 smbd_sig_hup_handler,
1648 sconn);
1649 if (!se) {
1650 exit_server("failed to setup SIGHUP handler");
1654 static void smbd_conf_updated(struct messaging_context *msg,
1655 void *private_data,
1656 uint32_t msg_type,
1657 struct server_id server_id,
1658 DATA_BLOB *data)
1660 struct smbd_server_connection *sconn =
1661 talloc_get_type_abort(private_data,
1662 struct smbd_server_connection);
1664 DEBUG(10,("smbd_conf_updated: Got message saying smb.conf was "
1665 "updated. Reloading.\n"));
1666 change_to_root_user();
1667 reload_services(sconn, conn_snum_used, false);
1670 static void smbd_id_cache_kill(struct messaging_context *msg_ctx,
1671 void *private_data,
1672 uint32_t msg_type,
1673 struct server_id server_id,
1674 DATA_BLOB* data)
1676 const char *msg = (data && data->data)
1677 ? (const char *)data->data : "<NULL>";
1678 struct id_cache_ref id;
1679 struct smbd_server_connection *sconn =
1680 talloc_get_type_abort(private_data,
1681 struct smbd_server_connection);
1683 if (!id_cache_ref_parse(msg, &id)) {
1684 DEBUG(0, ("Invalid ?ID: %s\n", msg));
1685 return;
1688 if (id_in_use(sconn, &id)) {
1689 exit_server_cleanly(msg);
1691 id_cache_delete_from_cache(&id);
1694 struct smbd_tevent_trace_state {
1695 struct tevent_context *ev;
1696 TALLOC_CTX *frame;
1697 SMBPROFILE_BASIC_ASYNC_STATE(profile_idle);
1700 static void smbd_tevent_trace_callback(enum tevent_trace_point point,
1701 void *private_data)
1703 struct smbd_tevent_trace_state *state =
1704 (struct smbd_tevent_trace_state *)private_data;
1706 switch (point) {
1707 case TEVENT_TRACE_BEFORE_WAIT:
1708 if (!smbprofile_dump_pending()) {
1710 * If there's no dump pending
1711 * we don't want to schedule a new 1 sec timer.
1713 * Instead we want to sleep as long as nothing happens.
1715 smbprofile_dump_setup(NULL);
1717 SMBPROFILE_BASIC_ASYNC_START(idle, profile_p, state->profile_idle);
1718 break;
1719 case TEVENT_TRACE_AFTER_WAIT:
1720 SMBPROFILE_BASIC_ASYNC_END(state->profile_idle);
1721 if (!smbprofile_dump_pending()) {
1723 * We need to flush our state after sleeping
1724 * (hopefully a long time).
1726 smbprofile_dump();
1728 * future profiling events should trigger timers
1729 * on our main event context.
1731 smbprofile_dump_setup(state->ev);
1733 break;
1734 case TEVENT_TRACE_BEFORE_LOOP_ONCE:
1735 TALLOC_FREE(state->frame);
1736 state->frame = talloc_stackframe_pool(8192);
1737 break;
1738 case TEVENT_TRACE_AFTER_LOOP_ONCE:
1739 TALLOC_FREE(state->frame);
1740 break;
1743 errno = 0;
1746 /****************************************************************************
1747 Process commands from the client
1748 ****************************************************************************/
1750 void smbd_process(struct tevent_context *ev_ctx,
1751 struct messaging_context *msg_ctx,
1752 int sock_fd,
1753 bool interactive)
1755 struct smbd_tevent_trace_state trace_state = {
1756 .ev = ev_ctx,
1757 .frame = talloc_stackframe(),
1759 const struct loadparm_substitution *lp_sub =
1760 loadparm_s3_global_substitution();
1761 struct smbXsrv_client *client = NULL;
1762 struct smbd_server_connection *sconn = NULL;
1763 struct smbXsrv_connection *xconn = NULL;
1764 const char *locaddr = NULL;
1765 const char *remaddr = NULL;
1766 int ret;
1767 NTSTATUS status;
1768 struct timeval tv = timeval_current();
1769 NTTIME now = timeval_to_nttime(&tv);
1770 char *chroot_dir = NULL;
1771 int rc;
1773 status = smbXsrv_client_create(ev_ctx, ev_ctx, msg_ctx, now, &client);
1774 if (!NT_STATUS_IS_OK(status)) {
1775 DBG_ERR("smbXsrv_client_create(): %s\n", nt_errstr(status));
1776 exit_server_cleanly("talloc_zero(struct smbXsrv_client).\n");
1780 * TODO: remove this...:-)
1782 global_smbXsrv_client = client;
1784 sconn = talloc_zero(client, struct smbd_server_connection);
1785 if (sconn == NULL) {
1786 exit_server("failed to create smbd_server_connection");
1789 client->sconn = sconn;
1790 sconn->client = client;
1792 sconn->ev_ctx = ev_ctx;
1793 sconn->msg_ctx = msg_ctx;
1795 ret = pthreadpool_tevent_init(sconn, lp_aio_max_threads(),
1796 &sconn->pool);
1797 if (ret != 0) {
1798 exit_server("pthreadpool_tevent_init() failed.");
1801 #if defined(WITH_SMB1SERVER)
1802 if (lp_server_max_protocol() >= PROTOCOL_SMB2_02) {
1803 #endif
1805 * We're not making the decision here,
1806 * we're just allowing the client
1807 * to decide between SMB1 and SMB2
1808 * with the first negprot
1809 * packet.
1811 sconn->using_smb2 = true;
1812 #if defined(WITH_SMB1SERVER)
1814 #endif
1816 if (!interactive) {
1817 smbd_setup_sig_term_handler(sconn);
1818 smbd_setup_sig_hup_handler(sconn);
1821 status = smbd_add_connection(client, sock_fd, now, &xconn);
1822 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
1824 * send a negative session response "not listening on calling
1825 * name"
1827 unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
1828 (void)smb1_srv_send(xconn,(char *)buf, false,
1829 0, false, NULL);
1830 exit_server_cleanly("connection denied");
1831 } else if (!NT_STATUS_IS_OK(status)) {
1832 exit_server_cleanly(nt_errstr(status));
1835 sconn->local_address =
1836 tsocket_address_copy(xconn->local_address, sconn);
1837 if (sconn->local_address == NULL) {
1838 exit_server_cleanly("tsocket_address_copy() failed");
1840 sconn->remote_address =
1841 tsocket_address_copy(xconn->remote_address, sconn);
1842 if (sconn->remote_address == NULL) {
1843 exit_server_cleanly("tsocket_address_copy() failed");
1845 sconn->remote_hostname =
1846 talloc_strdup(sconn, xconn->remote_hostname);
1847 if (sconn->remote_hostname == NULL) {
1848 exit_server_cleanly("tsocket_strdup() failed");
1851 client->global->local_address =
1852 tsocket_address_string(sconn->local_address,
1853 client->global);
1854 if (client->global->local_address == NULL) {
1855 exit_server_cleanly("tsocket_address_string() failed");
1857 client->global->remote_address =
1858 tsocket_address_string(sconn->remote_address,
1859 client->global);
1860 if (client->global->remote_address == NULL) {
1861 exit_server_cleanly("tsocket_address_string() failed");
1863 client->global->remote_name =
1864 talloc_strdup(client->global, sconn->remote_hostname);
1865 if (client->global->remote_name == NULL) {
1866 exit_server_cleanly("tsocket_strdup() failed");
1869 if (tsocket_address_is_inet(sconn->local_address, "ip")) {
1870 locaddr = tsocket_address_inet_addr_string(
1871 sconn->local_address,
1872 talloc_tos());
1873 if (locaddr == NULL) {
1874 DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
1875 __location__, strerror(errno)));
1876 exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
1878 } else {
1879 locaddr = "0.0.0.0";
1882 if (tsocket_address_is_inet(sconn->remote_address, "ip")) {
1883 remaddr = tsocket_address_inet_addr_string(
1884 sconn->remote_address,
1885 talloc_tos());
1886 if (remaddr == NULL) {
1887 DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
1888 __location__, strerror(errno)));
1889 exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
1891 } else {
1892 remaddr = "0.0.0.0";
1895 /* this is needed so that we get decent entries
1896 in smbstatus for port 445 connects */
1897 set_remote_machine_name(remaddr, false);
1898 reload_services(sconn, conn_snum_used, true);
1899 sub_set_socket_ids(remaddr,
1900 sconn->remote_hostname,
1901 locaddr);
1903 if (lp_preload_modules()) {
1904 smb_load_all_modules_absoute_path(lp_preload_modules());
1907 smb_perfcount_init();
1909 if (!init_account_policy()) {
1910 exit_server("Could not open account policy tdb.\n");
1913 chroot_dir = lp_root_directory(talloc_tos(), lp_sub);
1914 if (chroot_dir[0] != '\0') {
1915 rc = chdir(chroot_dir);
1916 if (rc != 0) {
1917 DBG_ERR("Failed to chdir to %s\n", chroot_dir);
1918 exit_server("Failed to chdir()");
1921 rc = chroot(chroot_dir);
1922 if (rc != 0) {
1923 DBG_ERR("Failed to change root to %s\n", chroot_dir);
1924 exit_server("Failed to chroot()");
1926 DBG_WARNING("Changed root to %s\n", chroot_dir);
1928 TALLOC_FREE(chroot_dir);
1931 if (!file_init(sconn)) {
1932 exit_server("file_init() failed");
1935 /* Setup oplocks */
1936 if (!init_oplocks(sconn))
1937 exit_server("Failed to init oplocks");
1939 /* register our message handlers */
1940 messaging_register(sconn->msg_ctx, sconn,
1941 MSG_SMB_FORCE_TDIS, msg_force_tdis);
1942 messaging_register(
1943 sconn->msg_ctx,
1944 sconn,
1945 MSG_SMB_FORCE_TDIS_DENIED,
1946 msg_force_tdis_denied);
1947 messaging_register(sconn->msg_ctx, sconn,
1948 MSG_SMB_CLOSE_FILE, msg_close_file);
1949 messaging_register(sconn->msg_ctx, sconn,
1950 MSG_SMB_FILE_RENAME, msg_file_was_renamed);
1952 id_cache_register_msgs(sconn->msg_ctx);
1953 messaging_deregister(sconn->msg_ctx, ID_CACHE_KILL, NULL);
1954 messaging_register(sconn->msg_ctx, sconn,
1955 ID_CACHE_KILL, smbd_id_cache_kill);
1957 messaging_deregister(sconn->msg_ctx,
1958 MSG_SMB_CONF_UPDATED, sconn->ev_ctx);
1959 messaging_register(sconn->msg_ctx, sconn,
1960 MSG_SMB_CONF_UPDATED, smbd_conf_updated);
1962 messaging_deregister(sconn->msg_ctx, MSG_SMB_KILL_CLIENT_IP,
1963 NULL);
1964 messaging_register(sconn->msg_ctx, sconn,
1965 MSG_SMB_KILL_CLIENT_IP,
1966 msg_kill_client_ip);
1968 messaging_deregister(sconn->msg_ctx, MSG_SMB_TELL_NUM_CHILDREN, NULL);
1971 * Use the default MSG_DEBUG handler to avoid rebroadcasting
1972 * MSGs to all child processes
1974 messaging_deregister(sconn->msg_ctx,
1975 MSG_DEBUG, NULL);
1976 messaging_register(sconn->msg_ctx, NULL,
1977 MSG_DEBUG, debug_message);
1979 #if defined(WITH_SMB1SERVER)
1980 if ((lp_keepalive() != 0)
1981 && !(event_add_idle(ev_ctx, NULL,
1982 timeval_set(lp_keepalive(), 0),
1983 "keepalive", keepalive_fn,
1984 sconn))) {
1985 DEBUG(0, ("Could not add keepalive event\n"));
1986 exit(1);
1988 #endif
1990 if (!(event_add_idle(ev_ctx, NULL,
1991 timeval_set(IDLE_CLOSED_TIMEOUT, 0),
1992 "deadtime", deadtime_fn, sconn))) {
1993 DEBUG(0, ("Could not add deadtime event\n"));
1994 exit(1);
1997 if (!(event_add_idle(ev_ctx, NULL,
1998 timeval_set(SMBD_HOUSEKEEPING_INTERVAL, 0),
1999 "housekeeping", housekeeping_fn, sconn))) {
2000 DEBUG(0, ("Could not add housekeeping event\n"));
2001 exit(1);
2004 smbprofile_dump_setup(ev_ctx);
2006 if (!init_dptrs(sconn)) {
2007 exit_server("init_dptrs() failed");
2010 TALLOC_FREE(trace_state.frame);
2012 tevent_set_trace_callback(ev_ctx, smbd_tevent_trace_callback,
2013 &trace_state);
2015 ret = tevent_loop_wait(ev_ctx);
2016 if (ret != 0) {
2017 DEBUG(1, ("tevent_loop_wait failed: %d, %s,"
2018 " exiting\n", ret, strerror(errno)));
2021 TALLOC_FREE(trace_state.frame);
2023 exit_server_cleanly(NULL);