Plumb SMB2 stubs into all the places we defer SMB1 operations.
[ira/wip.git] / source3 / smbd / 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 "smbd/globals.h"
23 #include "../librpc/gen_ndr/srv_dfs.h"
24 #include "../librpc/gen_ndr/srv_dssetup.h"
25 #include "../librpc/gen_ndr/srv_echo.h"
26 #include "../librpc/gen_ndr/srv_eventlog.h"
27 #include "../librpc/gen_ndr/srv_initshutdown.h"
28 #include "../librpc/gen_ndr/srv_lsa.h"
29 #include "../librpc/gen_ndr/srv_netlogon.h"
30 #include "../librpc/gen_ndr/srv_ntsvcs.h"
31 #include "../librpc/gen_ndr/srv_samr.h"
32 #include "../librpc/gen_ndr/srv_spoolss.h"
33 #include "../librpc/gen_ndr/srv_srvsvc.h"
34 #include "../librpc/gen_ndr/srv_svcctl.h"
35 #include "../librpc/gen_ndr/srv_winreg.h"
36 #include "../librpc/gen_ndr/srv_wkssvc.h"
37
38 extern bool global_machine_password_needs_changing;
39
40 static void construct_reply_common(struct smb_request *req, const char *inbuf,
41                                    char *outbuf);
42 static struct pending_message_list *get_deferred_open_message_smb(uint16_t mid);
43
44 static bool smbd_lock_socket_internal(struct smbd_server_connection *sconn)
45 {
46         bool ok;
47
48         if (smbd_server_conn->smb1.echo_handler.socket_lock_fd == -1) {
49                 return true;
50         }
51
52         smbd_server_conn->smb1.echo_handler.ref_count++;
53
54         if (smbd_server_conn->smb1.echo_handler.ref_count > 1) {
55                 return true;
56         }
57
58         DEBUG(10,("pid[%d] wait for socket lock\n", (int)sys_getpid()));
59
60         ok = fcntl_lock(smbd_server_conn->smb1.echo_handler.socket_lock_fd,
61                         SMB_F_SETLKW, 0, 0, F_WRLCK);
62         if (!ok) {
63                 return false;
64         }
65
66         DEBUG(10,("pid[%d] got for socket lock\n", (int)sys_getpid()));
67
68         return true;
69 }
70
71 void smbd_lock_socket(struct smbd_server_connection *sconn)
72 {
73         if (!smbd_lock_socket_internal(sconn)) {
74                 exit_server_cleanly("failed to lock socket");
75         }
76 }
77
78 static bool smbd_unlock_socket_internal(struct smbd_server_connection *sconn)
79 {
80         bool ok;
81
82         if (smbd_server_conn->smb1.echo_handler.socket_lock_fd == -1) {
83                 return true;
84         }
85
86         smbd_server_conn->smb1.echo_handler.ref_count--;
87
88         if (smbd_server_conn->smb1.echo_handler.ref_count > 0) {
89                 return true;
90         }
91
92         ok = fcntl_lock(smbd_server_conn->smb1.echo_handler.socket_lock_fd,
93                         SMB_F_SETLKW, 0, 0, F_UNLCK);
94         if (!ok) {
95                 return false;
96         }
97
98         DEBUG(10,("pid[%d] unlocked socket\n", (int)sys_getpid()));
99
100         return true;
101 }
102
103 void smbd_unlock_socket(struct smbd_server_connection *sconn)
104 {
105         if (!smbd_unlock_socket_internal(sconn)) {
106                 exit_server_cleanly("failed to unlock socket");
107         }
108 }
109
110 /* Accessor function for smb_read_error for smbd functions. */
111
112 /****************************************************************************
113  Send an smb to a fd.
114 ****************************************************************************/
115
116 bool srv_send_smb(int fd, char *buffer,
117                   bool do_signing, uint32_t seqnum,
118                   bool do_encrypt,
119                   struct smb_perfcount_data *pcd)
120 {
121         size_t len = 0;
122         size_t nwritten=0;
123         ssize_t ret;
124         char *buf_out = buffer;
125
126         smbd_lock_socket(smbd_server_conn);
127
128         if (do_signing) {
129                 /* Sign the outgoing packet if required. */
130                 srv_calculate_sign_mac(smbd_server_conn, buf_out, seqnum);
131         }
132
133         if (do_encrypt) {
134                 NTSTATUS status = srv_encrypt_buffer(buffer, &buf_out);
135                 if (!NT_STATUS_IS_OK(status)) {
136                         DEBUG(0, ("send_smb: SMB encryption failed "
137                                 "on outgoing packet! Error %s\n",
138                                 nt_errstr(status) ));
139                         goto out;
140                 }
141         }
142
143         len = smb_len(buf_out) + 4;
144
145         ret = write_data(fd,buf_out+nwritten,len - nwritten);
146         if (ret <= 0) {
147                 DEBUG(0,("pid[%d] Error writing %d bytes to client. %d. (%s)\n",
148                         (int)sys_getpid(), (int)len,(int)ret, strerror(errno) ));
149                 srv_free_enc_buffer(buf_out);
150                 goto out;
151         }
152
153         SMB_PERFCOUNT_SET_MSGLEN_OUT(pcd, len);
154         srv_free_enc_buffer(buf_out);
155 out:
156         SMB_PERFCOUNT_END(pcd);
157
158         smbd_unlock_socket(smbd_server_conn);
159         return true;
160 }
161
162 /*******************************************************************
163  Setup the word count and byte count for a smb message.
164 ********************************************************************/
165
166 int srv_set_message(char *buf,
167                         int num_words,
168                         int num_bytes,
169                         bool zero)
170 {
171         if (zero && (num_words || num_bytes)) {
172                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
173         }
174         SCVAL(buf,smb_wct,num_words);
175         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
176         smb_setlen(buf,(smb_size + num_words*2 + num_bytes - 4));
177         return (smb_size + num_words*2 + num_bytes);
178 }
179
180 static bool valid_smb_header(const uint8_t *inbuf)
181 {
182         if (is_encrypted_packet(inbuf)) {
183                 return true;
184         }
185         /*
186          * This used to be (strncmp(smb_base(inbuf),"\377SMB",4) == 0)
187          * but it just looks weird to call strncmp for this one.
188          */
189         return (IVAL(smb_base(inbuf), 0) == 0x424D53FF);
190 }
191
192 /* Socket functions for smbd packet processing. */
193
194 static bool valid_packet_size(size_t len)
195 {
196         /*
197          * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
198          * of header. Don't print the error if this fits.... JRA.
199          */
200
201         if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
202                 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
203                                         (unsigned long)len));
204                 return false;
205         }
206         return true;
207 }
208
209 static NTSTATUS read_packet_remainder(int fd, char *buffer,
210                                       unsigned int timeout, ssize_t len)
211 {
212         if (len <= 0) {
213                 return NT_STATUS_OK;
214         }
215
216         return read_fd_with_timeout(fd, buffer, len, len, timeout, NULL);
217 }
218
219 /****************************************************************************
220  Attempt a zerocopy writeX read. We know here that len > smb_size-4
221 ****************************************************************************/
222
223 /*
224  * Unfortunately, earlier versions of smbclient/libsmbclient
225  * don't send this "standard" writeX header. I've fixed this
226  * for 3.2 but we'll use the old method with earlier versions.
227  * Windows and CIFSFS at least use this standard size. Not
228  * sure about MacOSX.
229  */
230
231 #define STANDARD_WRITE_AND_X_HEADER_SIZE (smb_size - 4 + /* basic header */ \
232                                 (2*14) + /* word count (including bcc) */ \
233                                 1 /* pad byte */)
234
235 static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
236                                                     const char lenbuf[4],
237                                                     int fd, char **buffer,
238                                                     unsigned int timeout,
239                                                     size_t *p_unread,
240                                                     size_t *len_ret)
241 {
242         /* Size of a WRITEX call (+4 byte len). */
243         char writeX_header[4 + STANDARD_WRITE_AND_X_HEADER_SIZE];
244         ssize_t len = smb_len_large(lenbuf); /* Could be a UNIX large writeX. */
245         ssize_t toread;
246         NTSTATUS status;
247
248         memcpy(writeX_header, lenbuf, 4);
249
250         status = read_fd_with_timeout(
251                 fd, writeX_header + 4,
252                 STANDARD_WRITE_AND_X_HEADER_SIZE,
253                 STANDARD_WRITE_AND_X_HEADER_SIZE,
254                 timeout, NULL);
255
256         if (!NT_STATUS_IS_OK(status)) {
257                 return status;
258         }
259
260         /*
261          * Ok - now try and see if this is a possible
262          * valid writeX call.
263          */
264
265         if (is_valid_writeX_buffer((uint8_t *)writeX_header)) {
266                 /*
267                  * If the data offset is beyond what
268                  * we've read, drain the extra bytes.
269                  */
270                 uint16_t doff = SVAL(writeX_header,smb_vwv11);
271                 ssize_t newlen;
272
273                 if (doff > STANDARD_WRITE_AND_X_HEADER_SIZE) {
274                         size_t drain = doff - STANDARD_WRITE_AND_X_HEADER_SIZE;
275                         if (drain_socket(smbd_server_fd(), drain) != drain) {
276                                 smb_panic("receive_smb_raw_talloc_partial_read:"
277                                         " failed to drain pending bytes");
278                         }
279                 } else {
280                         doff = STANDARD_WRITE_AND_X_HEADER_SIZE;
281                 }
282
283                 /* Spoof down the length and null out the bcc. */
284                 set_message_bcc(writeX_header, 0);
285                 newlen = smb_len(writeX_header);
286
287                 /* Copy the header we've written. */
288
289                 *buffer = (char *)TALLOC_MEMDUP(mem_ctx,
290                                 writeX_header,
291                                 sizeof(writeX_header));
292
293                 if (*buffer == NULL) {
294                         DEBUG(0, ("Could not allocate inbuf of length %d\n",
295                                   (int)sizeof(writeX_header)));
296                         return NT_STATUS_NO_MEMORY;
297                 }
298
299                 /* Work out the remaining bytes. */
300                 *p_unread = len - STANDARD_WRITE_AND_X_HEADER_SIZE;
301                 *len_ret = newlen + 4;
302                 return NT_STATUS_OK;
303         }
304
305         if (!valid_packet_size(len)) {
306                 return NT_STATUS_INVALID_PARAMETER;
307         }
308
309         /*
310          * Not a valid writeX call. Just do the standard
311          * talloc and return.
312          */
313
314         *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
315
316         if (*buffer == NULL) {
317                 DEBUG(0, ("Could not allocate inbuf of length %d\n",
318                           (int)len+4));
319                 return NT_STATUS_NO_MEMORY;
320         }
321
322         /* Copy in what we already read. */
323         memcpy(*buffer,
324                 writeX_header,
325                 4 + STANDARD_WRITE_AND_X_HEADER_SIZE);
326         toread = len - STANDARD_WRITE_AND_X_HEADER_SIZE;
327
328         if(toread > 0) {
329                 status = read_packet_remainder(
330                         fd, (*buffer) + 4 + STANDARD_WRITE_AND_X_HEADER_SIZE,
331                         timeout, toread);
332
333                 if (!NT_STATUS_IS_OK(status)) {
334                         DEBUG(10, ("receive_smb_raw_talloc_partial_read: %s\n",
335                                    nt_errstr(status)));
336                         return status;
337                 }
338         }
339
340         *len_ret = len + 4;
341         return NT_STATUS_OK;
342 }
343
344 static NTSTATUS receive_smb_raw_talloc(TALLOC_CTX *mem_ctx, int fd,
345                                        char **buffer, unsigned int timeout,
346                                        size_t *p_unread, size_t *plen)
347 {
348         char lenbuf[4];
349         size_t len;
350         int min_recv_size = lp_min_receive_file_size();
351         NTSTATUS status;
352
353         *p_unread = 0;
354
355         status = read_smb_length_return_keepalive(fd, lenbuf, timeout, &len);
356         if (!NT_STATUS_IS_OK(status)) {
357                 DEBUG(10, ("receive_smb_raw: %s\n", nt_errstr(status)));
358                 return status;
359         }
360
361         if (CVAL(lenbuf,0) == 0 && min_recv_size &&
362             (smb_len_large(lenbuf) > /* Could be a UNIX large writeX. */
363                 (min_recv_size + STANDARD_WRITE_AND_X_HEADER_SIZE)) &&
364             !srv_is_signing_active(smbd_server_conn) &&
365             smbd_server_conn->smb1.echo_handler.trusted_fde == NULL) {
366
367                 return receive_smb_raw_talloc_partial_read(
368                         mem_ctx, lenbuf, fd, buffer, timeout, p_unread, plen);
369         }
370
371         if (!valid_packet_size(len)) {
372                 return NT_STATUS_INVALID_PARAMETER;
373         }
374
375         /*
376          * The +4 here can't wrap, we've checked the length above already.
377          */
378
379         *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
380
381         if (*buffer == NULL) {
382                 DEBUG(0, ("Could not allocate inbuf of length %d\n",
383                           (int)len+4));
384                 return NT_STATUS_NO_MEMORY;
385         }
386
387         memcpy(*buffer, lenbuf, sizeof(lenbuf));
388
389         status = read_packet_remainder(fd, (*buffer)+4, timeout, len);
390         if (!NT_STATUS_IS_OK(status)) {
391                 return status;
392         }
393
394         *plen = len + 4;
395         return NT_STATUS_OK;
396 }
397
398 static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd,
399                                    char **buffer, unsigned int timeout,
400                                    size_t *p_unread, bool *p_encrypted,
401                                    size_t *p_len,
402                                    uint32_t *seqnum,
403                                    bool trusted_channel)
404 {
405         size_t len = 0;
406         NTSTATUS status;
407
408         *p_encrypted = false;
409
410         status = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout,
411                                         p_unread, &len);
412         if (!NT_STATUS_IS_OK(status)) {
413                 return status;
414         }
415
416         if (is_encrypted_packet((uint8_t *)*buffer)) {
417                 status = srv_decrypt_buffer(*buffer);
418                 if (!NT_STATUS_IS_OK(status)) {
419                         DEBUG(0, ("receive_smb_talloc: SMB decryption failed on "
420                                 "incoming packet! Error %s\n",
421                                 nt_errstr(status) ));
422                         return status;
423                 }
424                 *p_encrypted = true;
425         }
426
427         /* Check the incoming SMB signature. */
428         if (!srv_check_sign_mac(smbd_server_conn, *buffer, seqnum, trusted_channel)) {
429                 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
430                           "incoming packet!\n"));
431                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
432         }
433
434         *p_len = len;
435         return NT_STATUS_OK;
436 }
437
438 /*
439  * Initialize a struct smb_request from an inbuf
440  */
441
442 static bool init_smb_request(struct smb_request *req, const uint8 *inbuf,
443                              size_t unread_bytes, bool encrypted,
444                              uint32_t seqnum)
445 {
446         struct smbd_server_connection *sconn = smbd_server_conn;
447         size_t req_size = smb_len(inbuf) + 4;
448         /* Ensure we have at least smb_size bytes. */
449         if (req_size < smb_size) {
450                 DEBUG(0,("init_smb_request: invalid request size %u\n",
451                         (unsigned int)req_size ));
452                 return false;
453         }
454         req->cmd    = CVAL(inbuf, smb_com);
455         req->flags2 = SVAL(inbuf, smb_flg2);
456         req->smbpid = SVAL(inbuf, smb_pid);
457         req->mid    = SVAL(inbuf, smb_mid);
458         req->seqnum = seqnum;
459         req->vuid   = SVAL(inbuf, smb_uid);
460         req->tid    = SVAL(inbuf, smb_tid);
461         req->wct    = CVAL(inbuf, smb_wct);
462         req->vwv    = (uint16_t *)(inbuf+smb_vwv);
463         req->buflen = smb_buflen(inbuf);
464         req->buf    = (const uint8_t *)smb_buf(inbuf);
465         req->unread_bytes = unread_bytes;
466         req->encrypted = encrypted;
467         req->conn = conn_find(sconn,req->tid);
468         req->chain_fsp = NULL;
469         req->chain_outbuf = NULL;
470         req->done = false;
471         req->smb2req = NULL;
472         smb_init_perfcount_data(&req->pcd);
473
474         /* Ensure we have at least wct words and 2 bytes of bcc. */
475         if (smb_size + req->wct*2 > req_size) {
476                 DEBUG(0,("init_smb_request: invalid wct number %u (size %u)\n",
477                         (unsigned int)req->wct,
478                         (unsigned int)req_size));
479                 return false;
480         }
481         /* Ensure bcc is correct. */
482         if (((uint8 *)smb_buf(inbuf)) + req->buflen > inbuf + req_size) {
483                 DEBUG(0,("init_smb_request: invalid bcc number %u "
484                         "(wct = %u, size %u)\n",
485                         (unsigned int)req->buflen,
486                         (unsigned int)req->wct,
487                         (unsigned int)req_size));
488                 return false;
489         }
490
491         req->outbuf = NULL;
492         return true;
493 }
494
495 static void process_smb(struct smbd_server_connection *conn,
496                         uint8_t *inbuf, size_t nread, size_t unread_bytes,
497                         uint32_t seqnum, bool encrypted,
498                         struct smb_perfcount_data *deferred_pcd);
499
500 static void smbd_deferred_open_timer(struct event_context *ev,
501                                      struct timed_event *te,
502                                      struct timeval _tval,
503                                      void *private_data)
504 {
505         struct pending_message_list *msg = talloc_get_type(private_data,
506                                            struct pending_message_list);
507         TALLOC_CTX *mem_ctx = talloc_tos();
508         uint16_t mid = SVAL(msg->buf.data,smb_mid);
509         uint8_t *inbuf;
510
511         inbuf = (uint8_t *)talloc_memdup(mem_ctx, msg->buf.data,
512                                          msg->buf.length);
513         if (inbuf == NULL) {
514                 exit_server("smbd_deferred_open_timer: talloc failed\n");
515                 return;
516         }
517
518         /* We leave this message on the queue so the open code can
519            know this is a retry. */
520         DEBUG(5,("smbd_deferred_open_timer: trigger mid %u.\n",
521                 (unsigned int)mid ));
522
523         /* Mark the message as processed so this is not
524          * re-processed in error. */
525         msg->processed = true;
526
527         process_smb(smbd_server_conn, inbuf,
528                     msg->buf.length, 0,
529                     msg->seqnum, msg->encrypted, &msg->pcd);
530
531         /* If it's still there and was processed, remove it. */
532         msg = get_deferred_open_message_smb(mid);
533         if (msg && msg->processed) {
534                 remove_deferred_open_message_smb(mid);
535         }
536 }
537
538 /****************************************************************************
539  Function to push a message onto the tail of a linked list of smb messages ready
540  for processing.
541 ****************************************************************************/
542
543 static bool push_queued_message(struct smb_request *req,
544                                 struct timeval request_time,
545                                 struct timeval end_time,
546                                 char *private_data, size_t private_len)
547 {
548         int msg_len = smb_len(req->inbuf) + 4;
549         struct pending_message_list *msg;
550
551         msg = TALLOC_ZERO_P(NULL, struct pending_message_list);
552
553         if(msg == NULL) {
554                 DEBUG(0,("push_message: malloc fail (1)\n"));
555                 return False;
556         }
557
558         msg->buf = data_blob_talloc(msg, req->inbuf, msg_len);
559         if(msg->buf.data == NULL) {
560                 DEBUG(0,("push_message: malloc fail (2)\n"));
561                 TALLOC_FREE(msg);
562                 return False;
563         }
564
565         msg->request_time = request_time;
566         msg->seqnum = req->seqnum;
567         msg->encrypted = req->encrypted;
568         msg->processed = false;
569         SMB_PERFCOUNT_DEFER_OP(&req->pcd, &msg->pcd);
570
571         if (private_data) {
572                 msg->private_data = data_blob_talloc(msg, private_data,
573                                                      private_len);
574                 if (msg->private_data.data == NULL) {
575                         DEBUG(0,("push_message: malloc fail (3)\n"));
576                         TALLOC_FREE(msg);
577                         return False;
578                 }
579         }
580
581         msg->te = event_add_timed(smbd_event_context(),
582                                   msg,
583                                   end_time,
584                                   smbd_deferred_open_timer,
585                                   msg);
586         if (!msg->te) {
587                 DEBUG(0,("push_message: event_add_timed failed\n"));
588                 TALLOC_FREE(msg);
589                 return false;
590         }
591
592         DLIST_ADD_END(deferred_open_queue, msg, struct pending_message_list *);
593
594         DEBUG(10,("push_message: pushed message length %u on "
595                   "deferred_open_queue\n", (unsigned int)msg_len));
596
597         return True;
598 }
599
600 /****************************************************************************
601  Function to delete a sharing violation open message by mid.
602 ****************************************************************************/
603
604 void remove_deferred_open_message_smb(uint16_t mid)
605 {
606         struct pending_message_list *pml;
607
608         if (smbd_server_conn->allow_smb2) {
609                 remove_deferred_open_message_smb2(mid);
610                 return;
611         }
612
613         for (pml = deferred_open_queue; pml; pml = pml->next) {
614                 if (mid == SVAL(pml->buf.data,smb_mid)) {
615                         DEBUG(10,("remove_deferred_open_message_smb: "
616                                   "deleting mid %u len %u\n",
617                                   (unsigned int)mid,
618                                   (unsigned int)pml->buf.length ));
619                         DLIST_REMOVE(deferred_open_queue, pml);
620                         TALLOC_FREE(pml);
621                         return;
622                 }
623         }
624 }
625
626 /****************************************************************************
627  Move a sharing violation open retry message to the front of the list and
628  schedule it for immediate processing.
629 ****************************************************************************/
630
631 void schedule_deferred_open_message_smb(uint16_t mid)
632 {
633         struct pending_message_list *pml;
634         int i = 0;
635
636         if (smbd_server_conn->allow_smb2) {
637                 schedule_deferred_open_message_smb2(mid);
638                 return;
639         }
640
641         for (pml = deferred_open_queue; pml; pml = pml->next) {
642                 uint16 msg_mid = SVAL(pml->buf.data,smb_mid);
643
644                 DEBUG(10,("schedule_deferred_open_message_smb: [%d] msg_mid = %u\n", i++,
645                         (unsigned int)msg_mid ));
646
647                 if (mid == msg_mid) {
648                         struct timed_event *te;
649
650                         if (pml->processed) {
651                                 /* A processed message should not be
652                                  * rescheduled. */
653                                 DEBUG(0,("schedule_deferred_open_message_smb: LOGIC ERROR "
654                                         "message mid %u was already processed\n",
655                                         msg_mid ));
656                                 continue;
657                         }
658
659                         DEBUG(10,("schedule_deferred_open_message_smb: scheduling mid %u\n",
660                                 mid ));
661
662                         te = event_add_timed(smbd_event_context(),
663                                              pml,
664                                              timeval_zero(),
665                                              smbd_deferred_open_timer,
666                                              pml);
667                         if (!te) {
668                                 DEBUG(10,("schedule_deferred_open_message_smb: "
669                                           "event_add_timed() failed, skipping mid %u\n",
670                                           mid ));
671                         }
672
673                         TALLOC_FREE(pml->te);
674                         pml->te = te;
675                         DLIST_PROMOTE(deferred_open_queue, pml);
676                         return;
677                 }
678         }
679
680         DEBUG(10,("schedule_deferred_open_message_smb: failed to find message mid %u\n",
681                 mid ));
682 }
683
684 /****************************************************************************
685  Return true if this mid is on the deferred queue and was not yet processed.
686 ****************************************************************************/
687
688 bool open_was_deferred(uint16_t mid)
689 {
690         struct pending_message_list *pml;
691
692         if (smbd_server_conn->allow_smb2) {
693                 return open_was_deferred_smb2(mid);
694         }
695
696         for (pml = deferred_open_queue; pml; pml = pml->next) {
697                 if (SVAL(pml->buf.data,smb_mid) == mid && !pml->processed) {
698                         return True;
699                 }
700         }
701         return False;
702 }
703
704 /****************************************************************************
705  Return the message queued by this mid.
706 ****************************************************************************/
707
708 static struct pending_message_list *get_deferred_open_message_smb(uint16_t mid)
709 {
710         struct pending_message_list *pml;
711
712         for (pml = deferred_open_queue; pml; pml = pml->next) {
713                 if (SVAL(pml->buf.data,smb_mid) == mid) {
714                         return pml;
715                 }
716         }
717         return NULL;
718 }
719
720 /****************************************************************************
721  Get the state data queued by this mid.
722 ****************************************************************************/
723
724 bool get_deferred_open_message_state(uint16_t mid,
725                                 struct timeval *p_request_time,
726                                 void **pp_state)
727 {
728         struct pending_message_list *pml;
729
730         if (smbd_server_conn->allow_smb2) {
731                 return get_deferred_open_message_state_smb2(mid,
732                                         p_request_time,
733                                         pp_state);
734         }
735
736         pml = get_deferred_open_message_smb(mid);
737         if (!pml) {
738                 return false;
739         }
740         if (p_request_time) {
741                 *p_request_time = pml->request_time;
742         }
743         if (pp_state) {
744                 *pp_state = (void *)pml->private_data.data;
745         }
746         return true;
747 }
748
749 /****************************************************************************
750  Function to push a deferred open smb message onto a linked list of local smb
751  messages ready for processing.
752 ****************************************************************************/
753
754 bool push_deferred_open_message_smb(struct smb_request *req,
755                                struct timeval request_time,
756                                struct timeval timeout,
757                                char *private_data, size_t priv_len)
758 {
759         struct timeval end_time;
760
761         if (req->smb2req) {
762                 return push_deferred_open_message_smb2(req,
763                                                 request_time,
764                                                 timeout,
765                                                 private_data,
766                                                 priv_len);
767         }
768
769         if (req->unread_bytes) {
770                 DEBUG(0,("push_deferred_open_message_smb: logic error ! "
771                         "unread_bytes = %u\n",
772                         (unsigned int)req->unread_bytes ));
773                 smb_panic("push_deferred_open_message_smb: "
774                         "logic error unread_bytes != 0" );
775         }
776
777         end_time = timeval_sum(&request_time, &timeout);
778
779         DEBUG(10,("push_deferred_open_message_smb: pushing message len %u mid %u "
780                   "timeout time [%u.%06u]\n",
781                   (unsigned int) smb_len(req->inbuf)+4, (unsigned int)req->mid,
782                   (unsigned int)end_time.tv_sec,
783                   (unsigned int)end_time.tv_usec));
784
785         return push_queued_message(req, request_time, end_time,
786                                    private_data, priv_len);
787 }
788
789 struct idle_event {
790         struct timed_event *te;
791         struct timeval interval;
792         char *name;
793         bool (*handler)(const struct timeval *now, void *private_data);
794         void *private_data;
795 };
796
797 static void smbd_idle_event_handler(struct event_context *ctx,
798                                     struct timed_event *te,
799                                     struct timeval now,
800                                     void *private_data)
801 {
802         struct idle_event *event =
803                 talloc_get_type_abort(private_data, struct idle_event);
804
805         TALLOC_FREE(event->te);
806
807         DEBUG(10,("smbd_idle_event_handler: %s %p called\n",
808                   event->name, event->te));
809
810         if (!event->handler(&now, event->private_data)) {
811                 DEBUG(10,("smbd_idle_event_handler: %s %p stopped\n",
812                           event->name, event->te));
813                 /* Don't repeat, delete ourselves */
814                 TALLOC_FREE(event);
815                 return;
816         }
817
818         DEBUG(10,("smbd_idle_event_handler: %s %p rescheduled\n",
819                   event->name, event->te));
820
821         event->te = event_add_timed(ctx, event,
822                                     timeval_sum(&now, &event->interval),
823                                     smbd_idle_event_handler, event);
824
825         /* We can't do much but fail here. */
826         SMB_ASSERT(event->te != NULL);
827 }
828
829 struct idle_event *event_add_idle(struct event_context *event_ctx,
830                                   TALLOC_CTX *mem_ctx,
831                                   struct timeval interval,
832                                   const char *name,
833                                   bool (*handler)(const struct timeval *now,
834                                                   void *private_data),
835                                   void *private_data)
836 {
837         struct idle_event *result;
838         struct timeval now = timeval_current();
839
840         result = TALLOC_P(mem_ctx, struct idle_event);
841         if (result == NULL) {
842                 DEBUG(0, ("talloc failed\n"));
843                 return NULL;
844         }
845
846         result->interval = interval;
847         result->handler = handler;
848         result->private_data = private_data;
849
850         if (!(result->name = talloc_asprintf(result, "idle_evt(%s)", name))) {
851                 DEBUG(0, ("talloc failed\n"));
852                 TALLOC_FREE(result);
853                 return NULL;
854         }
855
856         result->te = event_add_timed(event_ctx, result,
857                                      timeval_sum(&now, &interval),
858                                      smbd_idle_event_handler, result);
859         if (result->te == NULL) {
860                 DEBUG(0, ("event_add_timed failed\n"));
861                 TALLOC_FREE(result);
862                 return NULL;
863         }
864
865         DEBUG(10,("event_add_idle: %s %p\n", result->name, result->te));
866         return result;
867 }
868
869 static void smbd_sig_term_handler(struct tevent_context *ev,
870                                   struct tevent_signal *se,
871                                   int signum,
872                                   int count,
873                                   void *siginfo,
874                                   void *private_data)
875 {
876         exit_server_cleanly("termination signal");
877 }
878
879 void smbd_setup_sig_term_handler(void)
880 {
881         struct tevent_signal *se;
882
883         se = tevent_add_signal(smbd_event_context(),
884                                smbd_event_context(),
885                                SIGTERM, 0,
886                                smbd_sig_term_handler,
887                                NULL);
888         if (!se) {
889                 exit_server("failed to setup SIGTERM handler");
890         }
891 }
892
893 static void smbd_sig_hup_handler(struct tevent_context *ev,
894                                   struct tevent_signal *se,
895                                   int signum,
896                                   int count,
897                                   void *siginfo,
898                                   void *private_data)
899 {
900         change_to_root_user();
901         DEBUG(1,("Reloading services after SIGHUP\n"));
902         reload_services(False);
903 }
904
905 void smbd_setup_sig_hup_handler(void)
906 {
907         struct tevent_signal *se;
908
909         se = tevent_add_signal(smbd_event_context(),
910                                smbd_event_context(),
911                                SIGHUP, 0,
912                                smbd_sig_hup_handler,
913                                NULL);
914         if (!se) {
915                 exit_server("failed to setup SIGHUP handler");
916         }
917 }
918
919 static NTSTATUS smbd_server_connection_loop_once(struct smbd_server_connection *conn)
920 {
921         fd_set r_fds, w_fds;
922         int selrtn;
923         struct timeval to;
924         int maxfd = 0;
925
926         to.tv_sec = SMBD_SELECT_TIMEOUT;
927         to.tv_usec = 0;
928
929         /*
930          * Setup the select fd sets.
931          */
932
933         FD_ZERO(&r_fds);
934         FD_ZERO(&w_fds);
935
936         /*
937          * Are there any timed events waiting ? If so, ensure we don't
938          * select for longer than it would take to wait for them.
939          */
940
941         {
942                 struct timeval now;
943                 GetTimeOfDay(&now);
944
945                 event_add_to_select_args(smbd_event_context(), &now,
946                                          &r_fds, &w_fds, &to, &maxfd);
947         }
948
949         /* Process a signal and timed events now... */
950         if (run_events(smbd_event_context(), 0, NULL, NULL)) {
951                 return NT_STATUS_RETRY;
952         }
953
954         {
955                 int sav;
956                 START_PROFILE(smbd_idle);
957
958                 selrtn = sys_select(maxfd+1,&r_fds,&w_fds,NULL,&to);
959                 sav = errno;
960
961                 END_PROFILE(smbd_idle);
962                 errno = sav;
963         }
964
965         if (run_events(smbd_event_context(), selrtn, &r_fds, &w_fds)) {
966                 return NT_STATUS_RETRY;
967         }
968
969         /* Check if error */
970         if (selrtn == -1) {
971                 /* something is wrong. Maybe the socket is dead? */
972                 return map_nt_error_from_unix(errno);
973         }
974
975         /* Did we timeout ? */
976         if (selrtn == 0) {
977                 return NT_STATUS_RETRY;
978         }
979
980         /* should not be reached */
981         return NT_STATUS_INTERNAL_ERROR;
982 }
983
984 /*
985  * Only allow 5 outstanding trans requests. We're allocating memory, so
986  * prevent a DoS.
987  */
988
989 NTSTATUS allow_new_trans(struct trans_state *list, int mid)
990 {
991         int count = 0;
992         for (; list != NULL; list = list->next) {
993
994                 if (list->mid == mid) {
995                         return NT_STATUS_INVALID_PARAMETER;
996                 }
997
998                 count += 1;
999         }
1000         if (count > 5) {
1001                 return NT_STATUS_INSUFFICIENT_RESOURCES;
1002         }
1003
1004         return NT_STATUS_OK;
1005 }
1006
1007 /*
1008 These flags determine some of the permissions required to do an operation 
1009
1010 Note that I don't set NEED_WRITE on some write operations because they
1011 are used by some brain-dead clients when printing, and I don't want to
1012 force write permissions on print services.
1013 */
1014 #define AS_USER (1<<0)
1015 #define NEED_WRITE (1<<1) /* Must be paired with AS_USER */
1016 #define TIME_INIT (1<<2)
1017 #define CAN_IPC (1<<3) /* Must be paired with AS_USER */
1018 #define AS_GUEST (1<<5) /* Must *NOT* be paired with AS_USER */
1019 #define DO_CHDIR (1<<6)
1020
1021 /* 
1022    define a list of possible SMB messages and their corresponding
1023    functions. Any message that has a NULL function is unimplemented -
1024    please feel free to contribute implementations!
1025 */
1026 static const struct smb_message_struct {
1027         const char *name;
1028         void (*fn)(struct smb_request *req);
1029         int flags;
1030 } smb_messages[256] = {
1031
1032 /* 0x00 */ { "SMBmkdir",reply_mkdir,AS_USER | NEED_WRITE},
1033 /* 0x01 */ { "SMBrmdir",reply_rmdir,AS_USER | NEED_WRITE},
1034 /* 0x02 */ { "SMBopen",reply_open,AS_USER },
1035 /* 0x03 */ { "SMBcreate",reply_mknew,AS_USER},
1036 /* 0x04 */ { "SMBclose",reply_close,AS_USER | CAN_IPC },
1037 /* 0x05 */ { "SMBflush",reply_flush,AS_USER},
1038 /* 0x06 */ { "SMBunlink",reply_unlink,AS_USER | NEED_WRITE },
1039 /* 0x07 */ { "SMBmv",reply_mv,AS_USER | NEED_WRITE },
1040 /* 0x08 */ { "SMBgetatr",reply_getatr,AS_USER},
1041 /* 0x09 */ { "SMBsetatr",reply_setatr,AS_USER | NEED_WRITE},
1042 /* 0x0a */ { "SMBread",reply_read,AS_USER},
1043 /* 0x0b */ { "SMBwrite",reply_write,AS_USER | CAN_IPC },
1044 /* 0x0c */ { "SMBlock",reply_lock,AS_USER},
1045 /* 0x0d */ { "SMBunlock",reply_unlock,AS_USER},
1046 /* 0x0e */ { "SMBctemp",reply_ctemp,AS_USER },
1047 /* 0x0f */ { "SMBmknew",reply_mknew,AS_USER},
1048 /* 0x10 */ { "SMBcheckpath",reply_checkpath,AS_USER},
1049 /* 0x11 */ { "SMBexit",reply_exit,DO_CHDIR},
1050 /* 0x12 */ { "SMBlseek",reply_lseek,AS_USER},
1051 /* 0x13 */ { "SMBlockread",reply_lockread,AS_USER},
1052 /* 0x14 */ { "SMBwriteunlock",reply_writeunlock,AS_USER},
1053 /* 0x15 */ { NULL, NULL, 0 },
1054 /* 0x16 */ { NULL, NULL, 0 },
1055 /* 0x17 */ { NULL, NULL, 0 },
1056 /* 0x18 */ { NULL, NULL, 0 },
1057 /* 0x19 */ { NULL, NULL, 0 },
1058 /* 0x1a */ { "SMBreadbraw",reply_readbraw,AS_USER},
1059 /* 0x1b */ { "SMBreadBmpx",reply_readbmpx,AS_USER},
1060 /* 0x1c */ { "SMBreadBs",reply_readbs,AS_USER },
1061 /* 0x1d */ { "SMBwritebraw",reply_writebraw,AS_USER},
1062 /* 0x1e */ { "SMBwriteBmpx",reply_writebmpx,AS_USER},
1063 /* 0x1f */ { "SMBwriteBs",reply_writebs,AS_USER},
1064 /* 0x20 */ { "SMBwritec", NULL,0},
1065 /* 0x21 */ { NULL, NULL, 0 },
1066 /* 0x22 */ { "SMBsetattrE",reply_setattrE,AS_USER | NEED_WRITE },
1067 /* 0x23 */ { "SMBgetattrE",reply_getattrE,AS_USER },
1068 /* 0x24 */ { "SMBlockingX",reply_lockingX,AS_USER },
1069 /* 0x25 */ { "SMBtrans",reply_trans,AS_USER | CAN_IPC },
1070 /* 0x26 */ { "SMBtranss",reply_transs,AS_USER | CAN_IPC},
1071 /* 0x27 */ { "SMBioctl",reply_ioctl,0},
1072 /* 0x28 */ { "SMBioctls", NULL,AS_USER},
1073 /* 0x29 */ { "SMBcopy",reply_copy,AS_USER | NEED_WRITE },
1074 /* 0x2a */ { "SMBmove", NULL,AS_USER | NEED_WRITE },
1075 /* 0x2b */ { "SMBecho",reply_echo,0},
1076 /* 0x2c */ { "SMBwriteclose",reply_writeclose,AS_USER},
1077 /* 0x2d */ { "SMBopenX",reply_open_and_X,AS_USER | CAN_IPC },
1078 /* 0x2e */ { "SMBreadX",reply_read_and_X,AS_USER | CAN_IPC },
1079 /* 0x2f */ { "SMBwriteX",reply_write_and_X,AS_USER | CAN_IPC },
1080 /* 0x30 */ { NULL, NULL, 0 },
1081 /* 0x31 */ { NULL, NULL, 0 },
1082 /* 0x32 */ { "SMBtrans2",reply_trans2, AS_USER | CAN_IPC },
1083 /* 0x33 */ { "SMBtranss2",reply_transs2, AS_USER | CAN_IPC },
1084 /* 0x34 */ { "SMBfindclose",reply_findclose,AS_USER},
1085 /* 0x35 */ { "SMBfindnclose",reply_findnclose,AS_USER},
1086 /* 0x36 */ { NULL, NULL, 0 },
1087 /* 0x37 */ { NULL, NULL, 0 },
1088 /* 0x38 */ { NULL, NULL, 0 },
1089 /* 0x39 */ { NULL, NULL, 0 },
1090 /* 0x3a */ { NULL, NULL, 0 },
1091 /* 0x3b */ { NULL, NULL, 0 },
1092 /* 0x3c */ { NULL, NULL, 0 },
1093 /* 0x3d */ { NULL, NULL, 0 },
1094 /* 0x3e */ { NULL, NULL, 0 },
1095 /* 0x3f */ { NULL, NULL, 0 },
1096 /* 0x40 */ { NULL, NULL, 0 },
1097 /* 0x41 */ { NULL, NULL, 0 },
1098 /* 0x42 */ { NULL, NULL, 0 },
1099 /* 0x43 */ { NULL, NULL, 0 },
1100 /* 0x44 */ { NULL, NULL, 0 },
1101 /* 0x45 */ { NULL, NULL, 0 },
1102 /* 0x46 */ { NULL, NULL, 0 },
1103 /* 0x47 */ { NULL, NULL, 0 },
1104 /* 0x48 */ { NULL, NULL, 0 },
1105 /* 0x49 */ { NULL, NULL, 0 },
1106 /* 0x4a */ { NULL, NULL, 0 },
1107 /* 0x4b */ { NULL, NULL, 0 },
1108 /* 0x4c */ { NULL, NULL, 0 },
1109 /* 0x4d */ { NULL, NULL, 0 },
1110 /* 0x4e */ { NULL, NULL, 0 },
1111 /* 0x4f */ { NULL, NULL, 0 },
1112 /* 0x50 */ { NULL, NULL, 0 },
1113 /* 0x51 */ { NULL, NULL, 0 },
1114 /* 0x52 */ { NULL, NULL, 0 },
1115 /* 0x53 */ { NULL, NULL, 0 },
1116 /* 0x54 */ { NULL, NULL, 0 },
1117 /* 0x55 */ { NULL, NULL, 0 },
1118 /* 0x56 */ { NULL, NULL, 0 },
1119 /* 0x57 */ { NULL, NULL, 0 },
1120 /* 0x58 */ { NULL, NULL, 0 },
1121 /* 0x59 */ { NULL, NULL, 0 },
1122 /* 0x5a */ { NULL, NULL, 0 },
1123 /* 0x5b */ { NULL, NULL, 0 },
1124 /* 0x5c */ { NULL, NULL, 0 },
1125 /* 0x5d */ { NULL, NULL, 0 },
1126 /* 0x5e */ { NULL, NULL, 0 },
1127 /* 0x5f */ { NULL, NULL, 0 },
1128 /* 0x60 */ { NULL, NULL, 0 },
1129 /* 0x61 */ { NULL, NULL, 0 },
1130 /* 0x62 */ { NULL, NULL, 0 },
1131 /* 0x63 */ { NULL, NULL, 0 },
1132 /* 0x64 */ { NULL, NULL, 0 },
1133 /* 0x65 */ { NULL, NULL, 0 },
1134 /* 0x66 */ { NULL, NULL, 0 },
1135 /* 0x67 */ { NULL, NULL, 0 },
1136 /* 0x68 */ { NULL, NULL, 0 },
1137 /* 0x69 */ { NULL, NULL, 0 },
1138 /* 0x6a */ { NULL, NULL, 0 },
1139 /* 0x6b */ { NULL, NULL, 0 },
1140 /* 0x6c */ { NULL, NULL, 0 },
1141 /* 0x6d */ { NULL, NULL, 0 },
1142 /* 0x6e */ { NULL, NULL, 0 },
1143 /* 0x6f */ { NULL, NULL, 0 },
1144 /* 0x70 */ { "SMBtcon",reply_tcon,0},
1145 /* 0x71 */ { "SMBtdis",reply_tdis,DO_CHDIR},
1146 /* 0x72 */ { "SMBnegprot",reply_negprot,0},
1147 /* 0x73 */ { "SMBsesssetupX",reply_sesssetup_and_X,0},
1148 /* 0x74 */ { "SMBulogoffX",reply_ulogoffX, 0}, /* ulogoff doesn't give a valid TID */
1149 /* 0x75 */ { "SMBtconX",reply_tcon_and_X,0},
1150 /* 0x76 */ { NULL, NULL, 0 },
1151 /* 0x77 */ { NULL, NULL, 0 },
1152 /* 0x78 */ { NULL, NULL, 0 },
1153 /* 0x79 */ { NULL, NULL, 0 },
1154 /* 0x7a */ { NULL, NULL, 0 },
1155 /* 0x7b */ { NULL, NULL, 0 },
1156 /* 0x7c */ { NULL, NULL, 0 },
1157 /* 0x7d */ { NULL, NULL, 0 },
1158 /* 0x7e */ { NULL, NULL, 0 },
1159 /* 0x7f */ { NULL, NULL, 0 },
1160 /* 0x80 */ { "SMBdskattr",reply_dskattr,AS_USER},
1161 /* 0x81 */ { "SMBsearch",reply_search,AS_USER},
1162 /* 0x82 */ { "SMBffirst",reply_search,AS_USER},
1163 /* 0x83 */ { "SMBfunique",reply_search,AS_USER},
1164 /* 0x84 */ { "SMBfclose",reply_fclose,AS_USER},
1165 /* 0x85 */ { NULL, NULL, 0 },
1166 /* 0x86 */ { NULL, NULL, 0 },
1167 /* 0x87 */ { NULL, NULL, 0 },
1168 /* 0x88 */ { NULL, NULL, 0 },
1169 /* 0x89 */ { NULL, NULL, 0 },
1170 /* 0x8a */ { NULL, NULL, 0 },
1171 /* 0x8b */ { NULL, NULL, 0 },
1172 /* 0x8c */ { NULL, NULL, 0 },
1173 /* 0x8d */ { NULL, NULL, 0 },
1174 /* 0x8e */ { NULL, NULL, 0 },
1175 /* 0x8f */ { NULL, NULL, 0 },
1176 /* 0x90 */ { NULL, NULL, 0 },
1177 /* 0x91 */ { NULL, NULL, 0 },
1178 /* 0x92 */ { NULL, NULL, 0 },
1179 /* 0x93 */ { NULL, NULL, 0 },
1180 /* 0x94 */ { NULL, NULL, 0 },
1181 /* 0x95 */ { NULL, NULL, 0 },
1182 /* 0x96 */ { NULL, NULL, 0 },
1183 /* 0x97 */ { NULL, NULL, 0 },
1184 /* 0x98 */ { NULL, NULL, 0 },
1185 /* 0x99 */ { NULL, NULL, 0 },
1186 /* 0x9a */ { NULL, NULL, 0 },
1187 /* 0x9b */ { NULL, NULL, 0 },
1188 /* 0x9c */ { NULL, NULL, 0 },
1189 /* 0x9d */ { NULL, NULL, 0 },
1190 /* 0x9e */ { NULL, NULL, 0 },
1191 /* 0x9f */ { NULL, NULL, 0 },
1192 /* 0xa0 */ { "SMBnttrans",reply_nttrans, AS_USER | CAN_IPC },
1193 /* 0xa1 */ { "SMBnttranss",reply_nttranss, AS_USER | CAN_IPC },
1194 /* 0xa2 */ { "SMBntcreateX",reply_ntcreate_and_X, AS_USER | CAN_IPC },
1195 /* 0xa3 */ { NULL, NULL, 0 },
1196 /* 0xa4 */ { "SMBntcancel",reply_ntcancel, 0 },
1197 /* 0xa5 */ { "SMBntrename",reply_ntrename, AS_USER | NEED_WRITE },
1198 /* 0xa6 */ { NULL, NULL, 0 },
1199 /* 0xa7 */ { NULL, NULL, 0 },
1200 /* 0xa8 */ { NULL, NULL, 0 },
1201 /* 0xa9 */ { NULL, NULL, 0 },
1202 /* 0xaa */ { NULL, NULL, 0 },
1203 /* 0xab */ { NULL, NULL, 0 },
1204 /* 0xac */ { NULL, NULL, 0 },
1205 /* 0xad */ { NULL, NULL, 0 },
1206 /* 0xae */ { NULL, NULL, 0 },
1207 /* 0xaf */ { NULL, NULL, 0 },
1208 /* 0xb0 */ { NULL, NULL, 0 },
1209 /* 0xb1 */ { NULL, NULL, 0 },
1210 /* 0xb2 */ { NULL, NULL, 0 },
1211 /* 0xb3 */ { NULL, NULL, 0 },
1212 /* 0xb4 */ { NULL, NULL, 0 },
1213 /* 0xb5 */ { NULL, NULL, 0 },
1214 /* 0xb6 */ { NULL, NULL, 0 },
1215 /* 0xb7 */ { NULL, NULL, 0 },
1216 /* 0xb8 */ { NULL, NULL, 0 },
1217 /* 0xb9 */ { NULL, NULL, 0 },
1218 /* 0xba */ { NULL, NULL, 0 },
1219 /* 0xbb */ { NULL, NULL, 0 },
1220 /* 0xbc */ { NULL, NULL, 0 },
1221 /* 0xbd */ { NULL, NULL, 0 },
1222 /* 0xbe */ { NULL, NULL, 0 },
1223 /* 0xbf */ { NULL, NULL, 0 },
1224 /* 0xc0 */ { "SMBsplopen",reply_printopen,AS_USER},
1225 /* 0xc1 */ { "SMBsplwr",reply_printwrite,AS_USER},
1226 /* 0xc2 */ { "SMBsplclose",reply_printclose,AS_USER},
1227 /* 0xc3 */ { "SMBsplretq",reply_printqueue,AS_USER},
1228 /* 0xc4 */ { NULL, NULL, 0 },
1229 /* 0xc5 */ { NULL, NULL, 0 },
1230 /* 0xc6 */ { NULL, NULL, 0 },
1231 /* 0xc7 */ { NULL, NULL, 0 },
1232 /* 0xc8 */ { NULL, NULL, 0 },
1233 /* 0xc9 */ { NULL, NULL, 0 },
1234 /* 0xca */ { NULL, NULL, 0 },
1235 /* 0xcb */ { NULL, NULL, 0 },
1236 /* 0xcc */ { NULL, NULL, 0 },
1237 /* 0xcd */ { NULL, NULL, 0 },
1238 /* 0xce */ { NULL, NULL, 0 },
1239 /* 0xcf */ { NULL, NULL, 0 },
1240 /* 0xd0 */ { "SMBsends",reply_sends,AS_GUEST},
1241 /* 0xd1 */ { "SMBsendb", NULL,AS_GUEST},
1242 /* 0xd2 */ { "SMBfwdname", NULL,AS_GUEST},
1243 /* 0xd3 */ { "SMBcancelf", NULL,AS_GUEST},
1244 /* 0xd4 */ { "SMBgetmac", NULL,AS_GUEST},
1245 /* 0xd5 */ { "SMBsendstrt",reply_sendstrt,AS_GUEST},
1246 /* 0xd6 */ { "SMBsendend",reply_sendend,AS_GUEST},
1247 /* 0xd7 */ { "SMBsendtxt",reply_sendtxt,AS_GUEST},
1248 /* 0xd8 */ { NULL, NULL, 0 },
1249 /* 0xd9 */ { NULL, NULL, 0 },
1250 /* 0xda */ { NULL, NULL, 0 },
1251 /* 0xdb */ { NULL, NULL, 0 },
1252 /* 0xdc */ { NULL, NULL, 0 },
1253 /* 0xdd */ { NULL, NULL, 0 },
1254 /* 0xde */ { NULL, NULL, 0 },
1255 /* 0xdf */ { NULL, NULL, 0 },
1256 /* 0xe0 */ { NULL, NULL, 0 },
1257 /* 0xe1 */ { NULL, NULL, 0 },
1258 /* 0xe2 */ { NULL, NULL, 0 },
1259 /* 0xe3 */ { NULL, NULL, 0 },
1260 /* 0xe4 */ { NULL, NULL, 0 },
1261 /* 0xe5 */ { NULL, NULL, 0 },
1262 /* 0xe6 */ { NULL, NULL, 0 },
1263 /* 0xe7 */ { NULL, NULL, 0 },
1264 /* 0xe8 */ { NULL, NULL, 0 },
1265 /* 0xe9 */ { NULL, NULL, 0 },
1266 /* 0xea */ { NULL, NULL, 0 },
1267 /* 0xeb */ { NULL, NULL, 0 },
1268 /* 0xec */ { NULL, NULL, 0 },
1269 /* 0xed */ { NULL, NULL, 0 },
1270 /* 0xee */ { NULL, NULL, 0 },
1271 /* 0xef */ { NULL, NULL, 0 },
1272 /* 0xf0 */ { NULL, NULL, 0 },
1273 /* 0xf1 */ { NULL, NULL, 0 },
1274 /* 0xf2 */ { NULL, NULL, 0 },
1275 /* 0xf3 */ { NULL, NULL, 0 },
1276 /* 0xf4 */ { NULL, NULL, 0 },
1277 /* 0xf5 */ { NULL, NULL, 0 },
1278 /* 0xf6 */ { NULL, NULL, 0 },
1279 /* 0xf7 */ { NULL, NULL, 0 },
1280 /* 0xf8 */ { NULL, NULL, 0 },
1281 /* 0xf9 */ { NULL, NULL, 0 },
1282 /* 0xfa */ { NULL, NULL, 0 },
1283 /* 0xfb */ { NULL, NULL, 0 },
1284 /* 0xfc */ { NULL, NULL, 0 },
1285 /* 0xfd */ { NULL, NULL, 0 },
1286 /* 0xfe */ { NULL, NULL, 0 },
1287 /* 0xff */ { NULL, NULL, 0 }
1288
1289 };
1290
1291 /*******************************************************************
1292  allocate and initialize a reply packet
1293 ********************************************************************/
1294
1295 static bool create_outbuf(TALLOC_CTX *mem_ctx, struct smb_request *req,
1296                           const char *inbuf, char **outbuf, uint8_t num_words,
1297                           uint32_t num_bytes)
1298 {
1299         /*
1300          * Protect against integer wrap
1301          */
1302         if ((num_bytes > 0xffffff)
1303             || ((num_bytes + smb_size + num_words*2) > 0xffffff)) {
1304                 char *msg;
1305                 if (asprintf(&msg, "num_bytes too large: %u",
1306                              (unsigned)num_bytes) == -1) {
1307                         msg = CONST_DISCARD(char *, "num_bytes too large");
1308                 }
1309                 smb_panic(msg);
1310         }
1311
1312         *outbuf = TALLOC_ARRAY(mem_ctx, char,
1313                                smb_size + num_words*2 + num_bytes);
1314         if (*outbuf == NULL) {
1315                 return false;
1316         }
1317
1318         construct_reply_common(req, inbuf, *outbuf);
1319         srv_set_message(*outbuf, num_words, num_bytes, false);
1320         /*
1321          * Zero out the word area, the caller has to take care of the bcc area
1322          * himself
1323          */
1324         if (num_words != 0) {
1325                 memset(*outbuf + smb_vwv0, 0, num_words*2);
1326         }
1327
1328         return true;
1329 }
1330
1331 void reply_outbuf(struct smb_request *req, uint8 num_words, uint32 num_bytes)
1332 {
1333         char *outbuf;
1334         if (!create_outbuf(req, req, (char *)req->inbuf, &outbuf, num_words,
1335                            num_bytes)) {
1336                 smb_panic("could not allocate output buffer\n");
1337         }
1338         req->outbuf = (uint8_t *)outbuf;
1339 }
1340
1341
1342 /*******************************************************************
1343  Dump a packet to a file.
1344 ********************************************************************/
1345
1346 static void smb_dump(const char *name, int type, const char *data, ssize_t len)
1347 {
1348         int fd, i;
1349         char *fname = NULL;
1350         if (DEBUGLEVEL < 50) {
1351                 return;
1352         }
1353
1354         if (len < 4) len = smb_len(data)+4;
1355         for (i=1;i<100;i++) {
1356                 if (asprintf(&fname, "/tmp/%s.%d.%s", name, i,
1357                              type ? "req" : "resp") == -1) {
1358                         return;
1359                 }
1360                 fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
1361                 if (fd != -1 || errno != EEXIST) break;
1362         }
1363         if (fd != -1) {
1364                 ssize_t ret = write(fd, data, len);
1365                 if (ret != len)
1366                         DEBUG(0,("smb_dump: problem: write returned %d\n", (int)ret ));
1367                 close(fd);
1368                 DEBUG(0,("created %s len %lu\n", fname, (unsigned long)len));
1369         }
1370         SAFE_FREE(fname);
1371 }
1372
1373 /****************************************************************************
1374  Prepare everything for calling the actual request function, and potentially
1375  call the request function via the "new" interface.
1376
1377  Return False if the "legacy" function needs to be called, everything is
1378  prepared.
1379
1380  Return True if we're done.
1381
1382  I know this API sucks, but it is the one with the least code change I could
1383  find.
1384 ****************************************************************************/
1385
1386 static connection_struct *switch_message(uint8 type, struct smb_request *req, int size)
1387 {
1388         int flags;
1389         uint16 session_tag;
1390         connection_struct *conn = NULL;
1391         struct smbd_server_connection *sconn = smbd_server_conn;
1392
1393         errno = 0;
1394
1395         /* Make sure this is an SMB packet. smb_size contains NetBIOS header
1396          * so subtract 4 from it. */
1397         if (!valid_smb_header(req->inbuf)
1398             || (size < (smb_size - 4))) {
1399                 DEBUG(2,("Non-SMB packet of length %d. Terminating server\n",
1400                          smb_len(req->inbuf)));
1401                 exit_server_cleanly("Non-SMB packet");
1402         }
1403
1404         if (smb_messages[type].fn == NULL) {
1405                 DEBUG(0,("Unknown message type %d!\n",type));
1406                 smb_dump("Unknown", 1, (char *)req->inbuf, size);
1407                 reply_unknown_new(req, type);
1408                 return NULL;
1409         }
1410
1411         flags = smb_messages[type].flags;
1412
1413         /* In share mode security we must ignore the vuid. */
1414         session_tag = (lp_security() == SEC_SHARE)
1415                 ? UID_FIELD_INVALID : req->vuid;
1416         conn = req->conn;
1417
1418         DEBUG(3,("switch message %s (pid %d) conn 0x%lx\n", smb_fn_name(type),
1419                  (int)sys_getpid(), (unsigned long)conn));
1420
1421         smb_dump(smb_fn_name(type), 1, (char *)req->inbuf, size);
1422
1423         /* Ensure this value is replaced in the incoming packet. */
1424         SSVAL(req->inbuf,smb_uid,session_tag);
1425
1426         /*
1427          * Ensure the correct username is in current_user_info.  This is a
1428          * really ugly bugfix for problems with multiple session_setup_and_X's
1429          * being done and allowing %U and %G substitutions to work correctly.
1430          * There is a reason this code is done here, don't move it unless you
1431          * know what you're doing... :-).
1432          * JRA.
1433          */
1434
1435         if (session_tag != sconn->smb1.sessions.last_session_tag) {
1436                 user_struct *vuser = NULL;
1437
1438                 sconn->smb1.sessions.last_session_tag = session_tag;
1439                 if(session_tag != UID_FIELD_INVALID) {
1440                         vuser = get_valid_user_struct(sconn, session_tag);
1441                         if (vuser) {
1442                                 set_current_user_info(
1443                                         vuser->server_info->sanitized_username,
1444                                         vuser->server_info->unix_name,
1445                                         pdb_get_domain(vuser->server_info
1446                                                        ->sam_account));
1447                         }
1448                 }
1449         }
1450
1451         /* Does this call need to be run as the connected user? */
1452         if (flags & AS_USER) {
1453
1454                 /* Does this call need a valid tree connection? */
1455                 if (!conn) {
1456                         /*
1457                          * Amazingly, the error code depends on the command
1458                          * (from Samba4).
1459                          */
1460                         if (type == SMBntcreateX) {
1461                                 reply_nterror(req, NT_STATUS_INVALID_HANDLE);
1462                         } else {
1463                                 reply_nterror(req, NT_STATUS_NETWORK_NAME_DELETED);
1464                         }
1465                         return NULL;
1466                 }
1467
1468                 if (!change_to_user(conn,session_tag)) {
1469                         DEBUG(0, ("Error: Could not change to user. Removing "
1470                             "deferred open, mid=%d.\n", req->mid));
1471                         reply_force_doserror(req, ERRSRV, ERRbaduid);
1472                         return conn;
1473                 }
1474
1475                 /* All NEED_WRITE and CAN_IPC flags must also have AS_USER. */
1476
1477                 /* Does it need write permission? */
1478                 if ((flags & NEED_WRITE) && !CAN_WRITE(conn)) {
1479                         reply_nterror(req, NT_STATUS_MEDIA_WRITE_PROTECTED);
1480                         return conn;
1481                 }
1482
1483                 /* IPC services are limited */
1484                 if (IS_IPC(conn) && !(flags & CAN_IPC)) {
1485                         reply_nterror(req, NT_STATUS_ACCESS_DENIED);
1486                         return conn;
1487                 }
1488         } else {
1489                 /* This call needs to be run as root */
1490                 change_to_root_user();
1491         }
1492
1493         /* load service specific parameters */
1494         if (conn) {
1495                 if (req->encrypted) {
1496                         conn->encrypted_tid = true;
1497                         /* encrypted required from now on. */
1498                         conn->encrypt_level = Required;
1499                 } else if (ENCRYPTION_REQUIRED(conn)) {
1500                         if (req->cmd != SMBtrans2 && req->cmd != SMBtranss2) {
1501                                 exit_server_cleanly("encryption required "
1502                                         "on connection");
1503                                 return conn;
1504                         }
1505                 }
1506
1507                 if (!set_current_service(conn,SVAL(req->inbuf,smb_flg),
1508                                          (flags & (AS_USER|DO_CHDIR)
1509                                           ?True:False))) {
1510                         reply_nterror(req, NT_STATUS_ACCESS_DENIED);
1511                         return conn;
1512                 }
1513                 conn->num_smb_operations++;
1514         }
1515
1516         /* does this protocol need to be run as guest? */
1517         if ((flags & AS_GUEST)
1518             && (!change_to_guest() ||
1519                 !check_access(smbd_server_fd(), lp_hostsallow(-1),
1520                               lp_hostsdeny(-1)))) {
1521                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
1522                 return conn;
1523         }
1524
1525         smb_messages[type].fn(req);
1526         return req->conn;
1527 }
1528
1529 /****************************************************************************
1530  Construct a reply to the incoming packet.
1531 ****************************************************************************/
1532
1533 static void construct_reply(char *inbuf, int size, size_t unread_bytes,
1534                             uint32_t seqnum, bool encrypted,
1535                             struct smb_perfcount_data *deferred_pcd)
1536 {
1537         connection_struct *conn;
1538         struct smb_request *req;
1539
1540         if (!(req = talloc(talloc_tos(), struct smb_request))) {
1541                 smb_panic("could not allocate smb_request");
1542         }
1543
1544         if (!init_smb_request(req, (uint8 *)inbuf, unread_bytes, encrypted,
1545                               seqnum)) {
1546                 exit_server_cleanly("Invalid SMB request");
1547         }
1548
1549         req->inbuf  = (uint8_t *)talloc_move(req, &inbuf);
1550
1551         /* we popped this message off the queue - keep original perf data */
1552         if (deferred_pcd)
1553                 req->pcd = *deferred_pcd;
1554         else {
1555                 SMB_PERFCOUNT_START(&req->pcd);
1556                 SMB_PERFCOUNT_SET_OP(&req->pcd, req->cmd);
1557                 SMB_PERFCOUNT_SET_MSGLEN_IN(&req->pcd, size);
1558         }
1559
1560         conn = switch_message(req->cmd, req, size);
1561
1562         if (req->unread_bytes) {
1563                 /* writeX failed. drain socket. */
1564                 if (drain_socket(smbd_server_fd(), req->unread_bytes) !=
1565                                 req->unread_bytes) {
1566                         smb_panic("failed to drain pending bytes");
1567                 }
1568                 req->unread_bytes = 0;
1569         }
1570
1571         if (req->done) {
1572                 TALLOC_FREE(req);
1573                 return;
1574         }
1575
1576         if (req->outbuf == NULL) {
1577                 return;
1578         }
1579
1580         if (CVAL(req->outbuf,0) == 0) {
1581                 show_msg((char *)req->outbuf);
1582         }
1583
1584         if (!srv_send_smb(smbd_server_fd(),
1585                         (char *)req->outbuf,
1586                         true, req->seqnum+1,
1587                         IS_CONN_ENCRYPTED(conn)||req->encrypted,
1588                         &req->pcd)) {
1589                 exit_server_cleanly("construct_reply: srv_send_smb failed.");
1590         }
1591
1592         TALLOC_FREE(req);
1593
1594         return;
1595 }
1596
1597 /****************************************************************************
1598  Process an smb from the client
1599 ****************************************************************************/
1600 static void process_smb(struct smbd_server_connection *conn,
1601                         uint8_t *inbuf, size_t nread, size_t unread_bytes,
1602                         uint32_t seqnum, bool encrypted,
1603                         struct smb_perfcount_data *deferred_pcd)
1604 {
1605         int msg_type = CVAL(inbuf,0);
1606
1607         DO_PROFILE_INC(smb_count);
1608
1609         DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type,
1610                     smb_len(inbuf) ) );
1611         DEBUG( 3, ( "Transaction %d of length %d (%u toread)\n", trans_num,
1612                                 (int)nread,
1613                                 (unsigned int)unread_bytes ));
1614
1615         if (msg_type != 0) {
1616                 /*
1617                  * NetBIOS session request, keepalive, etc.
1618                  */
1619                 reply_special((char *)inbuf);
1620                 goto done;
1621         }
1622
1623         if (smbd_server_conn->allow_smb2) {
1624                 if (smbd_is_smb2_header(inbuf, nread)) {
1625                         smbd_smb2_first_negprot(smbd_server_conn, inbuf, nread);
1626                         return;
1627                 }
1628                 smbd_server_conn->allow_smb2 = false;
1629         }
1630
1631         show_msg((char *)inbuf);
1632
1633         construct_reply((char *)inbuf,nread,unread_bytes,seqnum,encrypted,deferred_pcd);
1634         trans_num++;
1635
1636 done:
1637         conn->smb1.num_requests++;
1638
1639         /* The timeout_processing function isn't run nearly
1640            often enough to implement 'max log size' without
1641            overrunning the size of the file by many megabytes.
1642            This is especially true if we are running at debug
1643            level 10.  Checking every 50 SMBs is a nice
1644            tradeoff of performance vs log file size overrun. */
1645
1646         if ((conn->smb1.num_requests % 50) == 0 &&
1647             need_to_check_log_size()) {
1648                 change_to_root_user();
1649                 check_log_size();
1650         }
1651 }
1652
1653 /****************************************************************************
1654  Return a string containing the function name of a SMB command.
1655 ****************************************************************************/
1656
1657 const char *smb_fn_name(int type)
1658 {
1659         const char *unknown_name = "SMBunknown";
1660
1661         if (smb_messages[type].name == NULL)
1662                 return(unknown_name);
1663
1664         return(smb_messages[type].name);
1665 }
1666
1667 /****************************************************************************
1668  Helper functions for contruct_reply.
1669 ****************************************************************************/
1670
1671 void add_to_common_flags2(uint32 v)
1672 {
1673         common_flags2 |= v;
1674 }
1675
1676 void remove_from_common_flags2(uint32 v)
1677 {
1678         common_flags2 &= ~v;
1679 }
1680
1681 static void construct_reply_common(struct smb_request *req, const char *inbuf,
1682                                    char *outbuf)
1683 {
1684         srv_set_message(outbuf,0,0,false);
1685
1686         SCVAL(outbuf, smb_com, req->cmd);
1687         SIVAL(outbuf,smb_rcls,0);
1688         SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES)); 
1689         SSVAL(outbuf,smb_flg2,
1690                 (SVAL(inbuf,smb_flg2) & FLAGS2_UNICODE_STRINGS) |
1691                 common_flags2);
1692         memset(outbuf+smb_pidhigh,'\0',(smb_tid-smb_pidhigh));
1693
1694         SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
1695         SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
1696         SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
1697         SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
1698 }
1699
1700 void construct_reply_common_req(struct smb_request *req, char *outbuf)
1701 {
1702         construct_reply_common(req, (char *)req->inbuf, outbuf);
1703 }
1704
1705 /*
1706  * How many bytes have we already accumulated up to the current wct field
1707  * offset?
1708  */
1709
1710 size_t req_wct_ofs(struct smb_request *req)
1711 {
1712         size_t buf_size;
1713
1714         if (req->chain_outbuf == NULL) {
1715                 return smb_wct - 4;
1716         }
1717         buf_size = talloc_get_size(req->chain_outbuf);
1718         if ((buf_size % 4) != 0) {
1719                 buf_size += (4 - (buf_size % 4));
1720         }
1721         return buf_size - 4;
1722 }
1723
1724 /*
1725  * Hack around reply_nterror & friends not being aware of chained requests,
1726  * generating illegal (i.e. wct==0) chain replies.
1727  */
1728
1729 static void fixup_chain_error_packet(struct smb_request *req)
1730 {
1731         uint8_t *outbuf = req->outbuf;
1732         req->outbuf = NULL;
1733         reply_outbuf(req, 2, 0);
1734         memcpy(req->outbuf, outbuf, smb_wct);
1735         TALLOC_FREE(outbuf);
1736         SCVAL(req->outbuf, smb_vwv0, 0xff);
1737 }
1738
1739 /**
1740  * @brief Find the smb_cmd offset of the last command pushed
1741  * @param[in] buf       The buffer we're building up
1742  * @retval              Where can we put our next andx cmd?
1743  *
1744  * While chaining requests, the "next" request we're looking at needs to put
1745  * its SMB_Command before the data the previous request already built up added
1746  * to the chain. Find the offset to the place where we have to put our cmd.
1747  */
1748
1749 static bool find_andx_cmd_ofs(uint8_t *buf, size_t *pofs)
1750 {
1751         uint8_t cmd;
1752         size_t ofs;
1753
1754         cmd = CVAL(buf, smb_com);
1755
1756         SMB_ASSERT(is_andx_req(cmd));
1757
1758         ofs = smb_vwv0;
1759
1760         while (CVAL(buf, ofs) != 0xff) {
1761
1762                 if (!is_andx_req(CVAL(buf, ofs))) {
1763                         return false;
1764                 }
1765
1766                 /*
1767                  * ofs is from start of smb header, so add the 4 length
1768                  * bytes. The next cmd is right after the wct field.
1769                  */
1770                 ofs = SVAL(buf, ofs+2) + 4 + 1;
1771
1772                 SMB_ASSERT(ofs+4 < talloc_get_size(buf));
1773         }
1774
1775         *pofs = ofs;
1776         return true;
1777 }
1778
1779 /**
1780  * @brief Do the smb chaining at a buffer level
1781  * @param[in] poutbuf           Pointer to the talloc'ed buffer to be modified
1782  * @param[in] smb_command       The command that we want to issue
1783  * @param[in] wct               How many words?
1784  * @param[in] vwv               The words, already in network order
1785  * @param[in] bytes_alignment   How shall we align "bytes"?
1786  * @param[in] num_bytes         How many bytes?
1787  * @param[in] bytes             The data the request ships
1788  *
1789  * smb_splice_chain() adds the vwv and bytes to the request already present in
1790  * *poutbuf.
1791  */
1792
1793 static bool smb_splice_chain(uint8_t **poutbuf, uint8_t smb_command,
1794                              uint8_t wct, const uint16_t *vwv,
1795                              size_t bytes_alignment,
1796                              uint32_t num_bytes, const uint8_t *bytes)
1797 {
1798         uint8_t *outbuf;
1799         size_t old_size, new_size;
1800         size_t ofs;
1801         size_t chain_padding = 0;
1802         size_t bytes_padding = 0;
1803         bool first_request;
1804
1805         old_size = talloc_get_size(*poutbuf);
1806
1807         /*
1808          * old_size == smb_wct means we're pushing the first request in for
1809          * libsmb/
1810          */
1811
1812         first_request = (old_size == smb_wct);
1813
1814         if (!first_request && ((old_size % 4) != 0)) {
1815                 /*
1816                  * Align the wct field of subsequent requests to a 4-byte
1817                  * boundary
1818                  */
1819                 chain_padding = 4 - (old_size % 4);
1820         }
1821
1822         /*
1823          * After the old request comes the new wct field (1 byte), the vwv's
1824          * and the num_bytes field. After at we might need to align the bytes
1825          * given to us to "bytes_alignment", increasing the num_bytes value.
1826          */
1827
1828         new_size = old_size + chain_padding + 1 + wct * sizeof(uint16_t) + 2;
1829
1830         if ((bytes_alignment != 0) && ((new_size % bytes_alignment) != 0)) {
1831                 bytes_padding = bytes_alignment - (new_size % bytes_alignment);
1832         }
1833
1834         new_size += bytes_padding + num_bytes;
1835
1836         if ((smb_command != SMBwriteX) && (new_size > 0xffff)) {
1837                 DEBUG(1, ("splice_chain: %u bytes won't fit\n",
1838                           (unsigned)new_size));
1839                 return false;
1840         }
1841
1842         outbuf = TALLOC_REALLOC_ARRAY(NULL, *poutbuf, uint8_t, new_size);
1843         if (outbuf == NULL) {
1844                 DEBUG(0, ("talloc failed\n"));
1845                 return false;
1846         }
1847         *poutbuf = outbuf;
1848
1849         if (first_request) {
1850                 SCVAL(outbuf, smb_com, smb_command);
1851         } else {
1852                 size_t andx_cmd_ofs;
1853
1854                 if (!find_andx_cmd_ofs(outbuf, &andx_cmd_ofs)) {
1855                         DEBUG(1, ("invalid command chain\n"));
1856                         *poutbuf = TALLOC_REALLOC_ARRAY(
1857                                 NULL, *poutbuf, uint8_t, old_size);
1858                         return false;
1859                 }
1860
1861                 if (chain_padding != 0) {
1862                         memset(outbuf + old_size, 0, chain_padding);
1863                         old_size += chain_padding;
1864                 }
1865
1866                 SCVAL(outbuf, andx_cmd_ofs, smb_command);
1867                 SSVAL(outbuf, andx_cmd_ofs + 2, old_size - 4);
1868         }
1869
1870         ofs = old_size;
1871
1872         /*
1873          * Push the chained request:
1874          *
1875          * wct field
1876          */
1877
1878         SCVAL(outbuf, ofs, wct);
1879         ofs += 1;
1880
1881         /*
1882          * vwv array
1883          */
1884
1885         memcpy(outbuf + ofs, vwv, sizeof(uint16_t) * wct);
1886         ofs += sizeof(uint16_t) * wct;
1887
1888         /*
1889          * bcc (byte count)
1890          */
1891
1892         SSVAL(outbuf, ofs, num_bytes + bytes_padding);
1893         ofs += sizeof(uint16_t);
1894
1895         /*
1896          * padding
1897          */
1898
1899         if (bytes_padding != 0) {
1900                 memset(outbuf + ofs, 0, bytes_padding);
1901                 ofs += bytes_padding;
1902         }
1903
1904         /*
1905          * The bytes field
1906          */
1907
1908         memcpy(outbuf + ofs, bytes, num_bytes);
1909
1910         return true;
1911 }
1912
1913 /****************************************************************************
1914  Construct a chained reply and add it to the already made reply
1915 ****************************************************************************/
1916
1917 void chain_reply(struct smb_request *req)
1918 {
1919         size_t smblen = smb_len(req->inbuf);
1920         size_t already_used, length_needed;
1921         uint8_t chain_cmd;
1922         uint32_t chain_offset;  /* uint32_t to avoid overflow */
1923
1924         uint8_t wct;
1925         uint16_t *vwv;
1926         uint16_t buflen;
1927         uint8_t *buf;
1928
1929         if (IVAL(req->outbuf, smb_rcls) != 0) {
1930                 fixup_chain_error_packet(req);
1931         }
1932
1933         /*
1934          * Any of the AndX requests and replies have at least a wct of
1935          * 2. vwv[0] is the next command, vwv[1] is the offset from the
1936          * beginning of the SMB header to the next wct field.
1937          *
1938          * None of the AndX requests put anything valuable in vwv[0] and [1],
1939          * so we can overwrite it here to form the chain.
1940          */
1941
1942         if ((req->wct < 2) || (CVAL(req->outbuf, smb_wct) < 2)) {
1943                 if (req->chain_outbuf == NULL) {
1944                         req->chain_outbuf = TALLOC_REALLOC_ARRAY(
1945                                 req, req->outbuf, uint8_t,
1946                                 smb_len(req->outbuf) + 4);
1947                         if (req->chain_outbuf == NULL) {
1948                                 smb_panic("talloc failed");
1949                         }
1950                 }
1951                 req->outbuf = NULL;
1952                 goto error;
1953         }
1954
1955         /*
1956          * Here we assume that this is the end of the chain. For that we need
1957          * to set "next command" to 0xff and the offset to 0. If we later find
1958          * more commands in the chain, this will be overwritten again.
1959          */
1960
1961         SCVAL(req->outbuf, smb_vwv0, 0xff);
1962         SCVAL(req->outbuf, smb_vwv0+1, 0);
1963         SSVAL(req->outbuf, smb_vwv1, 0);
1964
1965         if (req->chain_outbuf == NULL) {
1966                 /*
1967                  * In req->chain_outbuf we collect all the replies. Start the
1968                  * chain by copying in the first reply.
1969                  *
1970                  * We do the realloc because later on we depend on
1971                  * talloc_get_size to determine the length of
1972                  * chain_outbuf. The reply_xxx routines might have
1973                  * over-allocated (reply_pipe_read_and_X used to be such an
1974                  * example).
1975                  */
1976                 req->chain_outbuf = TALLOC_REALLOC_ARRAY(
1977                         req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4);
1978                 if (req->chain_outbuf == NULL) {
1979                         smb_panic("talloc failed");
1980                 }
1981                 req->outbuf = NULL;
1982         } else {
1983                 /*
1984                  * Update smb headers where subsequent chained commands
1985                  * may have updated them.
1986                  */
1987                 SCVAL(req->chain_outbuf, smb_tid, CVAL(req->outbuf, smb_tid));
1988                 SCVAL(req->chain_outbuf, smb_uid, CVAL(req->outbuf, smb_uid));
1989
1990                 if (!smb_splice_chain(&req->chain_outbuf,
1991                                       CVAL(req->outbuf, smb_com),
1992                                       CVAL(req->outbuf, smb_wct),
1993                                       (uint16_t *)(req->outbuf + smb_vwv),
1994                                       0, smb_buflen(req->outbuf),
1995                                       (uint8_t *)smb_buf(req->outbuf))) {
1996                         goto error;
1997                 }
1998                 TALLOC_FREE(req->outbuf);
1999         }
2000
2001         /*
2002          * We use the old request's vwv field to grab the next chained command
2003          * and offset into the chained fields.
2004          */
2005
2006         chain_cmd = CVAL(req->vwv+0, 0);
2007         chain_offset = SVAL(req->vwv+1, 0);
2008
2009         if (chain_cmd == 0xff) {
2010                 /*
2011                  * End of chain, no more requests from the client. So ship the
2012                  * replies.
2013                  */
2014                 smb_setlen((char *)(req->chain_outbuf),
2015                            talloc_get_size(req->chain_outbuf) - 4);
2016
2017                 if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf,
2018                                   true, req->seqnum+1,
2019                                   IS_CONN_ENCRYPTED(req->conn)
2020                                   ||req->encrypted,
2021                                   &req->pcd)) {
2022                         exit_server_cleanly("chain_reply: srv_send_smb "
2023                                             "failed.");
2024                 }
2025                 TALLOC_FREE(req->chain_outbuf);
2026                 req->done = true;
2027                 return;
2028         }
2029
2030         /* add a new perfcounter for this element of chain */
2031         SMB_PERFCOUNT_ADD(&req->pcd);
2032         SMB_PERFCOUNT_SET_OP(&req->pcd, chain_cmd);
2033         SMB_PERFCOUNT_SET_MSGLEN_IN(&req->pcd, smblen);
2034
2035         /*
2036          * Check if the client tries to fool us. The request so far uses the
2037          * space to the end of the byte buffer in the request just
2038          * processed. The chain_offset can't point into that area. If that was
2039          * the case, we could end up with an endless processing of the chain,
2040          * we would always handle the same request.
2041          */
2042
2043         already_used = PTR_DIFF(req->buf+req->buflen, smb_base(req->inbuf));
2044         if (chain_offset < already_used) {
2045                 goto error;
2046         }
2047
2048         /*
2049          * Next check: Make sure the chain offset does not point beyond the
2050          * overall smb request length.
2051          */
2052
2053         length_needed = chain_offset+1; /* wct */
2054         if (length_needed > smblen) {
2055                 goto error;
2056         }
2057
2058         /*
2059          * Now comes the pointer magic. Goal here is to set up req->vwv and
2060          * req->buf correctly again to be able to call the subsequent
2061          * switch_message(). The chain offset (the former vwv[1]) points at
2062          * the new wct field.
2063          */
2064
2065         wct = CVAL(smb_base(req->inbuf), chain_offset);
2066
2067         /*
2068          * Next consistency check: Make the new vwv array fits in the overall
2069          * smb request.
2070          */
2071
2072         length_needed += (wct+1)*sizeof(uint16_t); /* vwv+buflen */
2073         if (length_needed > smblen) {
2074                 goto error;
2075         }
2076         vwv = (uint16_t *)(smb_base(req->inbuf) + chain_offset + 1);
2077
2078         /*
2079          * Now grab the new byte buffer....
2080          */
2081
2082         buflen = SVAL(vwv+wct, 0);
2083
2084         /*
2085          * .. and check that it fits.
2086          */
2087
2088         length_needed += buflen;
2089         if (length_needed > smblen) {
2090                 goto error;
2091         }
2092         buf = (uint8_t *)(vwv+wct+1);
2093
2094         req->cmd = chain_cmd;
2095         req->wct = wct;
2096         req->vwv = vwv;
2097         req->buflen = buflen;
2098         req->buf = buf;
2099
2100         switch_message(chain_cmd, req, smblen);
2101
2102         if (req->outbuf == NULL) {
2103                 /*
2104                  * This happens if the chained command has suspended itself or
2105                  * if it has called srv_send_smb() itself.
2106                  */
2107                 return;
2108         }
2109
2110         /*
2111          * We end up here if the chained command was not itself chained or
2112          * suspended, but for example a close() command. We now need to splice
2113          * the chained commands' outbuf into the already built up chain_outbuf
2114          * and ship the result.
2115          */
2116         goto done;
2117
2118  error:
2119         /*
2120          * We end up here if there's any error in the chain syntax. Report a
2121          * DOS error, just like Windows does.
2122          */
2123         reply_force_doserror(req, ERRSRV, ERRerror);
2124         fixup_chain_error_packet(req);
2125
2126  done:
2127         /*
2128          * This scary statement intends to set the
2129          * FLAGS2_32_BIT_ERROR_CODES flg2 field in req->chain_outbuf
2130          * to the value req->outbuf carries
2131          */
2132         SSVAL(req->chain_outbuf, smb_flg2,
2133               (SVAL(req->chain_outbuf, smb_flg2) & ~FLAGS2_32_BIT_ERROR_CODES)
2134               | (SVAL(req->outbuf, smb_flg2) & FLAGS2_32_BIT_ERROR_CODES));
2135
2136         /*
2137          * Transfer the error codes from the subrequest to the main one
2138          */
2139         SSVAL(req->chain_outbuf, smb_rcls, SVAL(req->outbuf, smb_rcls));
2140         SSVAL(req->chain_outbuf, smb_err, SVAL(req->outbuf, smb_err));
2141
2142         if (!smb_splice_chain(&req->chain_outbuf,
2143                               CVAL(req->outbuf, smb_com),
2144                               CVAL(req->outbuf, smb_wct),
2145                               (uint16_t *)(req->outbuf + smb_vwv),
2146                               0, smb_buflen(req->outbuf),
2147                               (uint8_t *)smb_buf(req->outbuf))) {
2148                 exit_server_cleanly("chain_reply: smb_splice_chain failed\n");
2149         }
2150         TALLOC_FREE(req->outbuf);
2151
2152         smb_setlen((char *)(req->chain_outbuf),
2153                    talloc_get_size(req->chain_outbuf) - 4);
2154
2155         show_msg((char *)(req->chain_outbuf));
2156
2157         if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf,
2158                           true, req->seqnum+1,
2159                           IS_CONN_ENCRYPTED(req->conn)||req->encrypted,
2160                           &req->pcd)) {
2161                 exit_server_cleanly("construct_reply: srv_send_smb failed.");
2162         }
2163         TALLOC_FREE(req->chain_outbuf);
2164         req->done = true;
2165 }
2166
2167 /****************************************************************************
2168  Check if services need reloading.
2169 ****************************************************************************/
2170
2171 void check_reload(time_t t)
2172 {
2173         time_t printcap_cache_time = (time_t)lp_printcap_cache_time();
2174
2175         if(last_smb_conf_reload_time == 0) {
2176                 last_smb_conf_reload_time = t;
2177                 /* Our printing subsystem might not be ready at smbd start up.
2178                    Then no printer is available till the first printers check
2179                    is performed.  A lower initial interval circumvents this. */
2180                 if ( printcap_cache_time > 60 )
2181                         last_printer_reload_time = t - printcap_cache_time + 60;
2182                 else
2183                         last_printer_reload_time = t;
2184         }
2185
2186         if (mypid != getpid()) { /* First time or fork happened meanwhile */
2187                 /* randomize over 60 second the printcap reload to avoid all
2188                  * process hitting cupsd at the same time */
2189                 int time_range = 60;
2190
2191                 last_printer_reload_time += random() % time_range;
2192                 mypid = getpid();
2193         }
2194
2195         if (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK) {
2196                 reload_services(True);
2197                 last_smb_conf_reload_time = t;
2198         }
2199
2200         /* 'printcap cache time = 0' disable the feature */
2201
2202         if ( printcap_cache_time != 0 )
2203         { 
2204                 /* see if it's time to reload or if the clock has been set back */
2205
2206                 if ( (t >= last_printer_reload_time+printcap_cache_time) 
2207                         || (t-last_printer_reload_time  < 0) ) 
2208                 {
2209                         DEBUG( 3,( "Printcap cache time expired.\n"));
2210                         reload_printers();
2211                         last_printer_reload_time = t;
2212                 }
2213         }
2214 }
2215
2216 static bool fd_is_readable(int fd)
2217 {
2218         fd_set fds;
2219         struct timeval timeout = {0, };
2220         int ret;
2221
2222         FD_ZERO(&fds);
2223         FD_SET(fd, &fds);
2224
2225         ret = sys_select(fd+1, &fds, NULL, NULL, &timeout);
2226         if (ret == -1) {
2227                 return false;
2228         }
2229         return FD_ISSET(fd, &fds);
2230 }
2231
2232 static void smbd_server_connection_write_handler(struct smbd_server_connection *conn)
2233 {
2234         /* TODO: make write nonblocking */
2235 }
2236
2237 static void smbd_server_connection_read_handler(
2238         struct smbd_server_connection *conn, int fd)
2239 {
2240         uint8_t *inbuf = NULL;
2241         size_t inbuf_len = 0;
2242         size_t unread_bytes = 0;
2243         bool encrypted = false;
2244         TALLOC_CTX *mem_ctx = talloc_tos();
2245         NTSTATUS status;
2246         uint32_t seqnum;
2247
2248         bool from_client = (smbd_server_fd() == fd)?true:false;
2249
2250         if (from_client) {
2251                 smbd_lock_socket(conn);
2252
2253                 if (!fd_is_readable(smbd_server_fd())) {
2254                         DEBUG(10,("the echo listener was faster\n"));
2255                         smbd_unlock_socket(conn);
2256                         return;
2257                 }
2258
2259                 /* TODO: make this completely nonblocking */
2260                 status = receive_smb_talloc(mem_ctx, fd,
2261                                             (char **)(void *)&inbuf,
2262                                             0, /* timeout */
2263                                             &unread_bytes,
2264                                             &encrypted,
2265                                             &inbuf_len, &seqnum,
2266                                             false /* trusted channel */);
2267                 smbd_unlock_socket(conn);
2268         } else {
2269                 /* TODO: make this completely nonblocking */
2270                 status = receive_smb_talloc(mem_ctx, fd,
2271                                             (char **)(void *)&inbuf,
2272                                             0, /* timeout */
2273                                             &unread_bytes,
2274                                             &encrypted,
2275                                             &inbuf_len, &seqnum,
2276                                             true /* trusted channel */);
2277         }
2278
2279         if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
2280                 goto process;
2281         }
2282         if (NT_STATUS_IS_ERR(status)) {
2283                 exit_server_cleanly("failed to receive smb request");
2284         }
2285         if (!NT_STATUS_IS_OK(status)) {
2286                 return;
2287         }
2288
2289 process:
2290         process_smb(conn, inbuf, inbuf_len, unread_bytes,
2291                     seqnum, encrypted, NULL);
2292 }
2293
2294 static void smbd_server_connection_handler(struct event_context *ev,
2295                                            struct fd_event *fde,
2296                                            uint16_t flags,
2297                                            void *private_data)
2298 {
2299         struct smbd_server_connection *conn = talloc_get_type(private_data,
2300                                               struct smbd_server_connection);
2301
2302         if (flags & EVENT_FD_WRITE) {
2303                 smbd_server_connection_write_handler(conn);
2304         } else if (flags & EVENT_FD_READ) {
2305                 smbd_server_connection_read_handler(conn, smbd_server_fd());
2306         }
2307 }
2308
2309 static void smbd_server_echo_handler(struct event_context *ev,
2310                                      struct fd_event *fde,
2311                                      uint16_t flags,
2312                                      void *private_data)
2313 {
2314         struct smbd_server_connection *conn = talloc_get_type(private_data,
2315                                               struct smbd_server_connection);
2316
2317         if (flags & EVENT_FD_WRITE) {
2318                 smbd_server_connection_write_handler(conn);
2319         } else if (flags & EVENT_FD_READ) {
2320                 smbd_server_connection_read_handler(
2321                         conn, conn->smb1.echo_handler.trusted_fd);
2322         }
2323 }
2324
2325 /****************************************************************************
2326 received when we should release a specific IP
2327 ****************************************************************************/
2328 static void release_ip(const char *ip, void *priv)
2329 {
2330         char addr[INET6_ADDRSTRLEN];
2331         char *p = addr;
2332
2333         client_socket_addr(get_client_fd(),addr,sizeof(addr));
2334
2335         if (strncmp("::ffff:", addr, 7) == 0) {
2336                 p = addr + 7;
2337         }
2338
2339         if ((strcmp(p, ip) == 0) || ((p != addr) && strcmp(addr, ip) == 0)) {
2340                 /* we can't afford to do a clean exit - that involves
2341                    database writes, which would potentially mean we
2342                    are still running after the failover has finished -
2343                    we have to get rid of this process ID straight
2344                    away */
2345                 DEBUG(0,("Got release IP message for our IP %s - exiting immediately\n",
2346                         ip));
2347                 /* note we must exit with non-zero status so the unclean handler gets
2348                    called in the parent, so that the brl database is tickled */
2349                 _exit(1);
2350         }
2351 }
2352
2353 static void msg_release_ip(struct messaging_context *msg_ctx, void *private_data,
2354                            uint32_t msg_type, struct server_id server_id, DATA_BLOB *data)
2355 {
2356         release_ip((char *)data->data, NULL);
2357 }
2358
2359 #ifdef CLUSTER_SUPPORT
2360 static int client_get_tcp_info(struct sockaddr_storage *server,
2361                                struct sockaddr_storage *client)
2362 {
2363         socklen_t length;
2364         if (server_fd == -1) {
2365                 return -1;
2366         }
2367         length = sizeof(*server);
2368         if (getsockname(server_fd, (struct sockaddr *)server, &length) != 0) {
2369                 return -1;
2370         }
2371         length = sizeof(*client);
2372         if (getpeername(server_fd, (struct sockaddr *)client, &length) != 0) {
2373                 return -1;
2374         }
2375         return 0;
2376 }
2377 #endif
2378
2379 /*
2380  * Send keepalive packets to our client
2381  */
2382 static bool keepalive_fn(const struct timeval *now, void *private_data)
2383 {
2384         bool ret;
2385
2386         smbd_lock_socket(smbd_server_conn);
2387         ret = send_keepalive(smbd_server_fd());
2388         smbd_unlock_socket(smbd_server_conn);
2389
2390         if (!ret) {
2391                 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
2392                 return False;
2393         }
2394         return True;
2395 }
2396
2397 /*
2398  * Do the recurring check if we're idle
2399  */
2400 static bool deadtime_fn(const struct timeval *now, void *private_data)
2401 {
2402         struct smbd_server_connection *sconn = smbd_server_conn;
2403
2404         if (sconn->allow_smb2) {
2405                 /* TODO: implement real idle check */
2406                 if (sconn->smb2.sessions.list) {
2407                         return true;
2408                 }
2409                 DEBUG( 2, ( "Closing idle SMB2 connection\n" ) );
2410                 messaging_send(smbd_messaging_context(), procid_self(),
2411                                MSG_SHUTDOWN, &data_blob_null);
2412                 return false;
2413         }
2414
2415         if ((conn_num_open(sconn) == 0)
2416             || (conn_idle_all(sconn, now->tv_sec))) {
2417                 DEBUG( 2, ( "Closing idle SMB1 connection\n" ) );
2418                 messaging_send(smbd_messaging_context(), procid_self(),
2419                                MSG_SHUTDOWN, &data_blob_null);
2420                 return False;
2421         }
2422
2423         return True;
2424 }
2425
2426 /*
2427  * Do the recurring log file and smb.conf reload checks.
2428  */
2429
2430 static bool housekeeping_fn(const struct timeval *now, void *private_data)
2431 {
2432         change_to_root_user();
2433
2434         /* update printer queue caches if necessary */
2435         update_monitored_printq_cache();
2436
2437         /* check if we need to reload services */
2438         check_reload(time(NULL));
2439
2440         /* Change machine password if neccessary. */
2441         attempt_machine_password_change();
2442
2443         /*
2444          * Force a log file check.
2445          */
2446         force_check_log_size();
2447         check_log_size();
2448         return true;
2449 }
2450
2451 static int create_unlink_tmp(const char *dir)
2452 {
2453         char *fname;
2454         int fd;
2455
2456         fname = talloc_asprintf(talloc_tos(), "%s/listenerlock_XXXXXX", dir);
2457         if (fname == NULL) {
2458                 errno = ENOMEM;
2459                 return -1;
2460         }
2461         fd = mkstemp(fname);
2462         if (fd == -1) {
2463                 TALLOC_FREE(fname);
2464                 return -1;
2465         }
2466         if (unlink(fname) == -1) {
2467                 int sys_errno = errno;
2468                 close(fd);
2469                 TALLOC_FREE(fname);
2470                 errno = sys_errno;
2471                 return -1;
2472         }
2473         TALLOC_FREE(fname);
2474         return fd;
2475 }
2476
2477 struct smbd_echo_state {
2478         struct tevent_context *ev;
2479         struct iovec *pending;
2480         struct smbd_server_connection *sconn;
2481         int parent_pipe;
2482
2483         struct tevent_fd *parent_fde;
2484
2485         struct tevent_fd *read_fde;
2486         struct tevent_req *write_req;
2487 };
2488
2489 static void smbd_echo_writer_done(struct tevent_req *req);
2490
2491 static void smbd_echo_activate_writer(struct smbd_echo_state *state)
2492 {
2493         int num_pending;
2494
2495         if (state->write_req != NULL) {
2496                 return;
2497         }
2498
2499         num_pending = talloc_array_length(state->pending);
2500         if (num_pending == 0) {
2501                 return;
2502         }
2503
2504         state->write_req = writev_send(state, state->ev, NULL,
2505                                        state->parent_pipe, false,
2506                                        state->pending, num_pending);
2507         if (state->write_req == NULL) {
2508                 DEBUG(1, ("writev_send failed\n"));
2509                 exit(1);
2510         }
2511
2512         talloc_steal(state->write_req, state->pending);
2513         state->pending = NULL;
2514
2515         tevent_req_set_callback(state->write_req, smbd_echo_writer_done,
2516                                 state);
2517 }
2518
2519 static void smbd_echo_writer_done(struct tevent_req *req)
2520 {
2521         struct smbd_echo_state *state = tevent_req_callback_data(
2522                 req, struct smbd_echo_state);
2523         ssize_t written;
2524         int err;
2525
2526         written = writev_recv(req, &err);
2527         TALLOC_FREE(req);
2528         state->write_req = NULL;
2529         if (written == -1) {
2530                 DEBUG(1, ("writev to parent failed: %s\n", strerror(err)));
2531                 exit(1);
2532         }
2533         DEBUG(10,("echo_handler[%d]: forwarded pdu to main\n", (int)sys_getpid()));
2534         smbd_echo_activate_writer(state);
2535 }
2536
2537 static bool smbd_echo_reply(int fd,
2538                             uint8_t *inbuf, size_t inbuf_len,
2539                             uint32_t seqnum)
2540 {
2541         struct smb_request req;
2542         uint16_t num_replies;
2543         size_t out_len;
2544         char *outbuf;
2545         bool ok;
2546
2547         if (inbuf_len < smb_size) {
2548                 DEBUG(10, ("Got short packet: %d bytes\n", (int)inbuf_len));
2549                 return false;
2550         }
2551         if (!valid_smb_header(inbuf)) {
2552                 DEBUG(10, ("Got invalid SMB header\n"));
2553                 return false;
2554         }
2555
2556         if (!init_smb_request(&req, inbuf, 0, false, seqnum)) {
2557                 return false;
2558         }
2559         req.inbuf = inbuf;
2560
2561         DEBUG(10, ("smbecho handler got cmd %d (%s)\n", (int)req.cmd,
2562                    smb_messages[req.cmd].name
2563                    ? smb_messages[req.cmd].name : "unknown"));
2564
2565         if (req.cmd != SMBecho) {
2566                 return false;
2567         }
2568         if (req.wct < 1) {
2569                 return false;
2570         }
2571
2572         num_replies = SVAL(req.vwv+0, 0);
2573         if (num_replies != 1) {
2574                 /* Not a Windows "Hey, you're still there?" request */
2575                 return false;
2576         }
2577
2578         if (!create_outbuf(talloc_tos(), &req, (char *)req.inbuf, &outbuf,
2579                            1, req.buflen)) {
2580                 DEBUG(10, ("create_outbuf failed\n"));
2581                 return false;
2582         }
2583         req.outbuf = (uint8_t *)outbuf;
2584
2585         SSVAL(req.outbuf, smb_vwv0, num_replies);
2586
2587         if (req.buflen > 0) {
2588                 memcpy(smb_buf(req.outbuf), req.buf, req.buflen);
2589         }
2590
2591         out_len = smb_len(req.outbuf) + 4;
2592
2593         ok = srv_send_smb(smbd_server_fd(),
2594                           (char *)outbuf,
2595                           true, seqnum+1,
2596                           false, &req.pcd);
2597         TALLOC_FREE(outbuf);
2598         if (!ok) {
2599                 exit(1);
2600         }
2601
2602         return true;
2603 }
2604
2605 static void smbd_echo_exit(struct tevent_context *ev,
2606                            struct tevent_fd *fde, uint16_t flags,
2607                            void *private_data)
2608 {
2609         DEBUG(2, ("smbd_echo_exit: lost connection to parent\n"));
2610         exit(0);
2611 }
2612
2613 static void smbd_echo_reader(struct tevent_context *ev,
2614                              struct tevent_fd *fde, uint16_t flags,
2615                              void *private_data)
2616 {
2617         struct smbd_echo_state *state = talloc_get_type_abort(
2618                 private_data, struct smbd_echo_state);
2619         struct smbd_server_connection *sconn = state->sconn;
2620         size_t unread, num_pending;
2621         NTSTATUS status;
2622         struct iovec *tmp;
2623         uint32_t seqnum = 0;
2624         bool reply;
2625         bool ok;
2626         bool encrypted = false;
2627
2628         ok = smbd_lock_socket_internal(sconn);
2629         if (!ok) {
2630                 DEBUG(0, ("%s: failed to lock socket\n",
2631                         __location__));
2632                 exit(1);
2633         }
2634
2635         if (!fd_is_readable(smbd_server_fd())) {
2636                 DEBUG(10,("echo_handler[%d] the parent smbd was faster\n",
2637                           (int)sys_getpid()));
2638                 ok = smbd_unlock_socket_internal(sconn);
2639                 if (!ok) {
2640                         DEBUG(1, ("%s: failed to unlock socket in\n",
2641                                 __location__));
2642                         exit(1);
2643                 }
2644                 return;
2645         }
2646
2647         num_pending = talloc_array_length(state->pending);
2648         tmp = talloc_realloc(state, state->pending, struct iovec,
2649                              num_pending+1);
2650         if (tmp == NULL) {
2651                 DEBUG(1, ("talloc_realloc failed\n"));
2652                 exit(1);
2653         }
2654         state->pending = tmp;
2655
2656         DEBUG(10,("echo_handler[%d]: reading pdu\n", (int)sys_getpid()));
2657
2658         status = receive_smb_talloc(state, smbd_server_fd(),
2659                                     (char **)(void *)&state->pending[num_pending].iov_base,
2660                                     0 /* timeout */,
2661                                     &unread,
2662                                     &encrypted,
2663                                     &state->pending[num_pending].iov_len,
2664                                     &seqnum,
2665                                     false /* trusted_channel*/);
2666         if (!NT_STATUS_IS_OK(status)) {
2667                 DEBUG(1, ("echo_handler[%d]: receive_smb_raw_talloc failed: %s\n",
2668                           (int)sys_getpid(), nt_errstr(status)));
2669                 exit(1);
2670         }
2671
2672         ok = smbd_unlock_socket_internal(sconn);
2673         if (!ok) {
2674                 DEBUG(1, ("%s: failed to unlock socket in\n",
2675                         __location__));
2676                 exit(1);
2677         }
2678
2679         /*
2680          * place the seqnum in the packet so that the main process can reply
2681          * with signing
2682          */
2683         SIVAL((uint8_t *)state->pending[num_pending].iov_base, smb_ss_field, seqnum);
2684         SIVAL((uint8_t *)state->pending[num_pending].iov_base, smb_ss_field+4, NT_STATUS_V(NT_STATUS_OK));
2685
2686         reply = smbd_echo_reply(smbd_server_fd(),
2687                                 (uint8_t *)state->pending[num_pending].iov_base,
2688                                 state->pending[num_pending].iov_len,
2689                                 seqnum);
2690         if (reply) {
2691                 DEBUG(10,("echo_handler[%d]: replied to client\n", (int)sys_getpid()));
2692                 /* no check, shrinking by some bytes does not fail */
2693                 state->pending = talloc_realloc(state, state->pending,
2694                                                 struct iovec,
2695                                                 num_pending);
2696         } else {
2697                 DEBUG(10,("echo_handler[%d]: forward to main\n", (int)sys_getpid()));
2698                 smbd_echo_activate_writer(state);
2699         }
2700 }
2701
2702 static void smbd_echo_loop(struct smbd_server_connection *sconn,
2703                            int parent_pipe)
2704 {
2705         struct smbd_echo_state *state;
2706
2707         state = talloc_zero(sconn, struct smbd_echo_state);
2708         if (state == NULL) {
2709                 DEBUG(1, ("talloc failed\n"));
2710                 return;
2711         }
2712         state->sconn = sconn;
2713         state->parent_pipe = parent_pipe;
2714         state->ev = s3_tevent_context_init(state);
2715         if (state->ev == NULL) {
2716                 DEBUG(1, ("tevent_context_init failed\n"));
2717                 TALLOC_FREE(state);
2718                 return;
2719         }
2720         state->parent_fde = tevent_add_fd(state->ev, state, parent_pipe,
2721                                         TEVENT_FD_READ, smbd_echo_exit,
2722                                         state);
2723         if (state->parent_fde == NULL) {
2724                 DEBUG(1, ("tevent_add_fd failed\n"));
2725                 TALLOC_FREE(state);
2726                 return;
2727         }
2728         state->read_fde = tevent_add_fd(state->ev, state, smbd_server_fd(),
2729                                         TEVENT_FD_READ, smbd_echo_reader,
2730                                         state);
2731         if (state->read_fde == NULL) {
2732                 DEBUG(1, ("tevent_add_fd failed\n"));
2733                 TALLOC_FREE(state);
2734                 return;
2735         }
2736
2737         while (true) {
2738                 if (tevent_loop_once(state->ev) == -1) {
2739                         DEBUG(1, ("tevent_loop_once failed: %s\n",
2740                                   strerror(errno)));
2741                         break;
2742                 }
2743         }
2744         TALLOC_FREE(state);
2745 }
2746
2747 /*
2748  * Handle SMBecho requests in a forked child process
2749  */
2750 static bool fork_echo_handler(struct smbd_server_connection *sconn)
2751 {
2752         int listener_pipe[2];
2753         int res;
2754         pid_t child;
2755
2756         res = pipe(listener_pipe);
2757         if (res == -1) {
2758                 DEBUG(1, ("pipe() failed: %s\n", strerror(errno)));
2759                 return false;
2760         }
2761         sconn->smb1.echo_handler.socket_lock_fd = create_unlink_tmp(lp_lockdir());
2762         if (sconn->smb1.echo_handler.socket_lock_fd == -1) {
2763                 DEBUG(1, ("Could not create lock fd: %s\n", strerror(errno)));
2764                 goto fail;
2765         }
2766
2767         child = sys_fork();
2768         if (child == 0) {
2769                 NTSTATUS status;
2770
2771                 close(listener_pipe[0]);
2772
2773                 status = reinit_after_fork(smbd_messaging_context(),
2774                                            smbd_event_context(), false);
2775                 if (!NT_STATUS_IS_OK(status)) {
2776                         DEBUG(1, ("reinit_after_fork failed: %s\n",
2777                                   nt_errstr(status)));
2778                         exit(1);
2779                 }
2780                 smbd_echo_loop(sconn, listener_pipe[1]);
2781                 exit(0);
2782         }
2783         close(listener_pipe[1]);
2784         listener_pipe[1] = -1;
2785         sconn->smb1.echo_handler.trusted_fd = listener_pipe[0];
2786
2787         DEBUG(10,("fork_echo_handler: main[%d] echo_child[%d]\n", (int)sys_getpid(), child));
2788
2789         /*
2790          * Without smb signing this is the same as the normal smbd
2791          * listener. This needs to change once signing comes in.
2792          */
2793         sconn->smb1.echo_handler.trusted_fde = event_add_fd(smbd_event_context(),
2794                                         sconn,
2795                                         sconn->smb1.echo_handler.trusted_fd,
2796                                         EVENT_FD_READ,
2797                                         smbd_server_echo_handler,
2798                                         sconn);
2799         if (sconn->smb1.echo_handler.trusted_fde == NULL) {
2800                 DEBUG(1, ("event_add_fd failed\n"));
2801                 goto fail;
2802         }
2803
2804         return true;
2805
2806 fail:
2807         if (listener_pipe[0] != -1) {
2808                 close(listener_pipe[0]);
2809         }
2810         if (listener_pipe[1] != -1) {
2811                 close(listener_pipe[1]);
2812         }
2813         sconn->smb1.echo_handler.trusted_fd = -1;
2814         if (sconn->smb1.echo_handler.socket_lock_fd != -1) {
2815                 close(sconn->smb1.echo_handler.socket_lock_fd);
2816         }
2817         sconn->smb1.echo_handler.trusted_fd = -1;
2818         sconn->smb1.echo_handler.socket_lock_fd = -1;
2819         return false;
2820 }
2821
2822 /****************************************************************************
2823  Process commands from the client
2824 ****************************************************************************/
2825
2826 void smbd_process(void)
2827 {
2828         TALLOC_CTX *frame = talloc_stackframe();
2829         char remaddr[INET6_ADDRSTRLEN];
2830
2831         if (lp_maxprotocol() == PROTOCOL_SMB2 &&
2832             lp_security() != SEC_SHARE &&
2833             !lp_async_smb_echo_handler()) {
2834                 smbd_server_conn->allow_smb2 = true;
2835         }
2836
2837         /* Ensure child is set to blocking mode */
2838         set_blocking(smbd_server_fd(),True);
2839
2840         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
2841         set_socket_options(smbd_server_fd(), lp_socket_options());
2842
2843         /* this is needed so that we get decent entries
2844            in smbstatus for port 445 connects */
2845         set_remote_machine_name(get_peer_addr(smbd_server_fd(),
2846                                               remaddr,
2847                                               sizeof(remaddr)),
2848                                               false);
2849         reload_services(true);
2850
2851         /*
2852          * Before the first packet, check the global hosts allow/ hosts deny
2853          * parameters before doing any parsing of packets passed to us by the
2854          * client. This prevents attacks on our parsing code from hosts not in
2855          * the hosts allow list.
2856          */
2857
2858         if (!check_access(smbd_server_fd(), lp_hostsallow(-1),
2859                           lp_hostsdeny(-1))) {
2860                 char addr[INET6_ADDRSTRLEN];
2861
2862                 /*
2863                  * send a negative session response "not listening on calling
2864                  * name"
2865                  */
2866                 unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
2867                 DEBUG( 1, ("Connection denied from %s\n",
2868                            client_addr(get_client_fd(),addr,sizeof(addr)) ) );
2869                 (void)srv_send_smb(smbd_server_fd(),(char *)buf, false,
2870                                    0, false, NULL);
2871                 exit_server_cleanly("connection denied");
2872         }
2873
2874         static_init_rpc;
2875
2876         init_modules();
2877
2878         smb_perfcount_init();
2879
2880         if (!init_account_policy()) {
2881                 exit_server("Could not open account policy tdb.\n");
2882         }
2883
2884         if (*lp_rootdir()) {
2885                 if (chroot(lp_rootdir()) != 0) {
2886                         DEBUG(0,("Failed to change root to %s\n", lp_rootdir()));
2887                         exit_server("Failed to chroot()");
2888                 }
2889                 if (chdir("/") == -1) {
2890                         DEBUG(0,("Failed to chdir to / on chroot to %s\n", lp_rootdir()));
2891                         exit_server("Failed to chroot()");
2892                 }
2893                 DEBUG(0,("Changed root to %s\n", lp_rootdir()));
2894         }
2895
2896         if (!srv_init_signing(smbd_server_conn)) {
2897                 exit_server("Failed to init smb_signing");
2898         }
2899
2900         if (lp_async_smb_echo_handler() && !fork_echo_handler(smbd_server_conn)) {
2901                 exit_server("Failed to fork echo handler");
2902         }
2903
2904         /* Setup oplocks */
2905         if (!init_oplocks(smbd_messaging_context()))
2906                 exit_server("Failed to init oplocks");
2907
2908         /* register our message handlers */
2909         messaging_register(smbd_messaging_context(), NULL,
2910                            MSG_SMB_FORCE_TDIS, msg_force_tdis);
2911         messaging_register(smbd_messaging_context(), NULL,
2912                            MSG_SMB_RELEASE_IP, msg_release_ip);
2913         messaging_register(smbd_messaging_context(), NULL,
2914                            MSG_SMB_CLOSE_FILE, msg_close_file);
2915
2916         /*
2917          * Use the default MSG_DEBUG handler to avoid rebroadcasting
2918          * MSGs to all child processes
2919          */
2920         messaging_deregister(smbd_messaging_context(),
2921                              MSG_DEBUG, NULL);
2922         messaging_register(smbd_messaging_context(), NULL,
2923                            MSG_DEBUG, debug_message);
2924
2925         if ((lp_keepalive() != 0)
2926             && !(event_add_idle(smbd_event_context(), NULL,
2927                                 timeval_set(lp_keepalive(), 0),
2928                                 "keepalive", keepalive_fn,
2929                                 NULL))) {
2930                 DEBUG(0, ("Could not add keepalive event\n"));
2931                 exit(1);
2932         }
2933
2934         if (!(event_add_idle(smbd_event_context(), NULL,
2935                              timeval_set(IDLE_CLOSED_TIMEOUT, 0),
2936                              "deadtime", deadtime_fn, NULL))) {
2937                 DEBUG(0, ("Could not add deadtime event\n"));
2938                 exit(1);
2939         }
2940
2941         if (!(event_add_idle(smbd_event_context(), NULL,
2942                              timeval_set(SMBD_SELECT_TIMEOUT, 0),
2943                              "housekeeping", housekeeping_fn, NULL))) {
2944                 DEBUG(0, ("Could not add housekeeping event\n"));
2945                 exit(1);
2946         }
2947
2948 #ifdef CLUSTER_SUPPORT
2949
2950         if (lp_clustering()) {
2951                 /*
2952                  * We need to tell ctdb about our client's TCP
2953                  * connection, so that for failover ctdbd can send
2954                  * tickle acks, triggering a reconnection by the
2955                  * client.
2956                  */
2957
2958                 struct sockaddr_storage srv, clnt;
2959
2960                 if (client_get_tcp_info(&srv, &clnt) == 0) {
2961
2962                         NTSTATUS status;
2963
2964                         status = ctdbd_register_ips(
2965                                 messaging_ctdbd_connection(),
2966                                 &srv, &clnt, release_ip, NULL);
2967
2968                         if (!NT_STATUS_IS_OK(status)) {
2969                                 DEBUG(0, ("ctdbd_register_ips failed: %s\n",
2970                                           nt_errstr(status)));
2971                         }
2972                 } else
2973                 {
2974                         DEBUG(0,("Unable to get tcp info for "
2975                                  "CTDB_CONTROL_TCP_CLIENT: %s\n",
2976                                  strerror(errno)));
2977                 }
2978         }
2979
2980 #endif
2981
2982         smbd_server_conn->nbt.got_session = false;
2983
2984         smbd_server_conn->smb1.negprot.max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
2985
2986         smbd_server_conn->smb1.sessions.done_sesssetup = false;
2987         smbd_server_conn->smb1.sessions.max_send = BUFFER_SIZE;
2988         smbd_server_conn->smb1.sessions.last_session_tag = UID_FIELD_INVALID;
2989         /* users from session setup */
2990         smbd_server_conn->smb1.sessions.session_userlist = NULL;
2991         /* workgroup from session setup. */
2992         smbd_server_conn->smb1.sessions.session_workgroup = NULL;
2993         /* this holds info on user ids that are already validated for this VC */
2994         smbd_server_conn->smb1.sessions.validated_users = NULL;
2995         smbd_server_conn->smb1.sessions.next_vuid = VUID_OFFSET;
2996         smbd_server_conn->smb1.sessions.num_validated_vuids = 0;
2997 #ifdef HAVE_NETGROUP
2998         smbd_server_conn->smb1.sessions.my_yp_domain = NULL;
2999 #endif
3000
3001         conn_init(smbd_server_conn);
3002         if (!init_dptrs(smbd_server_conn)) {
3003                 exit_server("init_dptrs() failed");
3004         }
3005
3006         smbd_server_conn->smb1.fde = event_add_fd(smbd_event_context(),
3007                                                   smbd_server_conn,
3008                                                   smbd_server_fd(),
3009                                                   EVENT_FD_READ,
3010                                                   smbd_server_connection_handler,
3011                                                   smbd_server_conn);
3012         if (!smbd_server_conn->smb1.fde) {
3013                 exit_server("failed to create smbd_server_connection fde");
3014         }
3015
3016         TALLOC_FREE(frame);
3017
3018         while (True) {
3019                 NTSTATUS status;
3020
3021                 frame = talloc_stackframe_pool(8192);
3022
3023                 errno = 0;
3024
3025                 status = smbd_server_connection_loop_once(smbd_server_conn);
3026                 if (!NT_STATUS_EQUAL(status, NT_STATUS_RETRY) &&
3027                     !NT_STATUS_IS_OK(status)) {
3028                         DEBUG(3, ("smbd_server_connection_loop_once failed: %s,"
3029                                   " exiting\n", nt_errstr(status)));
3030                         break;
3031                 }
3032
3033                 TALLOC_FREE(frame);
3034         }
3035
3036         exit_server_cleanly(NULL);
3037 }
3038
3039 bool req_is_in_chain(struct smb_request *req)
3040 {
3041         if (req->vwv != (uint16_t *)(req->inbuf+smb_vwv)) {
3042                 /*
3043                  * We're right now handling a subsequent request, so we must
3044                  * be in a chain
3045                  */
3046                 return true;
3047         }
3048
3049         if (!is_andx_req(req->cmd)) {
3050                 return false;
3051         }
3052
3053         if (req->wct < 2) {
3054                 /*
3055                  * Okay, an illegal request, but definitely not chained :-)
3056                  */
3057                 return false;
3058         }
3059
3060         return (CVAL(req->vwv+0, 0) != 0xFF);
3061 }