smbd: Give source3/smbd/dir.c its own header file
[samba.git] / source3 / smbd / smb2_process.c
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
6
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.
11
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.
16
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/>.
19 */
20
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"
50 #include "source3/smbd/dir.h"
51
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;
59         uint32_t seqnum;
60         bool encrypted;
61         bool processed;
62         DATA_BLOB buf;
63         struct deferred_open_record *open_rec;
64 };
65
66 static struct pending_message_list *get_deferred_open_message_smb(
67         struct smbd_server_connection *sconn, uint64_t mid);
68
69 #if !defined(WITH_SMB1SERVER)
70 bool smb1_srv_send(struct smbXsrv_connection *xconn,
71                    char *buffer,
72                    bool do_signing,
73                    uint32_t seqnum,
74                    bool do_encrypt)
75 {
76         size_t len = 0;
77         ssize_t ret;
78         len = smb_len_large(buffer) + 4;
79         ret = write_data(xconn->transport.sock, buffer, len);
80         return (ret > 0);
81 }
82 #endif
83
84 /*******************************************************************
85  Setup the word count and byte count for a smb1 message.
86 ********************************************************************/
87
88 size_t srv_smb1_set_message(char *buf,
89                        size_t num_words,
90                        size_t num_bytes,
91                        bool zero)
92 {
93         if (zero && (num_words || num_bytes)) {
94                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
95         }
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);
100 }
101
102 NTSTATUS read_packet_remainder(int fd, char *buffer,
103                                unsigned int timeout, ssize_t len)
104 {
105         NTSTATUS status;
106
107         if (len <= 0) {
108                 return NT_STATUS_OK;
109         }
110
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 "
115                           "error = %s.\n",
116                           get_peer_addr(fd, addr, sizeof(addr)),
117                           nt_errstr(status)));
118         }
119         return status;
120 }
121
122 #if !defined(WITH_SMB1SERVER)
123 static NTSTATUS smb2_receive_raw_talloc(TALLOC_CTX *mem_ctx,
124                                         struct smbXsrv_connection *xconn,
125                                         int sock,
126                                         char **buffer, unsigned int timeout,
127                                         size_t *p_unread, size_t *plen)
128 {
129         char lenbuf[4];
130         size_t len;
131         NTSTATUS status;
132
133         *p_unread = 0;
134
135         status = read_smb_length_return_keepalive(sock, lenbuf, timeout,
136                                                   &len);
137         if (!NT_STATUS_IS_OK(status)) {
138                 return status;
139         }
140
141         /*
142          * The +4 here can't wrap, we've checked the length above already.
143          */
144
145         *buffer = talloc_array(mem_ctx, char, len+4);
146
147         if (*buffer == NULL) {
148                 DEBUG(0, ("Could not allocate inbuf of length %d\n",
149                           (int)len+4));
150                 return NT_STATUS_NO_MEMORY;
151         }
152
153         memcpy(*buffer, lenbuf, sizeof(lenbuf));
154
155         status = read_packet_remainder(sock, (*buffer)+4, timeout, len);
156         if (!NT_STATUS_IS_OK(status)) {
157                 return status;
158         }
159
160         *plen = len + 4;
161         return NT_STATUS_OK;
162 }
163
164 static NTSTATUS smb2_receive_talloc(TALLOC_CTX *mem_ctx,
165                                     struct smbXsrv_connection *xconn,
166                                     int sock,
167                                     char **buffer, unsigned int timeout,
168                                     size_t *p_unread, bool *p_encrypted,
169                                     size_t *p_len,
170                                     uint32_t *seqnum,
171                                     bool trusted_channel)
172 {
173         size_t len = 0;
174         NTSTATUS status;
175
176         *p_encrypted = false;
177
178         status = smb2_receive_raw_talloc(mem_ctx, xconn, sock, buffer, timeout,
179                                          p_unread, &len);
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)) );
186                 return status;
187         }
188
189         *p_len = len;
190         return NT_STATUS_OK;
191 }
192 #endif
193
194 NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,
195                             struct smbXsrv_connection *xconn,
196                             int sock,
197                             char **buffer, unsigned int timeout,
198                             size_t *p_unread, bool *p_encrypted,
199                             size_t *p_len,
200                             uint32_t *seqnum,
201                             bool trusted_channel)
202 {
203 #if defined(WITH_SMB1SERVER)
204         return smb1_receive_talloc(mem_ctx, xconn, sock, buffer, timeout,
205                                    p_unread, p_encrypted, p_len, seqnum,
206                                    trusted_channel);
207 #else
208         return smb2_receive_talloc(mem_ctx, xconn, sock, buffer, timeout,
209                                    p_unread, p_encrypted, p_len, seqnum,
210                                    trusted_channel);
211 #endif
212 }
213
214 /****************************************************************************
215  Function to delete a sharing violation open message by mid.
216 ****************************************************************************/
217
218 void remove_deferred_open_message_smb(struct smbXsrv_connection *xconn,
219                                       uint64_t mid)
220 {
221         struct smbd_server_connection *sconn = xconn->client->sconn;
222         struct pending_message_list *pml;
223
224         if (sconn->using_smb2) {
225                 remove_deferred_open_message_smb2(xconn, mid);
226                 return;
227         }
228
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);
236                         TALLOC_FREE(pml);
237                         return;
238                 }
239         }
240 }
241
242 static void smbd_deferred_open_timer(struct tevent_context *ev,
243                                      struct tevent_timer *te,
244                                      struct timeval _tval,
245                                      void *private_data)
246 {
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);
253         uint8_t *inbuf;
254
255         inbuf = (uint8_t *)talloc_memdup(mem_ctx, msg->buf.data,
256                                          msg->buf.length);
257         if (inbuf == NULL) {
258                 exit_server("smbd_deferred_open_timer: talloc failed\n");
259                 return;
260         }
261
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 ));
266
267         /* Mark the message as processed so this is not
268          * re-processed in error. */
269         msg->processed = true;
270
271         process_smb(xconn,
272                     inbuf,
273                     msg->buf.length,
274                     0,
275                     msg->seqnum,
276                     msg->encrypted);
277
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);
282         }
283 }
284
285 /****************************************************************************
286  Move a sharing violation open retry message to the front of the list and
287  schedule it for immediate processing.
288 ****************************************************************************/
289
290 bool schedule_deferred_open_message_smb(struct smbXsrv_connection *xconn,
291                                         uint64_t mid)
292 {
293         struct smbd_server_connection *sconn = xconn->client->sconn;
294         struct pending_message_list *pml;
295         int i = 0;
296
297         if (sconn->using_smb2) {
298                 return schedule_deferred_open_message_smb2(xconn, mid);
299         }
300
301         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
302                 uint64_t msg_mid = (uint64_t)SVAL(pml->buf.data,smb_mid);
303
304                 DEBUG(10,("schedule_deferred_open_message_smb: [%d] "
305                         "msg_mid = %llu\n",
306                         i++,
307                         (unsigned long long)msg_mid ));
308
309                 if (mid == msg_mid) {
310                         struct tevent_timer *te;
311
312                         if (pml->processed) {
313                                 /* A processed message should not be
314                                  * rescheduled. */
315                                 DEBUG(0,("schedule_deferred_open_message_smb: LOGIC ERROR "
316                                         "message mid %llu was already processed\n",
317                                         (unsigned long long)msg_mid ));
318                                 continue;
319                         }
320
321                         DEBUG(10,("schedule_deferred_open_message_smb: "
322                                 "scheduling mid %llu\n",
323                                 (unsigned long long)mid ));
324
325                         /*
326                          * smbd_deferred_open_timer() calls
327                          * process_smb() to redispatch the request
328                          * including the required impersonation.
329                          *
330                          * So we can just use the raw tevent_context.
331                          */
332                         te = tevent_add_timer(xconn->client->raw_ev_ctx,
333                                               pml,
334                                               timeval_zero(),
335                                               smbd_deferred_open_timer,
336                                               pml);
337                         if (!te) {
338                                 DEBUG(10,("schedule_deferred_open_message_smb: "
339                                         "event_add_timed() failed, "
340                                         "skipping mid %llu\n",
341                                         (unsigned long long)msg_mid ));
342                         }
343
344                         TALLOC_FREE(pml->te);
345                         pml->te = te;
346                         DLIST_PROMOTE(sconn->deferred_open_queue, pml);
347                         return true;
348                 }
349         }
350
351         DEBUG(10,("schedule_deferred_open_message_smb: failed to "
352                 "find message mid %llu\n",
353                 (unsigned long long)mid ));
354
355         return false;
356 }
357
358 /****************************************************************************
359  Return true if this mid is on the deferred queue and was not yet processed.
360 ****************************************************************************/
361
362 bool open_was_deferred(struct smbXsrv_connection *xconn, uint64_t mid)
363 {
364         struct smbd_server_connection *sconn = xconn->client->sconn;
365         struct pending_message_list *pml;
366
367         if (sconn->using_smb2) {
368                 return open_was_deferred_smb2(xconn, mid);
369         }
370
371         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
372                 if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid && !pml->processed) {
373                         return True;
374                 }
375         }
376         return False;
377 }
378
379 /****************************************************************************
380  Return the message queued by this mid.
381 ****************************************************************************/
382
383 static struct pending_message_list *get_deferred_open_message_smb(
384         struct smbd_server_connection *sconn, uint64_t mid)
385 {
386         struct pending_message_list *pml;
387
388         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
389                 if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid) {
390                         return pml;
391                 }
392         }
393         return NULL;
394 }
395
396 /****************************************************************************
397  Get the state data queued by this mid.
398 ****************************************************************************/
399
400 bool get_deferred_open_message_state(struct smb_request *smbreq,
401                                 struct timeval *p_request_time,
402                                 struct deferred_open_record **open_rec)
403 {
404         struct pending_message_list *pml;
405
406         if (smbreq->sconn->using_smb2) {
407                 return get_deferred_open_message_state_smb2(smbreq->smb2req,
408                                         p_request_time,
409                                         open_rec);
410         }
411
412         pml = get_deferred_open_message_smb(smbreq->sconn, smbreq->mid);
413         if (!pml) {
414                 return false;
415         }
416         if (p_request_time) {
417                 *p_request_time = pml->request_time;
418         }
419         if (open_rec != NULL) {
420                 *open_rec = pml->open_rec;
421         }
422         return true;
423 }
424
425 bool push_deferred_open_message_smb(struct smb_request *req,
426                                     struct timeval timeout,
427                                     struct file_id id,
428                                     struct deferred_open_record *open_rec)
429 {
430 #if defined(WITH_SMB1SERVER)
431         if (req->smb2req) {
432 #endif
433                 return push_deferred_open_message_smb2(req->smb2req,
434                                                 req->request_time,
435                                                 timeout,
436                                                 id,
437                                                 open_rec);
438 #if defined(WITH_SMB1SERVER)
439         } else {
440                 return push_deferred_open_message_smb1(req, timeout,
441                                                        id, open_rec);
442         }
443 #endif
444 }
445
446 static void construct_smb1_reply_common(uint8_t cmd, const uint8_t *inbuf,
447                                    char *outbuf)
448 {
449         uint16_t in_flags2 = SVAL(inbuf,smb_flg2);
450         uint16_t out_flags2 = common_flags2;
451
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;
455
456         srv_smb1_set_message(outbuf,0,0,false);
457
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);
464
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));
470 }
471
472 void construct_smb1_reply_common_req(struct smb_request *req, char *outbuf)
473 {
474         construct_smb1_reply_common(req->cmd, req->inbuf, outbuf);
475 }
476
477 /*******************************************************************
478  allocate and initialize a reply packet
479 ********************************************************************/
480
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)
484 {
485         size_t smb_len = MIN_SMB_SIZE + VWV(num_words) + num_bytes;
486
487         /*
488          * Protect against integer wrap.
489          * The SMB layer reply can be up to 0xFFFFFF bytes.
490          */
491         if ((num_bytes > 0xffffff) || (smb_len > 0xffffff)) {
492                 char *msg;
493                 if (asprintf(&msg, "num_bytes too large: %u",
494                              (unsigned)num_bytes) == -1) {
495                         msg = discard_const_p(char, "num_bytes too large");
496                 }
497                 smb_panic(msg);
498         }
499
500         /*
501          * Here we include the NBT header for now.
502          */
503         *outbuf = talloc_array(mem_ctx, char,
504                                NBT_HDR_SIZE + smb_len);
505         if (*outbuf == NULL) {
506                 return false;
507         }
508
509         construct_smb1_reply_common(req->cmd, inbuf, *outbuf);
510         srv_smb1_set_message(*outbuf, num_words, num_bytes, false);
511         /*
512          * Zero out the word area, the caller has to take care of the bcc area
513          * himself
514          */
515         if (num_words != 0) {
516                 memset(*outbuf + (NBT_HDR_SIZE + HDR_VWV), 0, VWV(num_words));
517         }
518
519         return true;
520 }
521
522 void reply_smb1_outbuf(struct smb_request *req, uint8_t num_words, uint32_t num_bytes)
523 {
524         char *outbuf;
525         if (!create_smb1_outbuf(req, req, req->inbuf, &outbuf, num_words,
526                            num_bytes)) {
527                 smb_panic("could not allocate output buffer\n");
528         }
529         req->outbuf = (uint8_t *)outbuf;
530 }
531
532 bool valid_smb1_header(const uint8_t *inbuf)
533 {
534         if (is_encrypted_packet(inbuf)) {
535                 return true;
536         }
537         /*
538          * This used to be (strncmp(smb_base(inbuf),"\377SMB",4) == 0)
539          * but it just looks weird to call strncmp for this one.
540          */
541         return (IVAL(smb_base(inbuf), 0) == 0x424D53FF);
542 }
543
544 /****************************************************************************
545  Process an smb from the client
546 ****************************************************************************/
547
548 static void process_smb2(struct smbXsrv_connection *xconn,
549                          uint8_t *inbuf,
550                          size_t nread,
551                          size_t unread_bytes,
552                          uint32_t seqnum,
553                          bool encrypted)
554 {
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");
560         }
561 }
562
563 void process_smb(struct smbXsrv_connection *xconn,
564                  uint8_t *inbuf,
565                  size_t nread,
566                  size_t unread_bytes,
567                  uint32_t seqnum,
568                  bool encrypted)
569 {
570         struct smbd_server_connection *sconn = xconn->client->sconn;
571         int msg_type = CVAL(inbuf,0);
572
573         DO_PROFILE_INC(request);
574
575         DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type,
576                     smb_len(inbuf) ) );
577         DEBUG(3, ("Transaction %d of length %d (%u toread)\n",
578                   sconn->trans_num, (int)nread, (unsigned int)unread_bytes));
579
580         if (msg_type != NBSSmessage) {
581                 /*
582                  * NetBIOS session request, keepalive, etc.
583                  */
584                 reply_special(xconn, (char *)inbuf, nread);
585                 goto done;
586         }
587
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)) {
593 #endif
594                         process_smb2(xconn,
595                                      inbuf,
596                                      nread,
597                                      unread_bytes,
598                                      seqnum,
599                                      encrypted);
600                         return;
601 #if defined(WITH_SMB1SERVER)
602                 }
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;
608                 }
609         }
610         process_smb1(xconn, inbuf, nread, unread_bytes, seqnum, encrypted);
611 #endif
612
613 done:
614         sconn->num_requests++;
615
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. */
622
623         if ((sconn->num_requests % 50) == 0 &&
624             need_to_check_log_size()) {
625                 change_to_root_user();
626                 check_log_size();
627         }
628 }
629
630 NTSTATUS smbXsrv_connection_init_tables(struct smbXsrv_connection *conn,
631                                         enum protocol_types protocol)
632 {
633         NTSTATUS status;
634
635         conn->protocol = protocol;
636
637         if (conn->client->session_table != NULL) {
638                 return NT_STATUS_OK;
639         }
640
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;
645                         return status;
646                 }
647
648                 status = smb2srv_open_table_init(conn);
649                 if (!NT_STATUS_IS_OK(status)) {
650                         conn->protocol = PROTOCOL_NONE;
651                         return status;
652                 }
653         } else {
654 #if defined(WITH_SMB1SERVER)
655                 status = smb1srv_session_table_init(conn);
656                 if (!NT_STATUS_IS_OK(status)) {
657                         conn->protocol = PROTOCOL_NONE;
658                         return status;
659                 }
660
661                 status = smb1srv_tcon_table_init(conn);
662                 if (!NT_STATUS_IS_OK(status)) {
663                         conn->protocol = PROTOCOL_NONE;
664                         return status;
665                 }
666
667                 status = smb1srv_open_table_init(conn);
668                 if (!NT_STATUS_IS_OK(status)) {
669                         conn->protocol = PROTOCOL_NONE;
670                         return status;
671                 }
672 #else
673                 conn->protocol = PROTOCOL_NONE;
674                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
675 #endif
676         }
677
678         set_Protocol(protocol);
679         return NT_STATUS_OK;
680 }
681
682 /**
683  * Create a debug string for the connection
684  *
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.
688  */
689 const char *smbXsrv_connection_dbg(const struct smbXsrv_connection *xconn)
690 {
691         const char *ret;
692         char *addr;
693         /*
694          * TODO: this can be improved later
695          * maybe including the client guid or more
696          */
697         addr = tsocket_address_string(xconn->remote_address, talloc_tos());
698         if (addr == NULL) {
699                 return "<tsocket_address_string() failed>";
700         }
701
702         ret = talloc_asprintf(talloc_tos(), "ptr=%p,id=%llu,addr=%s",
703                               xconn, (unsigned long long)xconn->channel_id, addr);
704         TALLOC_FREE(addr);
705         if (ret == NULL) {
706                 return "<talloc_asprintf() failed>";
707         }
708
709         return ret;
710 }
711
712 /*
713  * Initialize a struct smb_request from an inbuf
714  */
715
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,
721                       uint32_t seqnum)
722 {
723         struct smbXsrv_tcon *tcon;
724         NTSTATUS status;
725         NTTIME now;
726         size_t req_size = smb_len(inbuf) + 4;
727
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 ));
732                 return false;
733         }
734
735         *req = (struct smb_request) { .cmd = 0};
736
737         req->request_time = timeval_current();
738         now = timeval_to_nttime(&req->request_time);
739
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;
753         req->sconn = sconn;
754         req->xconn = xconn;
755         if (xconn != NULL) {
756                 status = smb1srv_tcon_lookup(xconn, req->tid, now, &tcon);
757                 if (NT_STATUS_IS_OK(status)) {
758                         req->conn = tcon->compat;
759                 }
760         }
761         req->posix_pathnames = lp_posix_pathnames();
762
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));
768                 return false;
769         }
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));
777                 return false;
778         }
779
780         return true;
781 }
782
783 /****************************************************************************
784  Construct a reply to the incoming packet.
785 ****************************************************************************/
786
787 static void construct_reply_smb1negprot(struct smbXsrv_connection *xconn,
788                                         char *inbuf, int size,
789                                         size_t unread_bytes)
790 {
791         struct smbd_server_connection *sconn = xconn->client->sconn;
792         struct smb_request *req;
793         NTSTATUS status;
794
795         if (!(req = talloc(talloc_tos(), struct smb_request))) {
796                 smb_panic("could not allocate smb_request");
797         }
798
799         if (!init_smb1_request(req, sconn, xconn, (uint8_t *)inbuf, unread_bytes,
800                               false, 0)) {
801                 exit_server_cleanly("Invalid SMB request");
802         }
803
804         req->inbuf  = (uint8_t *)talloc_move(req, &inbuf);
805
806         status = smb2_multi_protocol_reply_negprot(req);
807         if (req->outbuf == NULL) {
808                 /*
809                 * req->outbuf == NULL means we bootstrapped into SMB2.
810                 */
811                 return;
812         }
813         if (!NT_STATUS_IS_OK(status)) {
814                 if (!smb1_srv_send(req->xconn,
815                                    (char *)req->outbuf,
816                                    true,
817                                    req->seqnum + 1,
818                                    IS_CONN_ENCRYPTED(req->conn) ||
819                                            req->encrypted)) {
820                         exit_server_cleanly("construct_reply_smb1negprot: "
821                                             "smb1_srv_send failed.");
822                 }
823                 TALLOC_FREE(req);
824         } else {
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");
828         }
829 }
830
831 static void smbd_server_connection_write_handler(
832         struct smbXsrv_connection *xconn)
833 {
834         /* TODO: make write nonblocking */
835 }
836
837 static void smbd_smb2_server_connection_read_handler(
838                         struct smbXsrv_connection *xconn, int fd)
839 {
840         char lenbuf[NBT_HDR_SIZE];
841         size_t len = 0;
842         uint8_t *buffer = NULL;
843         size_t bufferlen = 0;
844         NTSTATUS status;
845         uint8_t msg_type = 0;
846
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");
851                 return;
852         }
853
854         /* Integer wrap check. */
855         if (len + NBT_HDR_SIZE < len) {
856                 exit_server_cleanly("Invalid length on initial request");
857                 return;
858         }
859
860         /*
861          * The +4 here can't wrap, we've checked the length above already.
862          */
863         bufferlen = len+NBT_HDR_SIZE;
864
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",
868                         bufferlen);
869                 exit_server_cleanly("talloc fail");
870                 return;
871         }
872
873         /* Copy the NBT_HDR_SIZE length. */
874         memcpy(buffer, lenbuf, sizeof(lenbuf));
875
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");
879                 return;
880         }
881
882         /* Check the message type. */
883         msg_type = PULL_LE_U8(buffer,0);
884         if (msg_type == NBSSrequest) {
885                 /*
886                  * clients can send this request before
887                  * bootstrapping into SMB2. Cope with this
888                  * message only, don't allow any other strange
889                  * NBSS types.
890                  */
891                 reply_special(xconn, (char *)buffer, bufferlen);
892                 xconn->client->sconn->num_requests++;
893                 return;
894         }
895
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");
900                 return;
901         }
902
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");
906                 return;
907         }
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",
914                                 cmd);
915                         exit_server_cleanly("Invalid initial SMB1 packet");
916                 }
917                 /* Minimal process_smb(). */
918                 show_msg((char *)buffer);
919                 construct_reply_smb1negprot(xconn, (char *)buffer,
920                                             bufferlen, 0);
921                 xconn->client->sconn->trans_num++;
922                 xconn->client->sconn->num_requests++;
923                 return;
924
925         } else if (!smbd_is_smb2_header(buffer, bufferlen)) {
926                 exit_server_cleanly("Invalid initial SMB2 packet");
927                 return;
928         }
929
930         /* Here we know we're a valid SMB2 packet. */
931
932         /*
933          * Point at the start of the SMB2 PDU.
934          * len is the length of the SMB2 PDU.
935          */
936
937         status = smbd_smb2_process_negprot(xconn,
938                                            0,
939                                            (const uint8_t *)buffer+NBT_HDR_SIZE,
940                                            len);
941         if (!NT_STATUS_IS_OK(status)) {
942                 exit_server_cleanly("SMB2 negprot fail");
943         }
944         return;
945 }
946
947 static void smbd_server_connection_handler(struct tevent_context *ev,
948                                            struct tevent_fd *fde,
949                                            uint16_t flags,
950                                            void *private_data)
951 {
952         struct smbXsrv_connection *xconn =
953                 talloc_get_type_abort(private_data,
954                 struct smbXsrv_connection);
955
956         if (!NT_STATUS_IS_OK(xconn->transport.status)) {
957                 /*
958                  * we're not supposed to do any io
959                  */
960                 TEVENT_FD_NOT_READABLE(xconn->transport.fde);
961                 TEVENT_FD_NOT_WRITEABLE(xconn->transport.fde);
962                 return;
963         }
964
965         if (flags & TEVENT_FD_WRITE) {
966                 smbd_server_connection_write_handler(xconn);
967                 return;
968         }
969         if (flags & TEVENT_FD_READ) {
970 #if defined(WITH_SMB1SERVER)
971                 if (lp_server_min_protocol() > PROTOCOL_NT1) {
972 #endif
973                         smbd_smb2_server_connection_read_handler(xconn,
974                                                 xconn->transport.sock);
975 #if defined(WITH_SMB1SERVER)
976                 } else {
977                         smbd_smb1_server_connection_read_handler(xconn,
978                                                 xconn->transport.sock);
979                 }
980 #endif
981                 return;
982         }
983 }
984
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];
991 };
992
993 static int release_ip(struct tevent_context *ev,
994                       uint32_t src_vnn,
995                       uint32_t dst_vnn,
996                       uint64_t dst_srvid,
997                       const uint8_t *msg,
998                       size_t msglen,
999                       void *private_data);
1000
1001 static int smbd_release_ip_state_destructor(struct smbd_release_ip_state *s)
1002 {
1003         struct ctdbd_connection *cconn = messaging_ctdb_connection();
1004         struct smbXsrv_connection *xconn = s->xconn;
1005
1006         if (cconn == NULL) {
1007                 return 0;
1008         }
1009
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);
1012         } else {
1013                 ctdbd_unregister_ips(cconn, &s->srv, &s->clnt, release_ip, s);
1014         }
1015
1016         return 0;
1017 }
1018
1019 static void smbd_release_ip_immediate(struct tevent_context *ctx,
1020                                       struct tevent_immediate *im,
1021                                       void *private_data)
1022 {
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;
1027
1028         if (!NT_STATUS_EQUAL(xconn->transport.status, NT_STATUS_ADDRESS_CLOSED)) {
1029                 /*
1030                  * smbd_server_connection_terminate() already triggered ?
1031                  */
1032                 return;
1033         }
1034
1035         smbd_server_connection_terminate(xconn, "CTDB_SRVID_RELEASE_IP");
1036 }
1037
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,
1043                       uint64_t dst_srvid,
1044                       const uint8_t *msg, size_t msglen,
1045                       void *private_data)
1046 {
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;
1051         const char *ip;
1052         const char *addr = state->addr;
1053         const char *p = addr;
1054
1055         if (msglen == 0) {
1056                 return 0;
1057         }
1058         if (msg[msglen-1] != '\0') {
1059                 return 0;
1060         }
1061
1062         ip = (const char *)msg;
1063
1064         if (!NT_STATUS_IS_OK(xconn->transport.status)) {
1065                 /* avoid recursion */
1066                 return 0;
1067         }
1068
1069         if (strncmp("::ffff:", addr, 7) == 0) {
1070                 p = addr + 7;
1071         }
1072
1073         DEBUG(10, ("Got release IP message for %s, "
1074                    "our address is %s\n", ip, p));
1075
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",
1078                         ip));
1079                 /*
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.
1083                  *
1084                  * A clean disconnect is needed in order to support
1085                  * durable handles.
1086                  *
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.
1090                  *
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()
1094                  * (also for SMB1).
1095                  *
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
1099                  */
1100                 tevent_schedule_immediate(state->im,
1101                                           xconn->client->raw_ev_ctx,
1102                                           smbd_release_ip_immediate,
1103                                           state);
1104
1105                 /*
1106                  * Make sure we don't get any io on the connection.
1107                  */
1108                 xconn->transport.status = NT_STATUS_ADDRESS_CLOSED;
1109                 return EADDRNOTAVAIL;
1110         }
1111
1112         return 0;
1113 }
1114
1115 static int match_cluster_movable_ip(uint32_t total_ip_count,
1116                                     const struct sockaddr_storage *ip,
1117                                     bool is_movable_ip,
1118                                     void *private_data)
1119 {
1120         const struct sockaddr_storage *srv = private_data;
1121         struct samba_sockaddr pub_ip = {
1122                 .u = {
1123                         .ss = *ip,
1124                 },
1125         };
1126         struct samba_sockaddr srv_ip = {
1127                 .u = {
1128                         .ss = *srv,
1129                 },
1130         };
1131
1132         if (is_movable_ip && sockaddr_equal(&pub_ip.u.sa, &srv_ip.u.sa)) {
1133                 return EADDRNOTAVAIL;
1134         }
1135
1136         return 0;
1137 }
1138
1139 static NTSTATUS smbd_register_ips(struct smbXsrv_connection *xconn,
1140                                   struct sockaddr_storage *srv,
1141                                   struct sockaddr_storage *clnt)
1142 {
1143         struct smbd_release_ip_state *state;
1144         struct ctdbd_connection *cconn;
1145         int ret;
1146
1147         cconn = messaging_ctdb_connection();
1148         if (cconn == NULL) {
1149                 return NT_STATUS_NO_MEMORY;
1150         }
1151
1152         state = talloc_zero(xconn, struct smbd_release_ip_state);
1153         if (state == NULL) {
1154                 return NT_STATUS_NO_MEMORY;
1155         }
1156         state->xconn = xconn;
1157         state->im = tevent_create_immediate(state);
1158         if (state->im == NULL) {
1159                 return NT_STATUS_NO_MEMORY;
1160         }
1161         state->srv = *srv;
1162         state->clnt = *clnt;
1163         if (print_sockaddr(state->addr, sizeof(state->addr), srv) == NULL) {
1164                 return NT_STATUS_NO_MEMORY;
1165         }
1166
1167         if (xconn->client->server_multi_channel_enabled) {
1168                 ret = ctdbd_public_ip_foreach(cconn,
1169                                               match_cluster_movable_ip,
1170                                               srv);
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",
1177                                 strerror(ret));
1178                         return NT_STATUS_INTERNAL_ERROR;
1179                 }
1180         }
1181
1182         ret = ctdbd_register_ips(cconn, srv, clnt, release_ip, state);
1183         if (ret != 0) {
1184                 return map_nt_error_from_unix(ret);
1185         }
1186
1187         talloc_set_destructor(state, smbd_release_ip_state_destructor);
1188
1189         return NT_STATUS_OK;
1190 }
1191
1192 static int smbXsrv_connection_destructor(struct smbXsrv_connection *xconn)
1193 {
1194         DBG_DEBUG("xconn[%s]\n", smbXsrv_connection_dbg(xconn));
1195         return 0;
1196 }
1197
1198 NTSTATUS smbd_add_connection(struct smbXsrv_client *client, int sock_fd,
1199                              NTTIME now, struct smbXsrv_connection **_xconn)
1200 {
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;
1213         char *p;
1214         const char *rhost = NULL;
1215         int ret;
1216         int tmp;
1217
1218         *_xconn = NULL;
1219
1220         DO_PROFILE_INC(connect);
1221
1222         xconn = talloc_zero(client, struct smbXsrv_connection);
1223         if (xconn == NULL) {
1224                 DEBUG(0,("talloc_zero(struct smbXsrv_connection)\n"));
1225                 TALLOC_FREE(frame);
1226                 return NT_STATUS_NO_MEMORY;
1227         }
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++;
1234         }
1235
1236         xconn->transport.sock = sock_fd;
1237 #if defined(WITH_SMB1SERVER)
1238         smbd_echo_init(xconn);
1239 #endif
1240         xconn->protocol = PROTOCOL_NONE;
1241
1242         /* Ensure child is set to blocking mode */
1243         set_blocking(sock_fd,True);
1244
1245         set_socket_options(sock_fd, "SO_KEEPALIVE");
1246         set_socket_options(sock_fd, lp_socket_options());
1247
1248         sa_socklen = sizeof(ss_clnt);
1249         ret = getpeername(sock_fd, sa_clnt, &sa_socklen);
1250         if (ret != 0) {
1251                 int saved_errno = errno;
1252                 int level = (errno == ENOTCONN)?2:0;
1253                 DEBUG(level,("getpeername() failed - %s\n",
1254                       strerror(saved_errno)));
1255                 TALLOC_FREE(frame);
1256                 return map_nt_error_from_unix_common(saved_errno);
1257         }
1258         ret = tsocket_address_bsd_from_sockaddr(xconn,
1259                                                 sa_clnt, sa_socklen,
1260                                                 &remote_address);
1261         if (ret != 0) {
1262                 int saved_errno = errno;
1263                 DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
1264                         __location__, strerror(saved_errno)));
1265                 TALLOC_FREE(frame);
1266                 return map_nt_error_from_unix_common(saved_errno);
1267         }
1268
1269         sa_socklen = sizeof(ss_srv);
1270         ret = getsockname(sock_fd, sa_srv, &sa_socklen);
1271         if (ret != 0) {
1272                 int saved_errno = errno;
1273                 int level = (errno == ENOTCONN)?2:0;
1274                 DEBUG(level,("getsockname() failed - %s\n",
1275                       strerror(saved_errno)));
1276                 TALLOC_FREE(frame);
1277                 return map_nt_error_from_unix_common(saved_errno);
1278         }
1279         ret = tsocket_address_bsd_from_sockaddr(xconn,
1280                                                 sa_srv, sa_socklen,
1281                                                 &local_address);
1282         if (ret != 0) {
1283                 int saved_errno = errno;
1284                 DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
1285                         __location__, strerror(saved_errno)));
1286                 TALLOC_FREE(frame);
1287                 return map_nt_error_from_unix_common(saved_errno);
1288         }
1289
1290         if (tsocket_address_is_inet(remote_address, "ip")) {
1291                 remaddr = tsocket_address_inet_addr_string(remote_address,
1292                                                            talloc_tos());
1293                 if (remaddr == NULL) {
1294                         DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
1295                                  __location__, strerror(errno)));
1296                         TALLOC_FREE(frame);
1297                         return NT_STATUS_NO_MEMORY;
1298                 }
1299         } else {
1300                 remaddr = "0.0.0.0";
1301         }
1302
1303         /*
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.
1308          */
1309
1310         ret = get_remote_hostname(remote_address,
1311                                   &p, talloc_tos());
1312         if (ret < 0) {
1313                 int saved_errno = errno;
1314                 DEBUG(0,("%s: get_remote_hostname failed - %s\n",
1315                         __location__, strerror(saved_errno)));
1316                 TALLOC_FREE(frame);
1317                 return map_nt_error_from_unix_common(saved_errno);
1318         }
1319         rhost = p;
1320         if (strequal(rhost, "UNKNOWN")) {
1321                 rhost = remaddr;
1322         }
1323
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;
1329         }
1330
1331         if (!srv_init_signing(xconn)) {
1332                 DEBUG(0, ("Failed to init smb_signing\n"));
1333                 TALLOC_FREE(frame);
1334                 return NT_STATUS_INTERNAL_ERROR;
1335         }
1336
1337         if (!allow_access(lp_hosts_deny(-1), lp_hosts_allow(-1),
1338                           xconn->remote_hostname,
1339                           remaddr)) {
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())));
1343
1344                 /*
1345                  * We return a valid xconn
1346                  * so that the caller can return an error message
1347                  * to the client
1348                  */
1349                 DLIST_ADD_END(client->connections, xconn);
1350                 talloc_steal(client, xconn);
1351
1352                 *_xconn = xconn;
1353                 TALLOC_FREE(frame);
1354                 return NT_STATUS_NETWORK_ACCESS_DENIED;
1355         }
1356
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())));
1360
1361         if (lp_clustering()) {
1362                 /*
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
1366                  * client.
1367                  */
1368                 NTSTATUS status;
1369
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)));
1374                 }
1375         }
1376
1377         tmp = lp_max_xmit();
1378         tmp = MAX(tmp, SMB_BUFFER_SIZE_MIN);
1379         tmp = MIN(tmp, SMB_BUFFER_SIZE_MAX);
1380
1381 #if defined(WITH_SMB1SERVER)
1382         xconn->smb1.negprot.max_recv = tmp;
1383
1384         xconn->smb1.sessions.done_sesssetup = false;
1385         xconn->smb1.sessions.max_send = SMB_BUFFER_SIZE_MAX;
1386 #endif
1387
1388         xconn->transport.fde = tevent_add_fd(client->raw_ev_ctx,
1389                                              xconn,
1390                                              sock_fd,
1391                                              TEVENT_FD_READ,
1392                                              smbd_server_connection_handler,
1393                                              xconn);
1394         if (!xconn->transport.fde) {
1395                 TALLOC_FREE(frame);
1396                 return NT_STATUS_NO_MEMORY;
1397         }
1398         tevent_fd_set_auto_close(xconn->transport.fde);
1399
1400         /* for now we only have one connection */
1401         DLIST_ADD_END(client->connections, xconn);
1402         talloc_steal(client, xconn);
1403
1404         *_xconn = xconn;
1405         TALLOC_FREE(frame);
1406         return NT_STATUS_OK;
1407 }
1408
1409 static bool uid_in_use(struct auth_session_info *session_info,
1410                        uid_t uid)
1411 {
1412         if (session_info->unix_token->uid == uid) {
1413                 return true;
1414         }
1415         return false;
1416 }
1417
1418 static bool gid_in_use(struct auth_session_info *session_info,
1419                        gid_t gid)
1420 {
1421         uint32_t i;
1422         struct security_unix_token *utok = NULL;
1423
1424         utok = session_info->unix_token;
1425         if (utok->gid == gid) {
1426                 return true;
1427         }
1428
1429         for(i = 0; i < utok->ngroups; i++) {
1430                 if (utok->groups[i] == gid) {
1431                         return true;
1432                 }
1433         }
1434         return false;
1435 }
1436
1437 static bool sid_in_use(struct auth_session_info *session_info,
1438                        const struct dom_sid *psid)
1439 {
1440         struct security_token *tok = NULL;
1441
1442         tok = session_info->security_token;
1443         if (tok == NULL) {
1444                 /*
1445                  * Not sure session_info->security_token can
1446                  * ever be NULL. This check might be not
1447                  * necessary.
1448                  */
1449                 return false;
1450         }
1451         if (security_token_has_sid(tok, psid)) {
1452                 return true;
1453         }
1454         return false;
1455 }
1456
1457 struct id_in_use_state {
1458         const struct id_cache_ref *id;
1459         bool match;
1460 };
1461
1462 static int id_in_use_cb(struct smbXsrv_session *session,
1463                         void *private_data)
1464 {
1465         struct id_in_use_state *state = (struct id_in_use_state *)
1466                 private_data;
1467         struct auth_session_info *session_info =
1468                 session->global->auth_session_info;
1469
1470         switch(state->id->type) {
1471         case UID:
1472                 state->match = uid_in_use(session_info, state->id->id.uid);
1473                 break;
1474         case GID:
1475                 state->match = gid_in_use(session_info, state->id->id.gid);
1476                 break;
1477         case SID:
1478                 state->match = sid_in_use(session_info, &state->id->id.sid);
1479                 break;
1480         default:
1481                 state->match = false;
1482                 break;
1483         }
1484         if (state->match) {
1485                 return -1;
1486         }
1487         return 0;
1488 }
1489
1490 static bool id_in_use(struct smbd_server_connection *sconn,
1491                       const struct id_cache_ref *id)
1492 {
1493         struct id_in_use_state state;
1494         NTSTATUS status;
1495
1496         state = (struct id_in_use_state) {
1497                 .id = id,
1498                 .match = false,
1499         };
1500
1501         status = smbXsrv_session_local_traverse(sconn->client,
1502                                                 id_in_use_cb,
1503                                                 &state);
1504         if (!NT_STATUS_IS_OK(status)) {
1505                 return false;
1506         }
1507
1508         return state.match;
1509 }
1510
1511 /****************************************************************************
1512  Check if services need reloading.
1513 ****************************************************************************/
1514
1515 static void check_reload(struct smbd_server_connection *sconn, time_t t)
1516 {
1517
1518         if (last_smb_conf_reload_time == 0) {
1519                 last_smb_conf_reload_time = t;
1520         }
1521
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;
1525         }
1526 }
1527
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)
1531 {
1532         struct smbd_server_connection *sconn = talloc_get_type_abort(
1533                 private_data, struct smbd_server_connection);
1534         const char *ip = (char *) data->data;
1535         char *client_ip;
1536
1537         DBG_DEBUG("Got kill request for client IP %s\n", ip);
1538
1539         client_ip = tsocket_address_inet_addr_string(sconn->remote_address,
1540                                                      talloc_tos());
1541         if (client_ip == NULL) {
1542                 return;
1543         }
1544
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");
1549         }
1550
1551         TALLOC_FREE(client_ip);
1552 }
1553
1554 /*
1555  * Do the recurring check if we're idle
1556  */
1557 static bool deadtime_fn(const struct timeval *now, void *private_data)
1558 {
1559         struct smbd_server_connection *sconn =
1560                 (struct smbd_server_connection *)private_data;
1561
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);
1568                 return False;
1569         }
1570
1571         return True;
1572 }
1573
1574 /*
1575  * Do the recurring log file and smb.conf reload checks.
1576  */
1577
1578 static bool housekeeping_fn(const struct timeval *now, void *private_data)
1579 {
1580         struct smbd_server_connection *sconn = talloc_get_type_abort(
1581                 private_data, struct smbd_server_connection);
1582
1583         DEBUG(5, ("housekeeping\n"));
1584
1585         change_to_root_user();
1586
1587         /* check if we need to reload services */
1588         check_reload(sconn, time_mono(NULL));
1589
1590         /*
1591          * Force a log file check.
1592          */
1593         force_check_log_size();
1594         check_log_size();
1595         return true;
1596 }
1597
1598 static void smbd_sig_term_handler(struct tevent_context *ev,
1599                                   struct tevent_signal *se,
1600                                   int signum,
1601                                   int count,
1602                                   void *siginfo,
1603                                   void *private_data)
1604 {
1605         exit_server_cleanly("termination signal");
1606 }
1607
1608 static void smbd_setup_sig_term_handler(struct smbd_server_connection *sconn)
1609 {
1610         struct tevent_signal *se;
1611
1612         se = tevent_add_signal(sconn->ev_ctx,
1613                                sconn,
1614                                SIGTERM, 0,
1615                                smbd_sig_term_handler,
1616                                sconn);
1617         if (!se) {
1618                 exit_server("failed to setup SIGTERM handler");
1619         }
1620 }
1621
1622 static void smbd_sig_hup_handler(struct tevent_context *ev,
1623                                   struct tevent_signal *se,
1624                                   int signum,
1625                                   int count,
1626                                   void *siginfo,
1627                                   void *private_data)
1628 {
1629         struct smbd_server_connection *sconn =
1630                 talloc_get_type_abort(private_data,
1631                 struct smbd_server_connection);
1632
1633         change_to_root_user();
1634         DEBUG(1,("Reloading services after SIGHUP\n"));
1635         reload_services(sconn, conn_snum_used, false);
1636 }
1637
1638 static void smbd_setup_sig_hup_handler(struct smbd_server_connection *sconn)
1639 {
1640         struct tevent_signal *se;
1641
1642         se = tevent_add_signal(sconn->ev_ctx,
1643                                sconn,
1644                                SIGHUP, 0,
1645                                smbd_sig_hup_handler,
1646                                sconn);
1647         if (!se) {
1648                 exit_server("failed to setup SIGHUP handler");
1649         }
1650 }
1651
1652 static void smbd_conf_updated(struct messaging_context *msg,
1653                               void *private_data,
1654                               uint32_t msg_type,
1655                               struct server_id server_id,
1656                               DATA_BLOB *data)
1657 {
1658         struct smbd_server_connection *sconn =
1659                 talloc_get_type_abort(private_data,
1660                 struct smbd_server_connection);
1661
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);
1666 }
1667
1668 static void smbd_id_cache_kill(struct messaging_context *msg_ctx,
1669                                void *private_data,
1670                                uint32_t msg_type,
1671                                struct server_id server_id,
1672                                DATA_BLOB* data)
1673 {
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);
1680
1681         if (!id_cache_ref_parse(msg, &id)) {
1682                 DEBUG(0, ("Invalid ?ID: %s\n", msg));
1683                 return;
1684         }
1685
1686         if (id_in_use(sconn, &id)) {
1687                 exit_server_cleanly(msg);
1688         }
1689         id_cache_delete_from_cache(&id);
1690 }
1691
1692 struct smbd_tevent_trace_state {
1693         struct tevent_context *ev;
1694         TALLOC_CTX *frame;
1695         SMBPROFILE_BASIC_ASYNC_STATE(profile_idle);
1696 };
1697
1698 static inline void smbd_tevent_trace_callback_before_loop_once(
1699         struct smbd_tevent_trace_state *state)
1700 {
1701         talloc_free(state->frame);
1702         state->frame = talloc_stackframe_pool(8192);
1703 }
1704
1705 static inline void smbd_tevent_trace_callback_after_loop_once(
1706         struct smbd_tevent_trace_state *state)
1707 {
1708         TALLOC_FREE(state->frame);
1709 }
1710
1711 static void smbd_tevent_trace_callback(enum tevent_trace_point point,
1712                                        void *private_data)
1713 {
1714         struct smbd_tevent_trace_state *state =
1715                 (struct smbd_tevent_trace_state *)private_data;
1716
1717         switch (point) {
1718         case TEVENT_TRACE_BEFORE_WAIT:
1719                 break;
1720         case TEVENT_TRACE_AFTER_WAIT:
1721                 break;
1722         case TEVENT_TRACE_BEFORE_LOOP_ONCE:
1723                 smbd_tevent_trace_callback_before_loop_once(state);
1724                 break;
1725         case TEVENT_TRACE_AFTER_LOOP_ONCE:
1726                 smbd_tevent_trace_callback_after_loop_once(state);
1727                 break;
1728         }
1729
1730         errno = 0;
1731 }
1732
1733 static void smbd_tevent_trace_callback_profile(enum tevent_trace_point point,
1734                                                void *private_data)
1735 {
1736         struct smbd_tevent_trace_state *state =
1737                 (struct smbd_tevent_trace_state *)private_data;
1738
1739         switch (point) {
1740         case TEVENT_TRACE_BEFORE_WAIT:
1741                 if (!smbprofile_dump_pending()) {
1742                         /*
1743                          * If there's no dump pending
1744                          * we don't want to schedule a new 1 sec timer.
1745                          *
1746                          * Instead we want to sleep as long as nothing happens.
1747                          */
1748                         smbprofile_dump_setup(NULL);
1749                 }
1750                 SMBPROFILE_BASIC_ASYNC_START(idle, profile_p, state->profile_idle);
1751                 break;
1752         case TEVENT_TRACE_AFTER_WAIT:
1753                 SMBPROFILE_BASIC_ASYNC_END(state->profile_idle);
1754                 if (!smbprofile_dump_pending()) {
1755                         /*
1756                          * We need to flush our state after sleeping
1757                          * (hopefully a long time).
1758                          */
1759                         smbprofile_dump();
1760                         /*
1761                          * future profiling events should trigger timers
1762                          * on our main event context.
1763                          */
1764                         smbprofile_dump_setup(state->ev);
1765                 }
1766                 break;
1767         case TEVENT_TRACE_BEFORE_LOOP_ONCE:
1768                 smbd_tevent_trace_callback_before_loop_once(state);
1769                 break;
1770         case TEVENT_TRACE_AFTER_LOOP_ONCE:
1771                 smbd_tevent_trace_callback_after_loop_once(state);
1772                 break;
1773         }
1774
1775         errno = 0;
1776 }
1777
1778 /****************************************************************************
1779  Process commands from the client
1780 ****************************************************************************/
1781
1782 void smbd_process(struct tevent_context *ev_ctx,
1783                   struct messaging_context *msg_ctx,
1784                   int sock_fd,
1785                   bool interactive)
1786 {
1787         struct smbd_tevent_trace_state trace_state = {
1788                 .ev = ev_ctx,
1789                 .frame = talloc_stackframe(),
1790         };
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;
1798         int ret;
1799         NTSTATUS status;
1800         struct timeval tv = timeval_current();
1801         NTTIME now = timeval_to_nttime(&tv);
1802         char *chroot_dir = NULL;
1803         int rc;
1804
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");
1809         }
1810
1811         /*
1812          * TODO: remove this...:-)
1813          */
1814         global_smbXsrv_client = client;
1815
1816         sconn = talloc_zero(client, struct smbd_server_connection);
1817         if (sconn == NULL) {
1818                 exit_server("failed to create smbd_server_connection");
1819         }
1820
1821         client->sconn = sconn;
1822         sconn->client = client;
1823
1824         sconn->ev_ctx = ev_ctx;
1825         sconn->msg_ctx = msg_ctx;
1826
1827         ret = pthreadpool_tevent_init(sconn, lp_aio_max_threads(),
1828                                       &sconn->pool);
1829         if (ret != 0) {
1830                 exit_server("pthreadpool_tevent_init() failed.");
1831         }
1832
1833 #if defined(WITH_SMB1SERVER)
1834         if (lp_server_max_protocol() >= PROTOCOL_SMB2_02) {
1835 #endif
1836                 /*
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
1841                  * packet.
1842                  */
1843                 sconn->using_smb2 = true;
1844 #if defined(WITH_SMB1SERVER)
1845         }
1846 #endif
1847
1848         if (!interactive) {
1849                 smbd_setup_sig_term_handler(sconn);
1850                 smbd_setup_sig_hup_handler(sconn);
1851         }
1852
1853         status = smbd_add_connection(client, sock_fd, now, &xconn);
1854         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
1855                 /*
1856                  * send a negative session response "not listening on calling
1857                  * name"
1858                  */
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));
1864         }
1865
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");
1870         }
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");
1875         }
1876         sconn->remote_hostname =
1877                 talloc_strdup(sconn, xconn->remote_hostname);
1878         if (sconn->remote_hostname == NULL) {
1879                 exit_server_cleanly("tsocket_strdup() failed");
1880         }
1881
1882         client->global->local_address =
1883                 tsocket_address_string(sconn->local_address,
1884                                        client->global);
1885         if (client->global->local_address == NULL) {
1886                 exit_server_cleanly("tsocket_address_string() failed");
1887         }
1888         client->global->remote_address =
1889                 tsocket_address_string(sconn->remote_address,
1890                                        client->global);
1891         if (client->global->remote_address == NULL) {
1892                 exit_server_cleanly("tsocket_address_string() failed");
1893         }
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");
1898         }
1899
1900         if (tsocket_address_is_inet(sconn->local_address, "ip")) {
1901                 locaddr = tsocket_address_inet_addr_string(
1902                                 sconn->local_address,
1903                                 talloc_tos());
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");
1908                 }
1909         } else {
1910                 locaddr = "0.0.0.0";
1911         }
1912
1913         if (tsocket_address_is_inet(sconn->remote_address, "ip")) {
1914                 remaddr = tsocket_address_inet_addr_string(
1915                                 sconn->remote_address,
1916                                 talloc_tos());
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");
1921                 }
1922         } else {
1923                 remaddr = "0.0.0.0";
1924         }
1925
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,
1932                            locaddr);
1933
1934         if (lp_preload_modules()) {
1935                 smb_load_all_modules_absoute_path(lp_preload_modules());
1936         }
1937
1938         if (!init_account_policy()) {
1939                 exit_server("Could not open account policy tdb.\n");
1940         }
1941
1942         chroot_dir = lp_root_directory(talloc_tos(), lp_sub);
1943         if (chroot_dir[0] != '\0') {
1944                 rc = chdir(chroot_dir);
1945                 if (rc != 0) {
1946                         DBG_ERR("Failed to chdir to %s\n", chroot_dir);
1947                         exit_server("Failed to chdir()");
1948                 }
1949
1950                 rc = chroot(chroot_dir);
1951                 if (rc != 0) {
1952                         DBG_ERR("Failed to change root to %s\n", chroot_dir);
1953                         exit_server("Failed to chroot()");
1954                 }
1955                 DBG_WARNING("Changed root to %s\n", chroot_dir);
1956
1957                 TALLOC_FREE(chroot_dir);
1958         }
1959
1960         if (!file_init(sconn)) {
1961                 exit_server("file_init() failed");
1962         }
1963
1964         /* Setup oplocks */
1965         if (!init_oplocks(sconn))
1966                 exit_server("Failed to init oplocks");
1967
1968         /* register our message handlers */
1969         messaging_register(sconn->msg_ctx, sconn,
1970                            MSG_SMB_FORCE_TDIS, msg_force_tdis);
1971         messaging_register(
1972                 sconn->msg_ctx,
1973                 sconn,
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);
1980
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);
1985
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);
1990
1991         messaging_deregister(sconn->msg_ctx, MSG_SMB_KILL_CLIENT_IP,
1992                              NULL);
1993         messaging_register(sconn->msg_ctx, sconn,
1994                            MSG_SMB_KILL_CLIENT_IP,
1995                            msg_kill_client_ip);
1996
1997         messaging_deregister(sconn->msg_ctx, MSG_SMB_TELL_NUM_CHILDREN, NULL);
1998
1999         /*
2000          * Use the default MSG_DEBUG handler to avoid rebroadcasting
2001          * MSGs to all child processes
2002          */
2003         messaging_deregister(sconn->msg_ctx,
2004                              MSG_DEBUG, NULL);
2005         messaging_register(sconn->msg_ctx, NULL,
2006                            MSG_DEBUG, debug_message);
2007
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,
2013                                 sconn))) {
2014                 DEBUG(0, ("Could not add keepalive event\n"));
2015                 exit(1);
2016         }
2017 #endif
2018
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"));
2023                 exit(1);
2024         }
2025
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"));
2030                 exit(1);
2031         }
2032
2033         smbprofile_dump_setup(ev_ctx);
2034
2035         if (!init_dptrs(sconn)) {
2036                 exit_server("init_dptrs() failed");
2037         }
2038
2039         TALLOC_FREE(trace_state.frame);
2040
2041         if (smbprofile_active()) {
2042                 tevent_set_trace_callback(ev_ctx,
2043                                           smbd_tevent_trace_callback_profile,
2044                                           &trace_state);
2045         } else {
2046                 tevent_set_trace_callback(ev_ctx,
2047                                           smbd_tevent_trace_callback,
2048                                           &trace_state);
2049         }
2050
2051         ret = tevent_loop_wait(ev_ctx);
2052         if (ret != 0) {
2053                 DEBUG(1, ("tevent_loop_wait failed: %d, %s,"
2054                           " exiting\n", ret, strerror(errno)));
2055         }
2056
2057         TALLOC_FREE(trace_state.frame);
2058
2059         exit_server_cleanly(NULL);
2060 }