s4-process_model: Panic if the standard init function fails
[samba.git] / source4 / smbd / process_standard.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    process model: standard (1 process per client connection)
5
6    Copyright (C) Andrew Tridgell 1992-2005
7    Copyright (C) James J Myers 2003 <myersjj@samba.org>
8    Copyright (C) Stefan (metze) Metzmacher 2004
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 #include "lib/events/events.h"
26 #include "smbd/process_model.h"
27 #include "system/filesys.h"
28 #include "cluster/cluster.h"
29 #include "param/param.h"
30 #include "ldb_wrap.h"
31
32 struct standard_child_state {
33         const char *name;
34         pid_t pid;
35         int to_parent_fd;
36         int from_child_fd;
37         struct tevent_fd *from_child_fde;
38 };
39
40 NTSTATUS process_model_standard_init(void);
41
42 /* we hold a pipe open in the parent, and the any child
43    processes wait for EOF on that pipe. This ensures that
44    children die when the parent dies */
45 static int child_pipe[2] = { -1, -1 };
46
47 /*
48   called when the process model is selected
49 */
50 static void standard_model_init(void)
51 {
52         int rc;
53
54         rc = pipe(child_pipe);
55         if (rc < 0) {
56                 smb_panic("Failed to initialze pipe!");
57         }
58 }
59
60 /*
61   handle EOF on the parent-to-all-children pipe in the child
62 */
63 static void standard_pipe_handler(struct tevent_context *event_ctx, struct tevent_fd *fde, 
64                                   uint16_t flags, void *private_data)
65 {
66         DEBUG(10,("Child %d exiting\n", (int)getpid()));
67         exit(0);
68 }
69
70 /*
71   handle EOF on the child pipe in the parent, so we know when a
72   process terminates without using SIGCHLD or waiting on all possible pids.
73
74   We need to ensure we do not ignore SIGCHLD because we need it to
75   work to get a valid error code from samba_runcmd_*().
76  */
77 static void standard_child_pipe_handler(struct tevent_context *ev,
78                                         struct tevent_fd *fde,
79                                         uint16_t flags,
80                                         void *private_data)
81 {
82         struct standard_child_state *state
83                 = talloc_get_type_abort(private_data, struct standard_child_state);
84         int status = 0;
85         pid_t pid;
86
87         /* the child has closed the pipe, assume its dead */
88         errno = 0;
89         pid = waitpid(state->pid, &status, 0);
90
91         if (pid != state->pid) {
92                 if (errno == ECHILD) {
93                         /*
94                          * this happens when the
95                          * parent has set SIGCHLD to
96                          * SIG_IGN. In that case we
97                          * can only get error
98                          * information for the child
99                          * via its logging. We should
100                          * stop using SIG_IGN on
101                          * SIGCHLD in the standard
102                          * process model.
103                          */
104                         DEBUG(0, ("Error in waitpid() unexpectedly got ECHILD "
105                                   "for child %d (%s) - %s, someone has set SIGCHLD "
106                                   "to SIG_IGN!\n",
107                                   state->pid, state->name, strerror(errno)));
108                         TALLOC_FREE(state);
109                         return;
110                 }
111                 DEBUG(0, ("Error in waitpid() for child %d (%s) - %s \n",
112                           state->pid, state->name, strerror(errno)));
113                 if (errno == 0) {
114                         errno = ECHILD;
115                 }
116                 TALLOC_FREE(state);
117                 return;
118         }
119         if (WIFEXITED(status)) {
120                 status = WEXITSTATUS(status);
121                 DEBUG(2, ("Child %d (%s) exited with status %d\n",
122                           state->pid, state->name, status));
123         } else if (WIFSIGNALED(status)) {
124                 status = WTERMSIG(status);
125                 DEBUG(0, ("Child %d (%s) terminated with signal %d\n",
126                           state->pid, state->name, status));
127         }
128         TALLOC_FREE(state);
129         return;
130 }
131
132 static struct standard_child_state *setup_standard_child_pipe(struct tevent_context *ev,
133                                                               const char *name)
134 {
135         struct standard_child_state *state;
136         int parent_child_pipe[2];
137         int ret;
138
139         /*
140          * Prepare a pipe to allow us to know when the child exits,
141          * because it will trigger a read event on this private
142          * pipe.
143          *
144          * We do all this before the accept and fork(), so we can
145          * clean up if it fails.
146          */
147         state = talloc_zero(ev, struct standard_child_state);
148         if (state == NULL) {
149                 return NULL;
150         }
151
152         if (name == NULL) {
153                 name = "";
154         }
155
156         state->name = talloc_strdup(state, name);
157         if (state->name == NULL) {
158                 TALLOC_FREE(state);
159                 return NULL;
160         }
161
162         ret = pipe(parent_child_pipe);
163         if (ret == -1) {
164                 DEBUG(0, ("Failed to create parent-child pipe to handle "
165                           "SIGCHLD to track new process for socket\n"));
166                 TALLOC_FREE(state);
167                 return NULL;
168         }
169
170         smb_set_close_on_exec(parent_child_pipe[0]);
171         smb_set_close_on_exec(parent_child_pipe[1]);
172
173         state->from_child_fd = parent_child_pipe[0];
174         state->to_parent_fd = parent_child_pipe[1];
175
176         /*
177          * The basic purpose of calling this handler is to ensure we
178          * call waitpid() and so avoid zombies (now that we no longer
179          * user SIGIGN on for SIGCHLD), but it also allows us to clean
180          * up other resources in the future.
181          */
182         state->from_child_fde = tevent_add_fd(ev, state,
183                                               state->from_child_fd,
184                                               TEVENT_FD_READ,
185                                               standard_child_pipe_handler,
186                                               state);
187         if (state->from_child_fde == NULL) {
188                 TALLOC_FREE(state);
189                 return NULL;
190         }
191         tevent_fd_set_auto_close(state->from_child_fde);
192
193         return state;
194 }
195
196 /*
197   called when a listening socket becomes readable. 
198 */
199 static void standard_accept_connection(struct tevent_context *ev, 
200                                        struct loadparm_context *lp_ctx,
201                                        struct socket_context *sock, 
202                                        void (*new_conn)(struct tevent_context *,
203                                                         struct loadparm_context *, struct socket_context *, 
204                                                         struct server_id , void *), 
205                                        void *private_data)
206 {
207         NTSTATUS status;
208         struct socket_context *sock2;
209         pid_t pid;
210         struct socket_address *c, *s;
211         struct standard_child_state *state;
212
213         state = setup_standard_child_pipe(ev, NULL);
214         if (state == NULL) {
215                 return;
216         }
217
218         /* accept an incoming connection. */
219         status = socket_accept(sock, &sock2);
220         if (!NT_STATUS_IS_OK(status)) {
221                 DEBUG(0,("standard_accept_connection: accept: %s\n",
222                          nt_errstr(status)));
223                 /* this looks strange, but is correct. We need to throttle things until
224                    the system clears enough resources to handle this new socket */
225                 sleep(1);
226                 close(state->to_parent_fd);
227                 state->to_parent_fd = -1;
228                 TALLOC_FREE(state);
229                 return;
230         }
231
232         pid = fork();
233
234         if (pid != 0) {
235                 close(state->to_parent_fd);
236                 state->to_parent_fd = -1;
237
238                 if (pid > 0) {
239                         state->pid = pid;
240                 } else {
241                         TALLOC_FREE(state);
242                 }
243
244                 /* parent or error code ... */
245                 talloc_free(sock2);
246                 /* go back to the event loop */
247                 return;
248         }
249
250         /* this leaves state->to_parent_fd open */
251         TALLOC_FREE(state);
252
253         pid = getpid();
254
255         /* This is now the child code. We need a completely new event_context to work with */
256
257         if (tevent_re_initialise(ev) != 0) {
258                 smb_panic("Failed to re-initialise tevent after fork");
259         }
260
261         /* this will free all the listening sockets and all state that
262            is not associated with this new connection */
263         talloc_free(sock);
264
265         /* we don't care if the dup fails, as its only a select()
266            speed optimisation */
267         socket_dup(sock2);
268                         
269         /* tdb needs special fork handling */
270         ldb_wrap_fork_hook();
271
272         tevent_add_fd(ev, ev, child_pipe[0], TEVENT_FD_READ,
273                       standard_pipe_handler, NULL);
274         if (child_pipe[1] != -1) {
275                 close(child_pipe[1]);
276                 child_pipe[1] = -1;
277         }
278
279         /* Ensure that the forked children do not expose identical random streams */
280         set_need_random_reseed();
281
282         /* setup the process title */
283         c = socket_get_peer_addr(sock2, ev);
284         s = socket_get_my_addr(sock2, ev);
285         if (s && c) {
286                 setproctitle("conn c[%s:%u] s[%s:%u] server_id[%d]",
287                              c->addr, c->port, s->addr, s->port, (int)pid);
288         }
289         talloc_free(c);
290         talloc_free(s);
291
292         /* setup this new connection.  Cluster ID is PID based for this process model */
293         new_conn(ev, lp_ctx, sock2, cluster_id(pid, 0), private_data);
294
295         /* we can't return to the top level here, as that event context is gone,
296            so we now process events in the new event context until there are no
297            more to process */      
298         tevent_loop_wait(ev);
299
300         talloc_free(ev);
301         exit(0);
302 }
303
304 /*
305   called to create a new server task
306 */
307 static void standard_new_task(struct tevent_context *ev, 
308                               struct loadparm_context *lp_ctx,
309                               const char *service_name,
310                               void (*new_task)(struct tevent_context *, struct loadparm_context *lp_ctx, struct server_id , void *),
311                               void *private_data)
312 {
313         pid_t pid;
314         struct standard_child_state *state;
315
316         state = setup_standard_child_pipe(ev, service_name);
317         if (state == NULL) {
318                 return;
319         }
320
321         pid = fork();
322
323         if (pid != 0) {
324                 close(state->to_parent_fd);
325                 state->to_parent_fd = -1;
326
327                 if (pid > 0) {
328                         state->pid = pid;
329                 } else {
330                         TALLOC_FREE(state);
331                 }
332
333                 /* parent or error code ... go back to the event loop */
334                 return;
335         }
336
337         /* this leaves state->to_parent_fd open */
338         TALLOC_FREE(state);
339
340         pid = getpid();
341
342         /* this will free all the listening sockets and all state that
343            is not associated with this new connection */
344         if (tevent_re_initialise(ev) != 0) {
345                 smb_panic("Failed to re-initialise tevent after fork");
346         }
347
348         /* ldb/tdb need special fork handling */
349         ldb_wrap_fork_hook();
350
351         tevent_add_fd(ev, ev, child_pipe[0], TEVENT_FD_READ,
352                       standard_pipe_handler, NULL);
353         if (child_pipe[1] != -1) {
354                 close(child_pipe[1]);
355                 child_pipe[1] = -1;
356         }
357
358         /* Ensure that the forked children do not expose identical random streams */
359         set_need_random_reseed();
360
361         setproctitle("task %s server_id[%d]", service_name, (int)pid);
362
363         /* setup this new task.  Cluster ID is PID based for this process model */
364         new_task(ev, lp_ctx, cluster_id(pid, 0), private_data);
365
366         /* we can't return to the top level here, as that event context is gone,
367            so we now process events in the new event context until there are no
368            more to process */      
369         tevent_loop_wait(ev);
370
371         talloc_free(ev);
372         exit(0);
373 }
374
375
376 /* called when a task goes down */
377 _NORETURN_ static void standard_terminate(struct tevent_context *ev, struct loadparm_context *lp_ctx,
378                                           const char *reason) 
379 {
380         DEBUG(2,("standard_terminate: reason[%s]\n",reason));
381
382         talloc_free(ev);
383
384         /* this reload_charcnv() has the effect of freeing the iconv context memory,
385            which makes leak checking easier */
386         reload_charcnv(lp_ctx);
387
388         /* terminate this process */
389         exit(0);
390 }
391
392 /* called to set a title of a task or connection */
393 static void standard_set_title(struct tevent_context *ev, const char *title) 
394 {
395         if (title) {
396                 setproctitle("%s", title);
397         } else {
398                 setproctitle(NULL);
399         }
400 }
401
402 static const struct model_ops standard_ops = {
403         .name                   = "standard",
404         .model_init             = standard_model_init,
405         .accept_connection      = standard_accept_connection,
406         .new_task               = standard_new_task,
407         .terminate              = standard_terminate,
408         .set_title              = standard_set_title,
409 };
410
411 /*
412   initialise the standard process model, registering ourselves with the process model subsystem
413  */
414 NTSTATUS process_model_standard_init(void)
415 {
416         return register_process_model(&standard_ops);
417 }