25e2d2cb5e5706c78d6dedcc3f29a2d83a4e9f34
[samba.git] / source3 / smbd / server.c
1 /*
2    Unix SMB/CIFS implementation.
3    Main SMB server routines
4    Copyright (C) Andrew Tridgell                1992-1998
5    Copyright (C) Martin Pool                    2002
6    Copyright (C) Jelmer Vernooij                2002-2003
7    Copyright (C) Volker Lendecke                1993-2007
8    Copyright (C) Jeremy Allison                 1993-2007
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25
26 static_decl_rpc;
27
28 static int am_parent = 1;
29
30 /* the last message the was processed */
31 int last_message = -1;
32
33 /* a useful macro to debug the last message processed */
34 #define LAST_MESSAGE() smb_fn_name(last_message)
35
36 extern struct auth_context *negprot_global_auth_context;
37 extern pstring user_socket_options;
38 extern SIG_ATOMIC_T got_sig_term;
39 extern SIG_ATOMIC_T reload_after_sighup;
40 static SIG_ATOMIC_T got_sig_cld;
41
42 extern int smb_read_error;
43
44 #ifdef WITH_DFS
45 extern int dcelogin_atmost_once;
46 #endif /* WITH_DFS */
47
48 /* really we should have a top level context structure that has the
49    client file descriptor as an element. That would require a major rewrite :(
50
51    the following 2 functions are an alternative - they make the file
52    descriptor private to smbd
53  */
54 static int server_fd = -1;
55
56 int smbd_server_fd(void)
57 {
58         return server_fd;
59 }
60
61 static void smbd_set_server_fd(int fd)
62 {
63         server_fd = fd;
64         client_setfd(fd);
65 }
66
67 /* Socket functions for smbd packet processing. */
68
69 static bool valid_packet_size(len)
70 {
71         /*
72          * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
73          * of header. Don't print the error if this fits.... JRA.
74          */
75
76         if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
77                 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
78                                         (unsigned long)len));
79                 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
80
81                         /*
82                          * Correct fix. smb_read_error may have already been
83                          * set. Only set it here if not already set. Global
84                          * variables still suck :-). JRA.
85                          */
86
87                         if (smb_read_error == 0)
88                                 smb_read_error = READ_ERROR;
89                         return false;
90                 }
91         }
92         return true;
93 }
94
95 static ssize_t read_packet_remainder(int fd,
96                                         char *buffer,
97                                         unsigned int timeout,
98                                         ssize_t len)
99 {
100         ssize_t ret;
101
102         if(len <= 0) {
103                 return len;
104         }
105
106         if (timeout > 0) {
107                 ret = read_socket_with_timeout(fd,
108                                                 buffer,
109                                                 len,
110                                                 len,
111                                                 timeout);
112         } else {
113                 ret = read_data(fd, buffer, len);
114         }
115
116         if (ret != len) {
117                 if (smb_read_error == 0) {
118                         smb_read_error = READ_ERROR;
119                 }
120                 return -1;
121         }
122
123         return len;
124 }
125
126 /****************************************************************************
127  Attempt a zerocopy writeX read. We know here that len > smb_size-4
128 ****************************************************************************/
129
130 /*
131  * Unfortunately, earlier versions of smbclient/libsmbclient
132  * don't send this "standard" writeX header. I've fixed this
133  * for 3.2 but we'll use the old method with earlier versions.
134  * Windows and CIFSFS at least use this standard size. Not
135  * sure about MacOSX.
136  */
137
138 #define STANDARD_WRITE_AND_X_HEADER_SIZE (smb_size - 4 + /* basic header */ \
139                                 (2*14) + /* word count (including bcc) */ \
140                                 1 /* pad byte */)
141
142 ssize_t receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
143                                         const char lenbuf[4],
144                                         int fd,
145                                         char **buffer,
146                                         unsigned int timeout,
147                                         size_t *p_unread)
148 {
149         /* Size of a WRITEX call (+4 byte len). */
150         char writeX_header[4 + STANDARD_WRITE_AND_X_HEADER_SIZE];
151         ssize_t len = smb_len(lenbuf);
152         ssize_t toread;
153         ssize_t ret;
154
155         memcpy(writeX_header, lenbuf, sizeof(lenbuf));
156
157         if (timeout > 0) {
158                 ret = read_socket_with_timeout(fd,
159                                         writeX_header + 4,
160                                         STANDARD_WRITE_AND_X_HEADER_SIZE,
161                                         STANDARD_WRITE_AND_X_HEADER_SIZE,
162                                         timeout);
163         } else {
164                 ret = read_data(fd,
165                                 writeX_header+4,
166                                 STANDARD_WRITE_AND_X_HEADER_SIZE);
167         }
168
169         if (ret != STANDARD_WRITE_AND_X_HEADER_SIZE) {
170                 if (smb_read_error == 0) {
171                         smb_read_error = READ_ERROR;
172                 }
173                 return -1;
174         }
175
176         /*
177          * Ok - now try and see if this is a possible
178          * valid writeX call.
179          */
180
181         if (is_valid_writeX_buffer(writeX_header)) {
182                 /*
183                  * If the data offset is beyond what
184                  * we've read, drain the extra bytes.
185                  */
186                 uint16_t doff = SVAL(writeX_header,smb_vwv11);
187                 ssize_t newlen;
188
189                 if (doff > STANDARD_WRITE_AND_X_HEADER_SIZE) {
190                         size_t drain = doff - STANDARD_WRITE_AND_X_HEADER_SIZE;
191                         if (drain_socket(smbd_server_fd(), drain) != drain) {
192                                 smb_panic("receive_smb_raw_talloc_partial_read:"
193                                         " failed to drain pending bytes");
194                         }
195                 } else {
196                         doff = STANDARD_WRITE_AND_X_HEADER_SIZE;
197                 }
198
199                 /* Spoof down the length and null out the bcc. */
200                 set_message_bcc(writeX_header, 0);
201                 newlen = smb_len(writeX_header);
202
203                 /* Copy the header we've written. */
204
205                 *buffer = TALLOC_MEMDUP(mem_ctx,
206                                 writeX_header,
207                                 sizeof(writeX_header));
208
209                 if (*buffer == NULL) {
210                         DEBUG(0, ("Could not allocate inbuf of length %d\n",
211                                   (int)sizeof(writeX_header)));
212                         if (smb_read_error == 0)
213                                 smb_read_error = READ_ERROR;
214                         return -1;
215                 }
216
217                 /* Work out the remaining bytes. */
218                 *p_unread = len - STANDARD_WRITE_AND_X_HEADER_SIZE;
219
220                 return newlen + 4;
221         }
222
223         if (!valid_packet_size(len)) {
224                 return -1;
225         }
226
227         /*
228          * Not a valid writeX call. Just do the standard
229          * talloc and return.
230          */
231
232         *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
233
234         if (*buffer == NULL) {
235                 DEBUG(0, ("Could not allocate inbuf of length %d\n",
236                           (int)len+4));
237                 if (smb_read_error == 0)
238                         smb_read_error = READ_ERROR;
239                 return -1;
240         }
241
242         /* Copy in what we already read. */
243         memcpy(*buffer,
244                 writeX_header,
245                 4 + STANDARD_WRITE_AND_X_HEADER_SIZE);
246         toread = len - STANDARD_WRITE_AND_X_HEADER_SIZE;
247
248         if(toread > 0) {
249                 ret = read_packet_remainder(fd,
250                         (*buffer) + 4 + STANDARD_WRITE_AND_X_HEADER_SIZE,
251                                         timeout,
252                                         toread);
253                 if (ret != toread) {
254                         return -1;
255                 }
256         }
257
258         return len + 4;
259 }
260
261 static ssize_t receive_smb_raw_talloc(TALLOC_CTX *mem_ctx,
262                                         int fd,
263                                         char **buffer,
264                                         unsigned int timeout,
265                                         size_t *p_unread)
266 {
267         char lenbuf[4];
268         ssize_t len,ret;
269         int min_recv_size = lp_min_receive_file_size();
270
271         smb_read_error = 0;
272         *p_unread = 0;
273
274         len = read_smb_length_return_keepalive(fd, lenbuf, timeout);
275         if (len < 0) {
276                 DEBUG(10,("receive_smb_raw: length < 0!\n"));
277
278                 /*
279                  * Correct fix. smb_read_error may have already been
280                  * set. Only set it here if not already set. Global
281                  * variables still suck :-). JRA.
282                  */
283
284                 if (smb_read_error == 0)
285                         smb_read_error = READ_ERROR;
286                 return -1;
287         }
288
289         if (CVAL(lenbuf,0) != SMBkeepalive &&
290                         min_recv_size &&
291                         len > min_recv_size &&
292                         !srv_is_signing_active()) {
293
294                 return receive_smb_raw_talloc_partial_read(mem_ctx,
295                                                         lenbuf,
296                                                         fd,
297                                                         buffer,
298                                                         timeout,
299                                                         p_unread);
300         }
301
302         if (!valid_packet_size(len)) {
303                 return -1;
304         }
305
306         /*
307          * The +4 here can't wrap, we've checked the length above already.
308          */
309
310         *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
311
312         if (*buffer == NULL) {
313                 DEBUG(0, ("Could not allocate inbuf of length %d\n",
314                           (int)len+4));
315                 if (smb_read_error == 0)
316                         smb_read_error = READ_ERROR;
317                 return -1;
318         }
319
320         memcpy(*buffer, lenbuf, sizeof(lenbuf));
321
322         ret = read_packet_remainder(fd, (*buffer)+4, timeout, len);
323         if (ret != len) {
324                 return -1;
325         }
326
327         return len + 4;
328 }
329
330 ssize_t receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd, char **buffer,
331                            unsigned int timeout, size_t *p_unread)
332 {
333         ssize_t len;
334
335         len = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout, p_unread);
336
337         if (len < 0) {
338                 return -1;
339         }
340
341         /* Check the incoming SMB signature. */
342         if (!srv_check_sign_mac(*buffer, true)) {
343                 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
344                           "incoming packet!\n"));
345                 if (smb_read_error == 0) {
346                         smb_read_error = READ_BAD_SIG;
347                 }
348                 return -1;
349         }
350
351         return len;
352 }
353
354 struct event_context *smbd_event_context(void)
355 {
356         static struct event_context *ctx;
357
358         if (!ctx && !(ctx = event_context_init(NULL))) {
359                 smb_panic("Could not init smbd event context");
360         }
361         return ctx;
362 }
363
364 struct messaging_context *smbd_messaging_context(void)
365 {
366         static struct messaging_context *ctx;
367
368         if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
369                                            smbd_event_context()))) {
370                 smb_panic("Could not init smbd messaging context");
371         }
372         return ctx;
373 }
374
375 /*******************************************************************
376  What to do when smb.conf is updated.
377  ********************************************************************/
378
379 static void smb_conf_updated(struct messaging_context *msg,
380                              void *private_data,
381                              uint32_t msg_type,
382                              struct server_id server_id,
383                              DATA_BLOB *data)
384 {
385         DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
386                   "updated. Reloading.\n"));
387         reload_services(False);
388 }
389
390
391 /*******************************************************************
392  Delete a statcache entry.
393  ********************************************************************/
394
395 static void smb_stat_cache_delete(struct messaging_context *msg,
396                                   void *private_data,
397                                   uint32_t msg_tnype,
398                                   struct server_id server_id,
399                                   DATA_BLOB *data)
400 {
401         const char *name = (const char *)data->data;
402         DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
403         stat_cache_delete(name);
404 }
405
406 /****************************************************************************
407  Terminate signal.
408 ****************************************************************************/
409
410 static void sig_term(void)
411 {
412         got_sig_term = 1;
413         sys_select_signal(SIGTERM);
414 }
415
416 /****************************************************************************
417  Catch a sighup.
418 ****************************************************************************/
419
420 static void sig_hup(int sig)
421 {
422         reload_after_sighup = 1;
423         sys_select_signal(SIGHUP);
424 }
425
426 /****************************************************************************
427  Catch a sigcld
428 ****************************************************************************/
429 static void sig_cld(int sig)
430 {
431         got_sig_cld = 1;
432         sys_select_signal(SIGCLD);
433 }
434
435 /****************************************************************************
436   Send a SIGTERM to our process group.
437 *****************************************************************************/
438
439 static void  killkids(void)
440 {
441         if(am_parent) kill(0,SIGTERM);
442 }
443
444 /****************************************************************************
445  Process a sam sync message - not sure whether to do this here or
446  somewhere else.
447 ****************************************************************************/
448
449 static void msg_sam_sync(struct messaging_context *msg,
450                          void *private_data,
451                          uint32_t msg_type,
452                          struct server_id server_id,
453                          DATA_BLOB *data)
454 {
455         DEBUG(10, ("** sam sync message received, ignoring\n"));
456 }
457
458
459 /****************************************************************************
460  Open the socket communication - inetd.
461 ****************************************************************************/
462
463 static bool open_sockets_inetd(void)
464 {
465         /* Started from inetd. fd 0 is the socket. */
466         /* We will abort gracefully when the client or remote system 
467            goes away */
468         smbd_set_server_fd(dup(0));
469         
470         /* close our standard file descriptors */
471         close_low_fds(False); /* Don't close stderr */
472         
473         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
474         set_socket_options(smbd_server_fd(), user_socket_options);
475
476         return True;
477 }
478
479 static void msg_exit_server(struct messaging_context *msg,
480                             void *private_data,
481                             uint32_t msg_type,
482                             struct server_id server_id,
483                             DATA_BLOB *data)
484 {
485         DEBUG(3, ("got a SHUTDOWN message\n"));
486         exit_server_cleanly(NULL);
487 }
488
489 #ifdef DEVELOPER
490 static void msg_inject_fault(struct messaging_context *msg,
491                              void *private_data,
492                              uint32_t msg_type,
493                              struct server_id src,
494                              DATA_BLOB *data)
495 {
496         int sig;
497
498         if (data->length != sizeof(sig)) {
499                 
500                 DEBUG(0, ("Process %s sent bogus signal injection request\n",
501                           procid_str_static(&src)));
502                 return;
503         }
504
505         sig = *(int *)data->data;
506         if (sig == -1) {
507                 exit_server("internal error injected");
508                 return;
509         }
510
511 #if HAVE_STRSIGNAL
512         DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
513                   procid_str_static(&src), sig, strsignal(sig)));
514 #else
515         DEBUG(0, ("Process %s requested injection of signal %d\n",
516                   procid_str_static(&src), sig));
517 #endif
518
519         kill(sys_getpid(), sig);
520 }
521 #endif /* DEVELOPER */
522
523 struct child_pid {
524         struct child_pid *prev, *next;
525         pid_t pid;
526 };
527
528 static struct child_pid *children;
529 static int num_children;
530
531 static void add_child_pid(pid_t pid)
532 {
533         struct child_pid *child;
534
535         if (lp_max_smbd_processes() == 0) {
536                 /* Don't bother with the child list if we don't care anyway */
537                 return;
538         }
539
540         child = SMB_MALLOC_P(struct child_pid);
541         if (child == NULL) {
542                 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
543                 return;
544         }
545         child->pid = pid;
546         DLIST_ADD(children, child);
547         num_children += 1;
548 }
549
550 static void remove_child_pid(pid_t pid)
551 {
552         struct child_pid *child;
553
554         if (lp_max_smbd_processes() == 0) {
555                 /* Don't bother with the child list if we don't care anyway */
556                 return;
557         }
558
559         for (child = children; child != NULL; child = child->next) {
560                 if (child->pid == pid) {
561                         struct child_pid *tmp = child;
562                         DLIST_REMOVE(children, child);
563                         SAFE_FREE(tmp);
564                         num_children -= 1;
565                         return;
566                 }
567         }
568
569         DEBUG(0, ("Could not find child %d -- ignoring\n", (int)pid));
570 }
571
572 /****************************************************************************
573  Have we reached the process limit ?
574 ****************************************************************************/
575
576 static bool allowable_number_of_smbd_processes(void)
577 {
578         int max_processes = lp_max_smbd_processes();
579
580         if (!max_processes)
581                 return True;
582
583         return num_children < max_processes;
584 }
585
586 /****************************************************************************
587  Open the socket communication.
588 ****************************************************************************/
589
590 static bool open_sockets_smbd(bool is_daemon, bool interactive, const char *smb_ports)
591 {
592         int num_interfaces = iface_count();
593         int num_sockets = 0;
594         int fd_listenset[FD_SETSIZE];
595         fd_set listen_set;
596         int s;
597         int maxfd = 0;
598         int i;
599         char *ports;
600
601         if (!is_daemon) {
602                 return open_sockets_inetd();
603         }
604
605 #ifdef HAVE_ATEXIT
606         {
607                 static int atexit_set;
608                 if(atexit_set == 0) {
609                         atexit_set=1;
610                         atexit(killkids);
611                 }
612         }
613 #endif
614
615         /* Stop zombies */
616         CatchSignal(SIGCLD, sig_cld);
617
618         FD_ZERO(&listen_set);
619
620         /* use a reasonable default set of ports - listing on 445 and 139 */
621         if (!smb_ports) {
622                 ports = lp_smb_ports();
623                 if (!ports || !*ports) {
624                         ports = smb_xstrdup(SMB_PORTS);
625                 } else {
626                         ports = smb_xstrdup(ports);
627                 }
628         } else {
629                 ports = smb_xstrdup(smb_ports);
630         }
631
632         if (lp_interfaces() && lp_bind_interfaces_only()) {
633                 /* We have been given an interfaces line, and been
634                    told to only bind to those interfaces. Create a
635                    socket per interface and bind to only these.
636                 */
637
638                 /* Now open a listen socket for each of the
639                    interfaces. */
640                 for(i = 0; i < num_interfaces; i++) {
641                         const struct sockaddr_storage *ifss =
642                                         iface_n_sockaddr_storage(i);
643                         fstring tok;
644                         const char *ptr;
645
646                         if (ifss == NULL) {
647                                 DEBUG(0,("open_sockets_smbd: "
648                                         "interface %d has NULL IP address !\n",
649                                         i));
650                                 continue;
651                         }
652
653                         for (ptr=ports; next_token(&ptr, tok, " \t,",
654                                                 sizeof(tok)); ) {
655                                 unsigned port = atoi(tok);
656                                 if (port == 0 || port > 0xffff) {
657                                         continue;
658                                 }
659                                 s = fd_listenset[num_sockets] =
660                                         open_socket_in(SOCK_STREAM, port, 0,
661                                                         ifss, True);
662                                 if(s == -1) {
663                                         continue;
664                                 }
665
666                                 /* ready to listen */
667                                 set_socket_options(s,"SO_KEEPALIVE");
668                                 set_socket_options(s,user_socket_options);
669
670                                 /* Set server socket to
671                                  * non-blocking for the accept. */
672                                 set_blocking(s,False);
673
674                                 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
675                                         DEBUG(0,("open_sockets_smbd: listen: "
676                                                 "%s\n", strerror(errno)));
677                                         close(s);
678                                         return False;
679                                 }
680                                 FD_SET(s,&listen_set);
681                                 maxfd = MAX( maxfd, s);
682
683                                 num_sockets++;
684                                 if (num_sockets >= FD_SETSIZE) {
685                                         DEBUG(0,("open_sockets_smbd: Too "
686                                                 "many sockets to bind to\n"));
687                                         return False;
688                                 }
689                         }
690                 }
691         } else {
692                 /* Just bind to 0.0.0.0 - accept connections
693                    from anywhere. */
694
695                 fstring tok;
696                 const char *ptr;
697                 const char *sock_addr = lp_socket_address();
698                 fstring sock_tok;
699                 const char *sock_ptr;
700
701                 if (strequal(sock_addr, "0.0.0.0") ||
702                                 strequal(sock_addr, "::")) {
703 #if HAVE_IPV6
704                         sock_addr = "::,0.0.0.0";
705 #else
706                         sock_addr = "0.0.0.0";
707 #endif
708                 }
709
710                 for (sock_ptr=sock_addr; next_token(&sock_ptr, sock_tok, " \t,",
711                                         sizeof(sock_tok)); ) {
712                         for (ptr=ports; next_token(&ptr, tok, " \t,",
713                                                 sizeof(tok)); ) {
714                                 struct sockaddr_storage ss;
715
716                                 unsigned port = atoi(tok);
717                                 if (port == 0 || port > 0xffff) {
718                                         continue;
719                                 }
720                                 /* open an incoming socket */
721                                 if (!interpret_string_addr(&ss, sock_tok,
722                                                 AI_NUMERICHOST|AI_PASSIVE)) {
723                                         continue;
724                                 }
725
726                                 s = open_socket_in(SOCK_STREAM, port, 0,
727                                                    &ss, true);
728                                 if (s == -1) {
729                                         continue;
730                                 }
731
732                                 /* ready to listen */
733                                 set_socket_options(s,"SO_KEEPALIVE");
734                                 set_socket_options(s,user_socket_options);
735
736                                 /* Set server socket to non-blocking
737                                  * for the accept. */
738                                 set_blocking(s,False);
739
740                                 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
741                                         DEBUG(0,("open_sockets_smbd: "
742                                                 "listen: %s\n",
743                                                  strerror(errno)));
744                                         close(s);
745                                         return False;
746                                 }
747
748                                 fd_listenset[num_sockets] = s;
749                                 FD_SET(s,&listen_set);
750                                 maxfd = MAX( maxfd, s);
751
752                                 num_sockets++;
753
754                                 if (num_sockets >= FD_SETSIZE) {
755                                         DEBUG(0,("open_sockets_smbd: Too "
756                                                 "many sockets to bind to\n"));
757                                         return False;
758                                 }
759                         }
760                 }
761         }
762
763         SAFE_FREE(ports);
764
765         if (num_sockets == 0) {
766                 DEBUG(0,("open_sockets_smbd: No "
767                         "sockets available to bind to.\n"));
768                 return false;
769         }
770
771         /* Setup the main smbd so that we can get messages. Note that
772            do this after starting listening. This is needed as when in
773            clustered mode, ctdb won't allow us to start doing database
774            operations until it has gone thru a full startup, which
775            includes checking to see that smbd is listening. */
776         claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
777
778         /* Listen to messages */
779
780         messaging_register(smbd_messaging_context(), NULL,
781                            MSG_SMB_SAM_SYNC, msg_sam_sync);
782         messaging_register(smbd_messaging_context(), NULL,
783                            MSG_SHUTDOWN, msg_exit_server);
784         messaging_register(smbd_messaging_context(), NULL,
785                            MSG_SMB_FILE_RENAME, msg_file_was_renamed);
786         messaging_register(smbd_messaging_context(), NULL,
787                            MSG_SMB_CONF_UPDATED, smb_conf_updated);
788         messaging_register(smbd_messaging_context(), NULL,
789                            MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
790         brl_register_msgs(smbd_messaging_context());
791
792 #ifdef DEVELOPER
793         messaging_register(smbd_messaging_context(), NULL,
794                            MSG_SMB_INJECT_FAULT, msg_inject_fault);
795 #endif
796
797         /* now accept incoming connections - forking a new process
798            for each incoming connection */
799         DEBUG(2,("waiting for a connection\n"));
800         while (1) {
801                 struct timeval now, idle_timeout;
802                 fd_set r_fds, w_fds;
803                 int num;
804
805                 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
806                 message_dispatch(smbd_messaging_context());
807
808                 if (got_sig_cld) {
809                         pid_t pid;
810                         got_sig_cld = False;
811
812                         while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
813                                 remove_child_pid(pid);
814                         }
815                 }
816
817                 idle_timeout = timeval_zero();
818
819                 memcpy((char *)&r_fds, (char *)&listen_set,
820                        sizeof(listen_set));
821                 FD_ZERO(&w_fds);
822                 GetTimeOfDay(&now);
823
824                 event_add_to_select_args(smbd_event_context(), &now,
825                                          &r_fds, &w_fds, &idle_timeout,
826                                          &maxfd);
827
828                 num = sys_select(maxfd+1,&r_fds,&w_fds,NULL,
829                                  timeval_is_zero(&idle_timeout) ?
830                                  NULL : &idle_timeout);
831
832                 if (num == -1 && errno == EINTR) {
833                         if (got_sig_term) {
834                                 exit_server_cleanly(NULL);
835                         }
836
837                         /* check for sighup processing */
838                         if (reload_after_sighup) {
839                                 change_to_root_user();
840                                 DEBUG(1,("Reloading services after SIGHUP\n"));
841                                 reload_services(False);
842                                 reload_after_sighup = 0;
843                         }
844
845                         continue;
846                 }
847
848                 if (run_events(smbd_event_context(), num, &r_fds, &w_fds)) {
849                         continue;
850                 }
851
852                 /* check if we need to reload services */
853                 check_reload(time(NULL));
854
855                 /* Find the sockets that are read-ready -
856                    accept on these. */
857                 for( ; num > 0; num--) {
858                         struct sockaddr addr;
859                         socklen_t in_addrlen = sizeof(addr);
860                         pid_t child = 0;
861
862                         s = -1;
863                         for(i = 0; i < num_sockets; i++) {
864                                 if(FD_ISSET(fd_listenset[i],&r_fds)) {
865                                         s = fd_listenset[i];
866                                         /* Clear this so we don't look
867                                            at it again. */
868                                         FD_CLR(fd_listenset[i],&r_fds);
869                                         break;
870                                 }
871                         }
872
873                         smbd_set_server_fd(accept(s,&addr,&in_addrlen));
874
875                         if (smbd_server_fd() == -1 && errno == EINTR)
876                                 continue;
877
878                         if (smbd_server_fd() == -1) {
879                                 DEBUG(0,("open_sockets_smbd: accept: %s\n",
880                                          strerror(errno)));
881                                 continue;
882                         }
883
884                         /* Ensure child is set to blocking mode */
885                         set_blocking(smbd_server_fd(),True);
886
887                         if (smbd_server_fd() != -1 && interactive)
888                                 return True;
889
890                         if (allowable_number_of_smbd_processes() &&
891                             smbd_server_fd() != -1 &&
892                             ((child = sys_fork())==0)) {
893                                 /* Child code ... */
894
895                                 /* Stop zombies, the parent explicitly handles
896                                  * them, counting worker smbds. */
897                                 CatchChild();
898
899                                 /* close the listening socket(s) */
900                                 for(i = 0; i < num_sockets; i++)
901                                         close(fd_listenset[i]);
902
903                                 /* close our standard file
904                                    descriptors */
905                                 close_low_fds(False);
906                                 am_parent = 0;
907
908                                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
909                                 set_socket_options(smbd_server_fd(),user_socket_options);
910
911                                 /* this is needed so that we get decent entries
912                                    in smbstatus for port 445 connects */
913                                 set_remote_machine_name(get_peer_addr(smbd_server_fd()),
914                                                         False);
915
916                                 /* Reset the state of the random
917                                  * number generation system, so
918                                  * children do not get the same random
919                                  * numbers as each other */
920
921                                 set_need_random_reseed();
922                                 /* tdb needs special fork handling - remove
923                                  * CLEAR_IF_FIRST flags */
924                                 if (tdb_reopen_all(1) == -1) {
925                                         DEBUG(0,("tdb_reopen_all failed.\n"));
926                                         smb_panic("tdb_reopen_all failed");
927                                 }
928
929                                 return True;
930                         }
931                         /* The parent doesn't need this socket */
932                         close(smbd_server_fd());
933
934                         /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
935                                 Clear the closed fd info out of server_fd --
936                                 and more importantly, out of client_fd in
937                                 util_sock.c, to avoid a possible
938                                 getpeername failure if we reopen the logs
939                                 and use %I in the filename.
940                         */
941
942                         smbd_set_server_fd(-1);
943
944                         if (child != 0) {
945                                 add_child_pid(child);
946                         }
947
948                         /* Force parent to check log size after
949                          * spawning child.  Fix from
950                          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
951                          * parent smbd will log to logserver.smb.  It
952                          * writes only two messages for each child
953                          * started/finished. But each child writes,
954                          * say, 50 messages also in logserver.smb,
955                          * begining with the debug_count of the
956                          * parent, before the child opens its own log
957                          * file logserver.client. In a worst case
958                          * scenario the size of logserver.smb would be
959                          * checked after about 50*50=2500 messages
960                          * (ca. 100kb).
961                          * */
962                         force_check_log_size();
963
964                 } /* end for num */
965         } /* end while 1 */
966
967 /* NOTREACHED   return True; */
968 }
969
970 /****************************************************************************
971  Reload printers
972 **************************************************************************/
973 void reload_printers(void)
974 {
975         int snum;
976         int n_services = lp_numservices();
977         int pnum = lp_servicenumber(PRINTERS_NAME);
978         const char *pname;
979
980         pcap_cache_reload();
981
982         /* remove stale printers */
983         for (snum = 0; snum < n_services; snum++) {
984                 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
985                 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
986                                       lp_autoloaded(snum)))
987                         continue;
988
989                 pname = lp_printername(snum);
990                 if (!pcap_printername_ok(pname)) {
991                         DEBUG(3, ("removing stale printer %s\n", pname));
992
993                         if (is_printer_published(NULL, snum, NULL))
994                                 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
995                         del_a_printer(pname);
996                         lp_killservice(snum);
997                 }
998         }
999
1000         load_printers();
1001 }
1002
1003 /****************************************************************************
1004  Reload the services file.
1005 **************************************************************************/
1006
1007 bool reload_services(bool test)
1008 {
1009         bool ret;
1010         
1011         if (lp_loaded()) {
1012                 pstring fname;
1013                 pstrcpy(fname,lp_configfile());
1014                 if (file_exist(fname, NULL) &&
1015                     !strcsequal(fname, dyn_CONFIGFILE)) {
1016                         pstrcpy(dyn_CONFIGFILE, fname);
1017                         test = False;
1018                 }
1019         }
1020
1021         reopen_logs();
1022
1023         if (test && !lp_file_list_changed())
1024                 return(True);
1025
1026         lp_killunused(conn_snum_used);
1027
1028         ret = lp_load(dyn_CONFIGFILE, False, False, True, True);
1029
1030         reload_printers();
1031
1032         /* perhaps the config filename is now set */
1033         if (!test)
1034                 reload_services(True);
1035
1036         reopen_logs();
1037
1038         load_interfaces();
1039
1040         if (smbd_server_fd() != -1) {      
1041                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
1042                 set_socket_options(smbd_server_fd(), user_socket_options);
1043         }
1044
1045         mangle_reset_cache();
1046         reset_stat_cache();
1047
1048         /* this forces service parameters to be flushed */
1049         set_current_service(NULL,0,True);
1050
1051         return(ret);
1052 }
1053
1054 /****************************************************************************
1055  Exit the server.
1056 ****************************************************************************/
1057
1058 /* Reasons for shutting down a server process. */
1059 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
1060
1061 static void exit_server_common(enum server_exit_reason how,
1062         const char *const reason) NORETURN_ATTRIBUTE;
1063
1064 static void exit_server_common(enum server_exit_reason how,
1065         const char *const reason)
1066 {
1067         static int firsttime=1;
1068
1069         if (!firsttime)
1070                 exit(0);
1071         firsttime = 0;
1072
1073         change_to_root_user();
1074
1075         if (negprot_global_auth_context) {
1076                 (negprot_global_auth_context->free)(&negprot_global_auth_context);
1077         }
1078
1079         conn_close_all();
1080
1081         invalidate_all_vuids();
1082
1083         /* 3 second timeout. */
1084         print_notify_send_messages(smbd_messaging_context(), 3);
1085
1086         /* delete our entry in the connections database. */
1087         yield_connection(NULL,"");
1088
1089         respond_to_all_remaining_local_messages();
1090
1091 #ifdef WITH_DFS
1092         if (dcelogin_atmost_once) {
1093                 dfs_unlogin();
1094         }
1095 #endif
1096
1097         locking_end();
1098         printing_end();
1099
1100         if (how != SERVER_EXIT_NORMAL) {
1101                 int oldlevel = DEBUGLEVEL;
1102
1103                 DEBUGLEVEL = 10;
1104
1105                 DEBUGSEP(0);
1106                 DEBUG(0,("Abnormal server exit: %s\n",
1107                         reason ? reason : "no explanation provided"));
1108                 DEBUGSEP(0);
1109
1110                 log_stack_trace();
1111
1112                 DEBUGLEVEL = oldlevel;
1113                 dump_core();
1114
1115         } else {    
1116                 DEBUG(3,("Server exit (%s)\n",
1117                         (reason ? reason : "normal exit")));
1118         }
1119
1120         exit(0);
1121 }
1122
1123 void exit_server(const char *const explanation)
1124 {
1125         exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
1126 }
1127
1128 void exit_server_cleanly(const char *const explanation)
1129 {
1130         exit_server_common(SERVER_EXIT_NORMAL, explanation);
1131 }
1132
1133 void exit_server_fault(void)
1134 {
1135         exit_server("critical server fault");
1136 }
1137
1138 /****************************************************************************
1139  Initialise connect, service and file structs.
1140 ****************************************************************************/
1141
1142 static bool init_structs(void )
1143 {
1144         /*
1145          * Set the machine NETBIOS name if not already
1146          * set from the config file.
1147          */
1148
1149         if (!init_names())
1150                 return False;
1151
1152         conn_init();
1153
1154         file_init();
1155
1156         /* for RPC pipes */
1157         init_rpc_pipe_hnd();
1158
1159         init_dptrs();
1160
1161         secrets_init();
1162
1163         return True;
1164 }
1165
1166 /*
1167  * Send keepalive packets to our client
1168  */
1169 static bool keepalive_fn(const struct timeval *now, void *private_data)
1170 {
1171         if (!send_keepalive(smbd_server_fd())) {
1172                 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
1173                 return False;
1174         }
1175         return True;
1176 }
1177
1178 /*
1179  * Do the recurring check if we're idle
1180  */
1181 static bool deadtime_fn(const struct timeval *now, void *private_data)
1182 {
1183         if ((conn_num_open() == 0)
1184             || (conn_idle_all(now->tv_sec))) {
1185                 DEBUG( 2, ( "Closing idle connection\n" ) );
1186                 messaging_send(smbd_messaging_context(), procid_self(),
1187                                MSG_SHUTDOWN, &data_blob_null);
1188                 return False;
1189         }
1190
1191         return True;
1192 }
1193
1194
1195 /****************************************************************************
1196  main program.
1197 ****************************************************************************/
1198
1199 /* Declare prototype for build_options() to avoid having to run it through
1200    mkproto.h.  Mixing $(builddir) and $(srcdir) source files in the current
1201    prototype generation system is too complicated. */
1202
1203 extern void build_options(bool screen);
1204
1205  int main(int argc,const char *argv[])
1206 {
1207         /* shall I run as a daemon */
1208         static bool is_daemon = False;
1209         static bool interactive = False;
1210         static bool Fork = True;
1211         static bool no_process_group = False;
1212         static bool log_stdout = False;
1213         static char *ports = NULL;
1214         static char *profile_level = NULL;
1215         int opt;
1216         poptContext pc;
1217         bool print_build_options = False;
1218         enum {
1219                 OPT_DAEMON = 1000,
1220                 OPT_INTERACTIVE,
1221                 OPT_FORK,
1222                 OPT_NO_PROCESS_GROUP,
1223                 OPT_LOG_STDOUT
1224         };
1225         struct poptOption long_options[] = {
1226         POPT_AUTOHELP
1227         {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1228         {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
1229         {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
1230         {"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1231         {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1232         {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
1233         {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
1234         {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
1235         POPT_COMMON_SAMBA
1236         POPT_COMMON_DYNCONFIG
1237         POPT_TABLEEND
1238         };
1239
1240         load_case_tables();
1241
1242         TimeInit();
1243
1244 #ifdef HAVE_SET_AUTH_PARAMETERS
1245         set_auth_parameters(argc,argv);
1246 #endif
1247
1248         pc = poptGetContext("smbd", argc, argv, long_options, 0);
1249         while((opt = poptGetNextOpt(pc)) != -1) {
1250                 switch (opt)  {
1251                 case OPT_DAEMON:
1252                         is_daemon = true;
1253                         break;
1254                 case OPT_INTERACTIVE:
1255                         interactive = true;
1256                         break;
1257                 case OPT_FORK:
1258                         Fork = false;
1259                         break;
1260                 case OPT_NO_PROCESS_GROUP:
1261                         no_process_group = true;
1262                         break;
1263                 case OPT_LOG_STDOUT:
1264                         log_stdout = true;
1265                         break;
1266                 case 'b':
1267                         print_build_options = True;
1268                         break;
1269                 default:
1270                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1271                                   poptBadOption(pc, 0), poptStrerror(opt));
1272                         poptPrintUsage(pc, stderr, 0);
1273                         exit(1);
1274                 }
1275         }
1276         poptFreeContext(pc);
1277
1278         if (print_build_options) {
1279                 build_options(True); /* Display output to screen as well as debug */
1280                 exit(0);
1281         }
1282
1283 #ifdef HAVE_SETLUID
1284         /* needed for SecureWare on SCO */
1285         setluid(0);
1286 #endif
1287
1288         sec_init();
1289
1290         set_remote_machine_name("smbd", False);
1291
1292         if (interactive) {
1293                 Fork = False;
1294                 log_stdout = True;
1295         }
1296
1297         if (interactive && (DEBUGLEVEL >= 9)) {
1298                 talloc_enable_leak_report();
1299         }
1300
1301         if (log_stdout && Fork) {
1302                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
1303                 exit(1);
1304         }
1305
1306         setup_logging(argv[0],log_stdout);
1307
1308         /* we want to re-seed early to prevent time delays causing
1309            client problems at a later date. (tridge) */
1310         generate_random_buffer(NULL, 0);
1311
1312         /* make absolutely sure we run as root - to handle cases where people
1313            are crazy enough to have it setuid */
1314
1315         gain_root_privilege();
1316         gain_root_group_privilege();
1317
1318         fault_setup((void (*)(void *))exit_server_fault);
1319         dump_core_setup("smbd");
1320
1321         CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
1322         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
1323         
1324         /* we are never interested in SIGPIPE */
1325         BlockSignals(True,SIGPIPE);
1326
1327 #if defined(SIGFPE)
1328         /* we are never interested in SIGFPE */
1329         BlockSignals(True,SIGFPE);
1330 #endif
1331
1332 #if defined(SIGUSR2)
1333         /* We are no longer interested in USR2 */
1334         BlockSignals(True,SIGUSR2);
1335 #endif
1336
1337         /* POSIX demands that signals are inherited. If the invoking process has
1338          * these signals masked, we will have problems, as we won't recieve them. */
1339         BlockSignals(False, SIGHUP);
1340         BlockSignals(False, SIGUSR1);
1341         BlockSignals(False, SIGTERM);
1342
1343         /* we want total control over the permissions on created files,
1344            so set our umask to 0 */
1345         umask(0);
1346
1347         init_sec_ctx();
1348
1349         reopen_logs();
1350
1351         DEBUG(0,("smbd version %s started.\n", SAMBA_VERSION_STRING));
1352         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1353
1354         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
1355                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
1356
1357         /* Output the build options to the debug log */ 
1358         build_options(False);
1359
1360         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
1361                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
1362                 exit(1);
1363         }
1364
1365         /*
1366          * Do this before reload_services.
1367          */
1368
1369         if (!reload_services(False))
1370                 return(-1);     
1371
1372         init_structs();
1373
1374 #ifdef WITH_PROFILE
1375         if (!profile_setup(smbd_messaging_context(), False)) {
1376                 DEBUG(0,("ERROR: failed to setup profiling\n"));
1377                 return -1;
1378         }
1379         if (profile_level != NULL) {
1380                 int pl = atoi(profile_level);
1381                 struct server_id src;
1382
1383                 DEBUG(1, ("setting profiling level: %s\n",profile_level));
1384                 src.pid = getpid();
1385                 set_profile_level(pl, src);
1386         }
1387 #endif
1388
1389         DEBUG(3,( "loaded services\n"));
1390
1391         if (!is_daemon && !is_a_socket(0)) {
1392                 if (!interactive)
1393                         DEBUG(0,("standard input is not a socket, assuming -D option\n"));
1394
1395                 /*
1396                  * Setting is_daemon here prevents us from eventually calling
1397                  * the open_sockets_inetd()
1398                  */
1399
1400                 is_daemon = True;
1401         }
1402
1403         if (is_daemon && !interactive) {
1404                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
1405                 become_daemon(Fork, no_process_group);
1406         }
1407
1408 #if HAVE_SETPGID
1409         /*
1410          * If we're interactive we want to set our own process group for
1411          * signal management.
1412          */
1413         if (interactive && !no_process_group)
1414                 setpgid( (pid_t)0, (pid_t)0);
1415 #endif
1416
1417         if (!directory_exist(lp_lockdir(), NULL))
1418                 mkdir(lp_lockdir(), 0755);
1419
1420         if (is_daemon)
1421                 pidfile_create("smbd");
1422
1423         /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1424
1425         if (smbd_messaging_context() == NULL)
1426                 exit(1);
1427
1428         /* Initialise the password backed before the global_sam_sid
1429            to ensure that we fetch from ldap before we make a domain sid up */
1430
1431         if(!initialize_password_db(False, smbd_event_context()))
1432                 exit(1);
1433
1434         if (!secrets_init()) {
1435                 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1436                 exit(1);
1437         }
1438
1439         if(!get_global_sam_sid()) {
1440                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1441                 exit(1);
1442         }
1443
1444         if (!session_init())
1445                 exit(1);
1446
1447         if (!connections_init(True))
1448                 exit(1);
1449
1450         if (!locking_init(0))
1451                 exit(1);
1452
1453         namecache_enable();
1454
1455         if (!init_registry())
1456                 exit(1);
1457
1458 #if 0
1459         if (!init_svcctl_db())
1460                 exit(1);
1461 #endif
1462
1463         if (!print_backend_init(smbd_messaging_context()))
1464                 exit(1);
1465
1466         if (!init_guest_info()) {
1467                 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1468                 return -1;
1469         }
1470
1471         /* only start the background queue daemon if we are 
1472            running as a daemon -- bad things will happen if
1473            smbd is launched via inetd and we fork a copy of 
1474            ourselves here */
1475
1476         if ( is_daemon && !interactive )
1477                 start_background_queue(); 
1478
1479         /* Always attempt to initialize DMAPI. We will only use it later if
1480          * lp_dmapi_support is set on the share, but we need a single global
1481          * session to work with.
1482          */
1483         dmapi_init_session();
1484
1485         if (!open_sockets_smbd(is_daemon, interactive, ports))
1486                 exit(1);
1487
1488         /*
1489          * everything after this point is run after the fork()
1490          */ 
1491
1492         static_init_rpc;
1493
1494         init_modules();
1495
1496         /* Possibly reload the services file. Only worth doing in
1497          * daemon mode. In inetd mode, we know we only just loaded this.
1498          */
1499         if (is_daemon) {
1500                 reload_services(True);
1501         }
1502
1503         if (!init_account_policy()) {
1504                 DEBUG(0,("Could not open account policy tdb.\n"));
1505                 exit(1);
1506         }
1507
1508         if (*lp_rootdir()) {
1509                 if (sys_chroot(lp_rootdir()) == 0)
1510                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
1511         }
1512
1513         /* Setup oplocks */
1514         if (!init_oplocks(smbd_messaging_context()))
1515                 exit(1);
1516         
1517         /* Setup aio signal handler. */
1518         initialize_async_io_handler();
1519
1520         /*
1521          * For clustering, we need to re-init our ctdbd connection after the
1522          * fork
1523          */
1524         if (!NT_STATUS_IS_OK(messaging_reinit(smbd_messaging_context())))
1525                 exit(1);
1526
1527         /* register our message handlers */
1528         messaging_register(smbd_messaging_context(), NULL,
1529                            MSG_SMB_FORCE_TDIS, msg_force_tdis);
1530
1531         if ((lp_keepalive() != 0)
1532             && !(event_add_idle(smbd_event_context(), NULL,
1533                                 timeval_set(lp_keepalive(), 0),
1534                                 "keepalive", keepalive_fn,
1535                                 NULL))) {
1536                 DEBUG(0, ("Could not add keepalive event\n"));
1537                 exit(1);
1538         }
1539
1540         if (!(event_add_idle(smbd_event_context(), NULL,
1541                              timeval_set(IDLE_CLOSED_TIMEOUT, 0),
1542                              "deadtime", deadtime_fn, NULL))) {
1543                 DEBUG(0, ("Could not add deadtime event\n"));
1544                 exit(1);
1545         }
1546
1547         smbd_process();
1548
1549         namecache_shutdown();
1550
1551         exit_server_cleanly(NULL);
1552         return(0);
1553 }