s3:smbd: only do profiling overhead in smbd_tevent_trace_callback() when needed
[bbaumbach/samba-autobuild/.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
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;
64 };
65
66 static struct pending_message_list *get_deferred_open_message_smb(
67         struct smbd_server_connection *sconn, uint64_t mid);
68
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)
73 {
74         size_t len = 0;
75         ssize_t ret;
76         char *buf_out = buffer;
77
78         if (!NT_STATUS_IS_OK(xconn->transport.status)) {
79                 /*
80                  * we're not supposed to do any io
81                  */
82                 return true;
83         }
84
85         len = smb_len_large(buf_out) + 4;
86
87         ret = write_data(xconn->transport.sock, buf_out, len);
88         if (ret <= 0) {
89                 int saved_errno = errno;
90                 /*
91                  * Try and give an error message saying what
92                  * client failed.
93                  */
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;
99
100                 srv_free_enc_buffer(xconn, buf_out);
101                 goto out;
102         }
103
104         SMB_PERFCOUNT_SET_MSGLEN_OUT(pcd, len);
105         srv_free_enc_buffer(xconn, buf_out);
106 out:
107         SMB_PERFCOUNT_END(pcd);
108
109         return (ret > 0);
110 }
111
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)
117 {
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);
123 }
124 #endif
125
126 /*******************************************************************
127  Setup the word count and byte count for a smb1 message.
128 ********************************************************************/
129
130 size_t srv_smb1_set_message(char *buf,
131                        size_t num_words,
132                        size_t num_bytes,
133                        bool zero)
134 {
135         if (zero && (num_words || num_bytes)) {
136                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
137         }
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);
142 }
143
144 NTSTATUS read_packet_remainder(int fd, char *buffer,
145                                unsigned int timeout, ssize_t len)
146 {
147         NTSTATUS status;
148
149         if (len <= 0) {
150                 return NT_STATUS_OK;
151         }
152
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)));
160         }
161         return status;
162 }
163
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)
170 {
171         char lenbuf[4];
172         size_t len;
173         NTSTATUS status;
174
175         *p_unread = 0;
176
177         status = read_smb_length_return_keepalive(sock, lenbuf, timeout,
178                                                   &len);
179         if (!NT_STATUS_IS_OK(status)) {
180                 return status;
181         }
182
183         /*
184          * The +4 here can't wrap, we've checked the length above already.
185          */
186
187         *buffer = talloc_array(mem_ctx, char, len+4);
188
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;
193         }
194
195         memcpy(*buffer, lenbuf, sizeof(lenbuf));
196
197         status = read_packet_remainder(sock, (*buffer)+4, timeout, len);
198         if (!NT_STATUS_IS_OK(status)) {
199                 return status;
200         }
201
202         *plen = len + 4;
203         return NT_STATUS_OK;
204 }
205
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)
214 {
215         size_t len = 0;
216         NTSTATUS status;
217
218         *p_encrypted = false;
219
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;
229         }
230
231         *p_len = len;
232         return NT_STATUS_OK;
233 }
234 #endif
235
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)
244 {
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
254 }
255
256 /****************************************************************************
257  Function to delete a sharing violation open message by mid.
258 ****************************************************************************/
259
260 void remove_deferred_open_message_smb(struct smbXsrv_connection *xconn,
261                                       uint64_t mid)
262 {
263         struct smbd_server_connection *sconn = xconn->client->sconn;
264         struct pending_message_list *pml;
265
266         if (sconn->using_smb2) {
267                 remove_deferred_open_message_smb2(xconn, mid);
268                 return;
269         }
270
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;
280                 }
281         }
282 }
283
284 static void smbd_deferred_open_timer(struct tevent_context *ev,
285                                      struct tevent_timer *te,
286                                      struct timeval _tval,
287                                      void *private_data)
288 {
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;
296
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;
302         }
303
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 ));
308
309         /* Mark the message as processed so this is not
310          * re-processed in error. */
311         msg->processed = true;
312
313         process_smb(xconn, inbuf,
314                     msg->buf.length, 0,
315                     msg->seqnum, msg->encrypted, &msg->pcd);
316
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);
321         }
322 }
323
324 /****************************************************************************
325  Move a sharing violation open retry message to the front of the list and
326  schedule it for immediate processing.
327 ****************************************************************************/
328
329 bool schedule_deferred_open_message_smb(struct smbXsrv_connection *xconn,
330                                         uint64_t mid)
331 {
332         struct smbd_server_connection *sconn = xconn->client->sconn;
333         struct pending_message_list *pml;
334         int i = 0;
335
336         if (sconn->using_smb2) {
337                 return schedule_deferred_open_message_smb2(xconn, mid);
338         }
339
340         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
341                 uint64_t msg_mid = (uint64_t)SVAL(pml->buf.data,smb_mid);
342
343                 DEBUG(10,("schedule_deferred_open_message_smb: [%d] "
344                         "msg_mid = %llu\n",
345                         i++,
346                         (unsigned long long)msg_mid ));
347
348                 if (mid == msg_mid) {
349                         struct tevent_timer *te;
350
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;
358                         }
359
360                         DEBUG(10,("schedule_deferred_open_message_smb: "
361                                 "scheduling mid %llu\n",
362                                 (unsigned long long)mid ));
363
364                         /*
365                          * smbd_deferred_open_timer() calls
366                          * process_smb() to redispatch the request
367                          * including the required impersonation.
368                          *
369                          * So we can just use the raw tevent_context.
370                          */
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 ));
381                         }
382
383                         TALLOC_FREE(pml->te);
384                         pml->te = te;
385                         DLIST_PROMOTE(sconn->deferred_open_queue, pml);
386                         return true;
387                 }
388         }
389
390         DEBUG(10,("schedule_deferred_open_message_smb: failed to "
391                 "find message mid %llu\n",
392                 (unsigned long long)mid ));
393
394         return false;
395 }
396
397 /****************************************************************************
398  Return true if this mid is on the deferred queue and was not yet processed.
399 ****************************************************************************/
400
401 bool open_was_deferred(struct smbXsrv_connection *xconn, uint64_t mid)
402 {
403         struct smbd_server_connection *sconn = xconn->client->sconn;
404         struct pending_message_list *pml;
405
406         if (sconn->using_smb2) {
407                 return open_was_deferred_smb2(xconn, mid);
408         }
409
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;
413                 }
414         }
415         return False;
416 }
417
418 /****************************************************************************
419  Return the message queued by this mid.
420 ****************************************************************************/
421
422 static struct pending_message_list *get_deferred_open_message_smb(
423         struct smbd_server_connection *sconn, uint64_t mid)
424 {
425         struct pending_message_list *pml;
426
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;
430                 }
431         }
432         return NULL;
433 }
434
435 /****************************************************************************
436  Get the state data queued by this mid.
437 ****************************************************************************/
438
439 bool get_deferred_open_message_state(struct smb_request *smbreq,
440                                 struct timeval *p_request_time,
441                                 struct deferred_open_record **open_rec)
442 {
443         struct pending_message_list *pml;
444
445         if (smbreq->sconn->using_smb2) {
446                 return get_deferred_open_message_state_smb2(smbreq->smb2req,
447                                         p_request_time,
448                                         open_rec);
449         }
450
451         pml = get_deferred_open_message_smb(smbreq->sconn, smbreq->mid);
452         if (!pml) {
453                 return false;
454         }
455         if (p_request_time) {
456                 *p_request_time = pml->request_time;
457         }
458         if (open_rec != NULL) {
459                 *open_rec = pml->open_rec;
460         }
461         return true;
462 }
463
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)
468 {
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,
475                                                 id,
476                                                 open_rec);
477 #if defined(WITH_SMB1SERVER)
478         } else {
479                 return push_deferred_open_message_smb1(req, timeout,
480                                                        id, open_rec);
481         }
482 #endif
483 }
484
485 static void construct_smb1_reply_common(uint8_t cmd, const uint8_t *inbuf,
486                                    char *outbuf)
487 {
488         uint16_t in_flags2 = SVAL(inbuf,smb_flg2);
489         uint16_t out_flags2 = common_flags2;
490
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;
494
495         srv_smb1_set_message(outbuf,0,0,false);
496
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);
503
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));
509 }
510
511 void construct_smb1_reply_common_req(struct smb_request *req, char *outbuf)
512 {
513         construct_smb1_reply_common(req->cmd, req->inbuf, outbuf);
514 }
515
516 /*******************************************************************
517  allocate and initialize a reply packet
518 ********************************************************************/
519
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)
523 {
524         size_t smb_len = MIN_SMB_SIZE + VWV(num_words) + num_bytes;
525
526         /*
527          * Protect against integer wrap.
528          * The SMB layer reply can be up to 0xFFFFFF bytes.
529          */
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");
535                 }
536                 smb_panic(msg);
537         }
538
539         /*
540          * Here we include the NBT header for now.
541          */
542         *outbuf = talloc_array(mem_ctx, char,
543                                NBT_HDR_SIZE + smb_len);
544         if (*outbuf == NULL) {
545                 return false;
546         }
547
548         construct_smb1_reply_common(req->cmd, inbuf, *outbuf);
549         srv_smb1_set_message(*outbuf, num_words, num_bytes, false);
550         /*
551          * Zero out the word area, the caller has to take care of the bcc area
552          * himself
553          */
554         if (num_words != 0) {
555                 memset(*outbuf + (NBT_HDR_SIZE + HDR_VWV), 0, VWV(num_words));
556         }
557
558         return true;
559 }
560
561 void reply_smb1_outbuf(struct smb_request *req, uint8_t num_words, uint32_t num_bytes)
562 {
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");
567         }
568         req->outbuf = (uint8_t *)outbuf;
569 }
570
571 bool valid_smb1_header(const uint8_t *inbuf)
572 {
573         if (is_encrypted_packet(inbuf)) {
574                 return true;
575         }
576         /*
577          * This used to be (strncmp(smb_base(inbuf),"\377SMB",4) == 0)
578          * but it just looks weird to call strncmp for this one.
579          */
580         return (IVAL(smb_base(inbuf), 0) == 0x424D53FF);
581 }
582
583 /****************************************************************************
584  Process an smb from the client
585 ****************************************************************************/
586
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)
591 {
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");
597         }
598 }
599
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)
604 {
605         struct smbd_server_connection *sconn = xconn->client->sconn;
606         int msg_type = CVAL(inbuf,0);
607
608         DO_PROFILE_INC(request);
609
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));
614
615         if (msg_type != NBSSmessage) {
616                 /*
617                  * NetBIOS session request, keepalive, etc.
618                  */
619                 reply_special(xconn, (char *)inbuf, nread);
620                 goto done;
621         }
622
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)
633                 }
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;
639                 }
640         }
641         process_smb1(xconn, inbuf, nread, unread_bytes, seqnum, encrypted,
642                      deferred_pcd);
643 #endif
644
645 done:
646         sconn->num_requests++;
647
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. */
654
655         if ((sconn->num_requests % 50) == 0 &&
656             need_to_check_log_size()) {
657                 change_to_root_user();
658                 check_log_size();
659         }
660 }
661
662 NTSTATUS smbXsrv_connection_init_tables(struct smbXsrv_connection *conn,
663                                         enum protocol_types protocol)
664 {
665         NTSTATUS status;
666
667         conn->protocol = protocol;
668
669         if (conn->client->session_table != NULL) {
670                 return NT_STATUS_OK;
671         }
672
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;
678                 }
679
680                 status = smb2srv_open_table_init(conn);
681                 if (!NT_STATUS_IS_OK(status)) {
682                         conn->protocol = PROTOCOL_NONE;
683                         return status;
684                 }
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;
691                 }
692
693                 status = smb1srv_tcon_table_init(conn);
694                 if (!NT_STATUS_IS_OK(status)) {
695                         conn->protocol = PROTOCOL_NONE;
696                         return status;
697                 }
698
699                 status = smb1srv_open_table_init(conn);
700                 if (!NT_STATUS_IS_OK(status)) {
701                         conn->protocol = PROTOCOL_NONE;
702                         return status;
703                 }
704 #else
705                 conn->protocol = PROTOCOL_NONE;
706                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
707 #endif
708         }
709
710         set_Protocol(protocol);
711         return NT_STATUS_OK;
712 }
713
714 /**
715  * Create a debug string for the connection
716  *
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.
720  */
721 const char *smbXsrv_connection_dbg(const struct smbXsrv_connection *xconn)
722 {
723         const char *ret;
724         char *addr;
725         /*
726          * TODO: this can be improved later
727          * maybe including the client guid or more
728          */
729         addr = tsocket_address_string(xconn->remote_address, talloc_tos());
730         if (addr == NULL) {
731                 return "<tsocket_address_string() failed>";
732         }
733
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>";
739         }
740
741         return ret;
742 }
743
744 /*
745  * Initialize a struct smb_request from an inbuf
746  */
747
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)
754 {
755         struct smbXsrv_tcon *tcon;
756         NTSTATUS status;
757         NTTIME now;
758         size_t req_size = smb_len(inbuf) + 4;
759
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;
765         }
766
767         req->request_time = timeval_current();
768         now = timeval_to_nttime(&req->request_time);
769
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;
790                 }
791         }
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);
797
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;
804         }
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;
813         }
814
815         req->outbuf = NULL;
816         return true;
817 }
818
819 /****************************************************************************
820  Construct a reply to the incoming packet.
821 ****************************************************************************/
822
823 static void construct_reply_smb1negprot(struct smbXsrv_connection *xconn,
824                                         char *inbuf, int size,
825                                         size_t unread_bytes)
826 {
827         struct smbd_server_connection *sconn = xconn->client->sconn;
828         struct smb_request *req;
829         NTSTATUS status;
830
831         if (!(req = talloc(talloc_tos(), struct smb_request))) {
832                 smb_panic("could not allocate smb_request");
833         }
834
835         if (!init_smb1_request(req, sconn, xconn, (uint8_t *)inbuf, unread_bytes,
836                               false, 0)) {
837                 exit_server_cleanly("Invalid SMB request");
838         }
839
840         req->inbuf  = (uint8_t *)talloc_move(req, &inbuf);
841
842         status = smb2_multi_protocol_reply_negprot(req);
843         if (req->outbuf == NULL) {
844                 /*
845                 * req->outbuf == NULL means we bootstrapped into SMB2.
846                 */
847                 return;
848         }
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.");
857                 }
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");
863         }
864 }
865
866 static void smbd_server_connection_write_handler(
867         struct smbXsrv_connection *xconn)
868 {
869         /* TODO: make write nonblocking */
870 }
871
872 static void smbd_smb2_server_connection_read_handler(
873                         struct smbXsrv_connection *xconn, int fd)
874 {
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;
881
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;
887         }
888
889         /* Integer wrap check. */
890         if (len + NBT_HDR_SIZE < len) {
891                 exit_server_cleanly("Invalid length on initial request");
892                 return;
893         }
894
895         /*
896          * The +4 here can't wrap, we've checked the length above already.
897          */
898         bufferlen = len+NBT_HDR_SIZE;
899
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;
906         }
907
908         /* Copy the NBT_HDR_SIZE length. */
909         memcpy(buffer, lenbuf, sizeof(lenbuf));
910
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;
915         }
916
917         /* Check the message type. */
918         msg_type = PULL_LE_U8(buffer,0);
919         if (msg_type == NBSSrequest) {
920                 /*
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.
925                  */
926                 reply_special(xconn, (char *)buffer, bufferlen);
927                 xconn->client->sconn->num_requests++;
928                 return;
929         }
930
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;
936         }
937
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;
942         }
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");
951                 }
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;
959
960         } else if (!smbd_is_smb2_header(buffer, bufferlen)) {
961                 exit_server_cleanly("Invalid initial SMB2 packet");
962                 return;
963         }
964
965         /* Here we know we're a valid SMB2 packet. */
966
967         /*
968          * Point at the start of the SMB2 PDU.
969          * len is the length of the SMB2 PDU.
970          */
971
972         status = smbd_smb2_process_negprot(xconn,
973                                            0,
974                                            (const uint8_t *)buffer+NBT_HDR_SIZE,
975                                            len);
976         if (!NT_STATUS_IS_OK(status)) {
977                 exit_server_cleanly("SMB2 negprot fail");
978         }
979         return;
980 }
981
982 static void smbd_server_connection_handler(struct tevent_context *ev,
983                                            struct tevent_fd *fde,
984                                            uint16_t flags,
985                                            void *private_data)
986 {
987         struct smbXsrv_connection *xconn =
988                 talloc_get_type_abort(private_data,
989                 struct smbXsrv_connection);
990
991         if (!NT_STATUS_IS_OK(xconn->transport.status)) {
992                 /*
993                  * we're not supposed to do any io
994                  */
995                 TEVENT_FD_NOT_READABLE(xconn->transport.fde);
996                 TEVENT_FD_NOT_WRITEABLE(xconn->transport.fde);
997                 return;
998         }
999
1000         if (flags & TEVENT_FD_WRITE) {
1001                 smbd_server_connection_write_handler(xconn);
1002                 return;
1003         }
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);
1014                 }
1015 #endif
1016                 return;
1017         }
1018 }
1019
1020 struct smbd_release_ip_state {
1021         struct smbXsrv_connection *xconn;
1022         struct tevent_immediate *im;
1023         char addr[INET6_ADDRSTRLEN];
1024 };
1025
1026 static void smbd_release_ip_immediate(struct tevent_context *ctx,
1027                                       struct tevent_immediate *im,
1028                                       void *private_data)
1029 {
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;
1034
1035         if (!NT_STATUS_EQUAL(xconn->transport.status, NT_STATUS_ADDRESS_CLOSED)) {
1036                 /*
1037                  * smbd_server_connection_terminate() already triggered ?
1038                  */
1039                 return;
1040         }
1041
1042         smbd_server_connection_terminate(xconn, "CTDB_SRVID_RELEASE_IP");
1043 }
1044
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)
1053 {
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;
1061
1062         if (msglen == 0) {
1063                 return 0;
1064         }
1065         if (msg[msglen-1] != '\0') {
1066                 return 0;
1067         }
1068
1069         ip = (const char *)msg;
1070
1071         if (!NT_STATUS_IS_OK(xconn->transport.status)) {
1072                 /* avoid recursion */
1073                 return 0;
1074         }
1075
1076         if (strncmp("::ffff:", addr, 7) == 0) {
1077                 p = addr + 7;
1078         }
1079
1080         DEBUG(10, ("Got release IP message for %s, "
1081                    "our address is %s\n", ip, p));
1082
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));
1086                 /*
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.
1090                  *
1091                  * A clean disconnect is needed in order to support
1092                  * durable handles.
1093                  *
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.
1097                  *
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).
1102                  *
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
1106                  */
1107                 tevent_schedule_immediate(state->im,
1108                                           xconn->client->raw_ev_ctx,
1109                                           smbd_release_ip_immediate,
1110                                           state);
1111
1112                 /*
1113                  * Make sure we don't get any io on the connection.
1114                  */
1115                 xconn->transport.status = NT_STATUS_ADDRESS_CLOSED;
1116                 return EADDRNOTAVAIL;
1117         }
1118
1119         return 0;
1120 }
1121
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)
1126 {
1127         const struct sockaddr_storage *srv = private_data;
1128         struct samba_sockaddr pub_ip = {
1129                 .u = {
1130                         .ss = *ip,
1131                 },
1132         };
1133         struct samba_sockaddr srv_ip = {
1134                 .u = {
1135                         .ss = *srv,
1136                 },
1137         };
1138
1139         if (is_movable_ip && sockaddr_equal(&pub_ip.u.sa, &srv_ip.u.sa)) {
1140                 return EADDRNOTAVAIL;
1141         }
1142
1143         return 0;
1144 }
1145
1146 static NTSTATUS smbd_register_ips(struct smbXsrv_connection *xconn,
1147                                   struct sockaddr_storage *srv,
1148                                   struct sockaddr_storage *clnt)
1149 {
1150         struct smbd_release_ip_state *state;
1151         struct ctdbd_connection *cconn;
1152         int ret;
1153
1154         cconn = messaging_ctdb_connection();
1155         if (cconn == NULL) {
1156                 return NT_STATUS_NO_MEMORY;
1157         }
1158
1159         state = talloc_zero(xconn, struct smbd_release_ip_state);
1160         if (state == NULL) {
1161                 return NT_STATUS_NO_MEMORY;
1162         }
1163         state->xconn = xconn;
1164         state->im = tevent_create_immediate(state);
1165         if (state->im == NULL) {
1166                 return NT_STATUS_NO_MEMORY;
1167         }
1168         if (print_sockaddr(state->addr, sizeof(state->addr), srv) == NULL) {
1169                 return NT_STATUS_NO_MEMORY;
1170         }
1171
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;
1184                 }
1185         }
1186
1187         ret = ctdbd_register_ips(cconn, srv, clnt, release_ip, state);
1188         if (ret != 0) {
1189                 return map_nt_error_from_unix(ret);
1190         }
1191         return NT_STATUS_OK;
1192 }
1193
1194 static int smbXsrv_connection_destructor(struct smbXsrv_connection *xconn)
1195 {
1196         DBG_DEBUG("xconn[%s]\n", smbXsrv_connection_dbg(xconn));
1197         return 0;
1198 }
1199
1200 NTSTATUS smbd_add_connection(struct smbXsrv_client *client, int sock_fd,
1201                              NTTIME now, struct smbXsrv_connection **_xconn)
1202 {
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;
1219
1220         *_xconn = NULL;
1221
1222         DO_PROFILE_INC(connect);
1223
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;
1229         }
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++;
1236         }
1237
1238         xconn->transport.sock = sock_fd;
1239 #if defined(WITH_SMB1SERVER)
1240         smbd_echo_init(xconn);
1241 #endif
1242         xconn->protocol = PROTOCOL_NONE;
1243
1244         /* Ensure child is set to blocking mode */
1245         set_blocking(sock_fd,True);
1246
1247         set_socket_options(sock_fd, "SO_KEEPALIVE");
1248         set_socket_options(sock_fd, lp_socket_options());
1249
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);
1259         }
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);
1269         }
1270
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);
1280         }
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);
1290         }
1291
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;
1300                 }
1301         } else {
1302                 remaddr = "0.0.0.0";
1303         }
1304
1305         /*
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.
1310          */
1311
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);
1320         }
1321         rhost = p;
1322         if (strequal(rhost, "UNKNOWN")) {
1323                 rhost = remaddr;
1324         }
1325
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;
1331         }
1332
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;
1337         }
1338
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())));
1345
1346                 /*
1347                  * We return a valid xconn
1348                  * so that the caller can return an error message
1349                  * to the client
1350                  */
1351                 DLIST_ADD_END(client->connections, xconn);
1352                 talloc_steal(client, xconn);
1353
1354                 *_xconn = xconn;
1355                 TALLOC_FREE(frame);
1356                 return NT_STATUS_NETWORK_ACCESS_DENIED;
1357         }
1358
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())));
1362
1363         if (lp_clustering()) {
1364                 /*
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.
1369                  */
1370                 NTSTATUS status;
1371
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)));
1376                 }
1377         }
1378
1379         tmp = lp_max_xmit();
1380         tmp = MAX(tmp, SMB_BUFFER_SIZE_MIN);
1381         tmp = MIN(tmp, SMB_BUFFER_SIZE_MAX);
1382
1383 #if defined(WITH_SMB1SERVER)
1384         xconn->smb1.negprot.max_recv = tmp;
1385
1386         xconn->smb1.sessions.done_sesssetup = false;
1387         xconn->smb1.sessions.max_send = SMB_BUFFER_SIZE_MAX;
1388 #endif
1389
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;
1399         }
1400         tevent_fd_set_auto_close(xconn->transport.fde);
1401
1402         /* for now we only have one connection */
1403         DLIST_ADD_END(client->connections, xconn);
1404         talloc_steal(client, xconn);
1405
1406         *_xconn = xconn;
1407         TALLOC_FREE(frame);
1408         return NT_STATUS_OK;
1409 }
1410
1411 static bool uid_in_use(struct auth_session_info *session_info,
1412                        uid_t uid)
1413 {
1414         if (session_info->unix_token->uid == uid) {
1415                 return true;
1416         }
1417         return false;
1418 }
1419
1420 static bool gid_in_use(struct auth_session_info *session_info,
1421                        gid_t gid)
1422 {
1423         uint32_t i;
1424         struct security_unix_token *utok = NULL;
1425
1426         utok = session_info->unix_token;
1427         if (utok->gid == gid) {
1428                 return true;
1429         }
1430
1431         for(i = 0; i < utok->ngroups; i++) {
1432                 if (utok->groups[i] == gid) {
1433                         return true;
1434                 }
1435         }
1436         return false;
1437 }
1438
1439 static bool sid_in_use(struct auth_session_info *session_info,
1440                        const struct dom_sid *psid)
1441 {
1442         struct security_token *tok = NULL;
1443
1444         tok = session_info->security_token;
1445         if (tok == NULL) {
1446                 /*
1447                  * Not sure session_info->security_token can
1448                  * ever be NULL. This check might be not
1449                  * necessary.
1450                  */
1451                 return false;
1452         }
1453         if (security_token_has_sid(tok, psid)) {
1454                 return true;
1455         }
1456         return false;
1457 }
1458
1459 struct id_in_use_state {
1460         const struct id_cache_ref *id;
1461         bool match;
1462 };
1463
1464 static int id_in_use_cb(struct smbXsrv_session *session,
1465                         void *private_data)
1466 {
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;
1471
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;
1485         }
1486         if (state->match) {
1487                 return -1;
1488         }
1489         return 0;
1490 }
1491
1492 static bool id_in_use(struct smbd_server_connection *sconn,
1493                       const struct id_cache_ref *id)
1494 {
1495         struct id_in_use_state state;
1496         NTSTATUS status;
1497
1498         state = (struct id_in_use_state) {
1499                 .id = id,
1500                 .match = false,
1501         };
1502
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;
1508         }
1509
1510         return state.match;
1511 }
1512
1513 /****************************************************************************
1514  Check if services need reloading.
1515 ****************************************************************************/
1516
1517 static void check_reload(struct smbd_server_connection *sconn, time_t t)
1518 {
1519
1520         if (last_smb_conf_reload_time == 0) {
1521                 last_smb_conf_reload_time = t;
1522         }
1523
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;
1527         }
1528 }
1529
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)
1533 {
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;
1538
1539         DBG_DEBUG("Got kill request for client IP %s\n", ip);
1540
1541         client_ip = tsocket_address_inet_addr_string(sconn->remote_address,
1542                                                      talloc_tos());
1543         if (client_ip == NULL) {
1544                 return;
1545         }
1546
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");
1551         }
1552
1553         TALLOC_FREE(client_ip);
1554 }
1555
1556 /*
1557  * Do the recurring check if we're idle
1558  */
1559 static bool deadtime_fn(const struct timeval *now, void *private_data)
1560 {
1561         struct smbd_server_connection *sconn =
1562                 (struct smbd_server_connection *)private_data;
1563
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;
1571         }
1572
1573         return True;
1574 }
1575
1576 /*
1577  * Do the recurring log file and smb.conf reload checks.
1578  */
1579
1580 static bool housekeeping_fn(const struct timeval *now, void *private_data)
1581 {
1582         struct smbd_server_connection *sconn = talloc_get_type_abort(
1583                 private_data, struct smbd_server_connection);
1584
1585         DEBUG(5, ("housekeeping\n"));
1586
1587         change_to_root_user();
1588
1589         /* check if we need to reload services */
1590         check_reload(sconn, time_mono(NULL));
1591
1592         /*
1593          * Force a log file check.
1594          */
1595         force_check_log_size();
1596         check_log_size();
1597         return true;
1598 }
1599
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)
1606 {
1607         exit_server_cleanly("termination signal");
1608 }
1609
1610 static void smbd_setup_sig_term_handler(struct smbd_server_connection *sconn)
1611 {
1612         struct tevent_signal *se;
1613
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");
1621         }
1622 }
1623
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)
1630 {
1631         struct smbd_server_connection *sconn =
1632                 talloc_get_type_abort(private_data,
1633                 struct smbd_server_connection);
1634
1635         change_to_root_user();
1636         DEBUG(1,("Reloading services after SIGHUP\n"));
1637         reload_services(sconn, conn_snum_used, false);
1638 }
1639
1640 static void smbd_setup_sig_hup_handler(struct smbd_server_connection *sconn)
1641 {
1642         struct tevent_signal *se;
1643
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");
1651         }
1652 }
1653
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)
1659 {
1660         struct smbd_server_connection *sconn =
1661                 talloc_get_type_abort(private_data,
1662                 struct smbd_server_connection);
1663
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);
1668 }
1669
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)
1675 {
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);
1682
1683         if (!id_cache_ref_parse(msg, &id)) {
1684                 DEBUG(0, ("Invalid ?ID: %s\n", msg));
1685                 return;
1686         }
1687
1688         if (id_in_use(sconn, &id)) {
1689                 exit_server_cleanly(msg);
1690         }
1691         id_cache_delete_from_cache(&id);
1692 }
1693
1694 struct smbd_tevent_trace_state {
1695         struct tevent_context *ev;
1696         TALLOC_CTX *frame;
1697         SMBPROFILE_BASIC_ASYNC_STATE(profile_idle);
1698 };
1699
1700 static inline void smbd_tevent_trace_callback_before_loop_once(
1701         struct smbd_tevent_trace_state *state)
1702 {
1703         talloc_free(state->frame);
1704         state->frame = talloc_stackframe_pool(8192);
1705 }
1706
1707 static inline void smbd_tevent_trace_callback_after_loop_once(
1708         struct smbd_tevent_trace_state *state)
1709 {
1710         TALLOC_FREE(state->frame);
1711 }
1712
1713 static void smbd_tevent_trace_callback(enum tevent_trace_point point,
1714                                        void *private_data)
1715 {
1716         struct smbd_tevent_trace_state *state =
1717                 (struct smbd_tevent_trace_state *)private_data;
1718
1719         switch (point) {
1720         case TEVENT_TRACE_BEFORE_WAIT:
1721                 break;
1722         case TEVENT_TRACE_AFTER_WAIT:
1723                 break;
1724         case TEVENT_TRACE_BEFORE_LOOP_ONCE:
1725                 smbd_tevent_trace_callback_before_loop_once(state);
1726                 break;
1727         case TEVENT_TRACE_AFTER_LOOP_ONCE:
1728                 smbd_tevent_trace_callback_after_loop_once(state);
1729                 break;
1730         }
1731
1732         errno = 0;
1733 }
1734
1735 static void smbd_tevent_trace_callback_profile(enum tevent_trace_point point,
1736                                                void *private_data)
1737 {
1738         struct smbd_tevent_trace_state *state =
1739                 (struct smbd_tevent_trace_state *)private_data;
1740
1741         switch (point) {
1742         case TEVENT_TRACE_BEFORE_WAIT:
1743                 if (!smbprofile_dump_pending()) {
1744                         /*
1745                          * If there's no dump pending
1746                          * we don't want to schedule a new 1 sec timer.
1747                          *
1748                          * Instead we want to sleep as long as nothing happens.
1749                          */
1750                         smbprofile_dump_setup(NULL);
1751                 }
1752                 SMBPROFILE_BASIC_ASYNC_START(idle, profile_p, state->profile_idle);
1753                 break;
1754         case TEVENT_TRACE_AFTER_WAIT:
1755                 SMBPROFILE_BASIC_ASYNC_END(state->profile_idle);
1756                 if (!smbprofile_dump_pending()) {
1757                         /*
1758                          * We need to flush our state after sleeping
1759                          * (hopefully a long time).
1760                          */
1761                         smbprofile_dump();
1762                         /*
1763                          * future profiling events should trigger timers
1764                          * on our main event context.
1765                          */
1766                         smbprofile_dump_setup(state->ev);
1767                 }
1768                 break;
1769         case TEVENT_TRACE_BEFORE_LOOP_ONCE:
1770                 smbd_tevent_trace_callback_before_loop_once(state);
1771                 break;
1772         case TEVENT_TRACE_AFTER_LOOP_ONCE:
1773                 smbd_tevent_trace_callback_after_loop_once(state);
1774                 break;
1775         }
1776
1777         errno = 0;
1778 }
1779
1780 /****************************************************************************
1781  Process commands from the client
1782 ****************************************************************************/
1783
1784 void smbd_process(struct tevent_context *ev_ctx,
1785                   struct messaging_context *msg_ctx,
1786                   int sock_fd,
1787                   bool interactive)
1788 {
1789         struct smbd_tevent_trace_state trace_state = {
1790                 .ev = ev_ctx,
1791                 .frame = talloc_stackframe(),
1792         };
1793         const struct loadparm_substitution *lp_sub =
1794                 loadparm_s3_global_substitution();
1795         struct smbXsrv_client *client = NULL;
1796         struct smbd_server_connection *sconn = NULL;
1797         struct smbXsrv_connection *xconn = NULL;
1798         const char *locaddr = NULL;
1799         const char *remaddr = NULL;
1800         int ret;
1801         NTSTATUS status;
1802         struct timeval tv = timeval_current();
1803         NTTIME now = timeval_to_nttime(&tv);
1804         char *chroot_dir = NULL;
1805         int rc;
1806
1807         status = smbXsrv_client_create(ev_ctx, ev_ctx, msg_ctx, now, &client);
1808         if (!NT_STATUS_IS_OK(status)) {
1809                 DBG_ERR("smbXsrv_client_create(): %s\n", nt_errstr(status));
1810                 exit_server_cleanly("talloc_zero(struct smbXsrv_client).\n");
1811         }
1812
1813         /*
1814          * TODO: remove this...:-)
1815          */
1816         global_smbXsrv_client = client;
1817
1818         sconn = talloc_zero(client, struct smbd_server_connection);
1819         if (sconn == NULL) {
1820                 exit_server("failed to create smbd_server_connection");
1821         }
1822
1823         client->sconn = sconn;
1824         sconn->client = client;
1825
1826         sconn->ev_ctx = ev_ctx;
1827         sconn->msg_ctx = msg_ctx;
1828
1829         ret = pthreadpool_tevent_init(sconn, lp_aio_max_threads(),
1830                                       &sconn->pool);
1831         if (ret != 0) {
1832                 exit_server("pthreadpool_tevent_init() failed.");
1833         }
1834
1835 #if defined(WITH_SMB1SERVER)
1836         if (lp_server_max_protocol() >= PROTOCOL_SMB2_02) {
1837 #endif
1838                 /*
1839                  * We're not making the decision here,
1840                  * we're just allowing the client
1841                  * to decide between SMB1 and SMB2
1842                  * with the first negprot
1843                  * packet.
1844                  */
1845                 sconn->using_smb2 = true;
1846 #if defined(WITH_SMB1SERVER)
1847         }
1848 #endif
1849
1850         if (!interactive) {
1851                 smbd_setup_sig_term_handler(sconn);
1852                 smbd_setup_sig_hup_handler(sconn);
1853         }
1854
1855         status = smbd_add_connection(client, sock_fd, now, &xconn);
1856         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
1857                 /*
1858                  * send a negative session response "not listening on calling
1859                  * name"
1860                  */
1861                 unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
1862                 (void)smb1_srv_send(xconn,(char *)buf, false,
1863                                     0, false, NULL);
1864                 exit_server_cleanly("connection denied");
1865         } else if (!NT_STATUS_IS_OK(status)) {
1866                 exit_server_cleanly(nt_errstr(status));
1867         }
1868
1869         sconn->local_address =
1870                 tsocket_address_copy(xconn->local_address, sconn);
1871         if (sconn->local_address == NULL) {
1872                 exit_server_cleanly("tsocket_address_copy() failed");
1873         }
1874         sconn->remote_address =
1875                 tsocket_address_copy(xconn->remote_address, sconn);
1876         if (sconn->remote_address == NULL) {
1877                 exit_server_cleanly("tsocket_address_copy() failed");
1878         }
1879         sconn->remote_hostname =
1880                 talloc_strdup(sconn, xconn->remote_hostname);
1881         if (sconn->remote_hostname == NULL) {
1882                 exit_server_cleanly("tsocket_strdup() failed");
1883         }
1884
1885         client->global->local_address =
1886                 tsocket_address_string(sconn->local_address,
1887                                        client->global);
1888         if (client->global->local_address == NULL) {
1889                 exit_server_cleanly("tsocket_address_string() failed");
1890         }
1891         client->global->remote_address =
1892                 tsocket_address_string(sconn->remote_address,
1893                                        client->global);
1894         if (client->global->remote_address == NULL) {
1895                 exit_server_cleanly("tsocket_address_string() failed");
1896         }
1897         client->global->remote_name =
1898                 talloc_strdup(client->global, sconn->remote_hostname);
1899         if (client->global->remote_name == NULL) {
1900                 exit_server_cleanly("tsocket_strdup() failed");
1901         }
1902
1903         if (tsocket_address_is_inet(sconn->local_address, "ip")) {
1904                 locaddr = tsocket_address_inet_addr_string(
1905                                 sconn->local_address,
1906                                 talloc_tos());
1907                 if (locaddr == NULL) {
1908                         DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
1909                                  __location__, strerror(errno)));
1910                         exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
1911                 }
1912         } else {
1913                 locaddr = "0.0.0.0";
1914         }
1915
1916         if (tsocket_address_is_inet(sconn->remote_address, "ip")) {
1917                 remaddr = tsocket_address_inet_addr_string(
1918                                 sconn->remote_address,
1919                                 talloc_tos());
1920                 if (remaddr == NULL) {
1921                         DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
1922                                  __location__, strerror(errno)));
1923                         exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
1924                 }
1925         } else {
1926                 remaddr = "0.0.0.0";
1927         }
1928
1929         /* this is needed so that we get decent entries
1930            in smbstatus for port 445 connects */
1931         set_remote_machine_name(remaddr, false);
1932         reload_services(sconn, conn_snum_used, true);
1933         sub_set_socket_ids(remaddr,
1934                            sconn->remote_hostname,
1935                            locaddr);
1936
1937         if (lp_preload_modules()) {
1938                 smb_load_all_modules_absoute_path(lp_preload_modules());
1939         }
1940
1941         smb_perfcount_init();
1942
1943         if (!init_account_policy()) {
1944                 exit_server("Could not open account policy tdb.\n");
1945         }
1946
1947         chroot_dir = lp_root_directory(talloc_tos(), lp_sub);
1948         if (chroot_dir[0] != '\0') {
1949                 rc = chdir(chroot_dir);
1950                 if (rc != 0) {
1951                         DBG_ERR("Failed to chdir to %s\n", chroot_dir);
1952                         exit_server("Failed to chdir()");
1953                 }
1954
1955                 rc = chroot(chroot_dir);
1956                 if (rc != 0) {
1957                         DBG_ERR("Failed to change root to %s\n", chroot_dir);
1958                         exit_server("Failed to chroot()");
1959                 }
1960                 DBG_WARNING("Changed root to %s\n", chroot_dir);
1961
1962                 TALLOC_FREE(chroot_dir);
1963         }
1964
1965         if (!file_init(sconn)) {
1966                 exit_server("file_init() failed");
1967         }
1968
1969         /* Setup oplocks */
1970         if (!init_oplocks(sconn))
1971                 exit_server("Failed to init oplocks");
1972
1973         /* register our message handlers */
1974         messaging_register(sconn->msg_ctx, sconn,
1975                            MSG_SMB_FORCE_TDIS, msg_force_tdis);
1976         messaging_register(
1977                 sconn->msg_ctx,
1978                 sconn,
1979                 MSG_SMB_FORCE_TDIS_DENIED,
1980                 msg_force_tdis_denied);
1981         messaging_register(sconn->msg_ctx, sconn,
1982                            MSG_SMB_CLOSE_FILE, msg_close_file);
1983         messaging_register(sconn->msg_ctx, sconn,
1984                            MSG_SMB_FILE_RENAME, msg_file_was_renamed);
1985
1986         id_cache_register_msgs(sconn->msg_ctx);
1987         messaging_deregister(sconn->msg_ctx, ID_CACHE_KILL, NULL);
1988         messaging_register(sconn->msg_ctx, sconn,
1989                            ID_CACHE_KILL, smbd_id_cache_kill);
1990
1991         messaging_deregister(sconn->msg_ctx,
1992                              MSG_SMB_CONF_UPDATED, sconn->ev_ctx);
1993         messaging_register(sconn->msg_ctx, sconn,
1994                            MSG_SMB_CONF_UPDATED, smbd_conf_updated);
1995
1996         messaging_deregister(sconn->msg_ctx, MSG_SMB_KILL_CLIENT_IP,
1997                              NULL);
1998         messaging_register(sconn->msg_ctx, sconn,
1999                            MSG_SMB_KILL_CLIENT_IP,
2000                            msg_kill_client_ip);
2001
2002         messaging_deregister(sconn->msg_ctx, MSG_SMB_TELL_NUM_CHILDREN, NULL);
2003
2004         /*
2005          * Use the default MSG_DEBUG handler to avoid rebroadcasting
2006          * MSGs to all child processes
2007          */
2008         messaging_deregister(sconn->msg_ctx,
2009                              MSG_DEBUG, NULL);
2010         messaging_register(sconn->msg_ctx, NULL,
2011                            MSG_DEBUG, debug_message);
2012
2013 #if defined(WITH_SMB1SERVER)
2014         if ((lp_keepalive() != 0)
2015             && !(event_add_idle(ev_ctx, NULL,
2016                                 timeval_set(lp_keepalive(), 0),
2017                                 "keepalive", keepalive_fn,
2018                                 sconn))) {
2019                 DEBUG(0, ("Could not add keepalive event\n"));
2020                 exit(1);
2021         }
2022 #endif
2023
2024         if (!(event_add_idle(ev_ctx, NULL,
2025                              timeval_set(IDLE_CLOSED_TIMEOUT, 0),
2026                              "deadtime", deadtime_fn, sconn))) {
2027                 DEBUG(0, ("Could not add deadtime event\n"));
2028                 exit(1);
2029         }
2030
2031         if (!(event_add_idle(ev_ctx, NULL,
2032                              timeval_set(SMBD_HOUSEKEEPING_INTERVAL, 0),
2033                              "housekeeping", housekeeping_fn, sconn))) {
2034                 DEBUG(0, ("Could not add housekeeping event\n"));
2035                 exit(1);
2036         }
2037
2038         smbprofile_dump_setup(ev_ctx);
2039
2040         if (!init_dptrs(sconn)) {
2041                 exit_server("init_dptrs() failed");
2042         }
2043
2044         TALLOC_FREE(trace_state.frame);
2045
2046         if (smbprofile_active()) {
2047                 tevent_set_trace_callback(ev_ctx,
2048                                           smbd_tevent_trace_callback_profile,
2049                                           &trace_state);
2050         } else {
2051                 tevent_set_trace_callback(ev_ctx,
2052                                           smbd_tevent_trace_callback,
2053                                           &trace_state);
2054         }
2055
2056         ret = tevent_loop_wait(ev_ctx);
2057         if (ret != 0) {
2058                 DEBUG(1, ("tevent_loop_wait failed: %d, %s,"
2059                           " exiting\n", ret, strerror(errno)));
2060         }
2061
2062         TALLOC_FREE(trace_state.frame);
2063
2064         exit_server_cleanly(NULL);
2065 }