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