r1486: commit the start of the generic server infastructure
[samba.git] / source4 / smbd / process_thread.c
1 /* 
2    Unix SMB/CIFS implementation.
3    thread model: standard (1 thread per client connection)
4    Copyright (C) Andrew Tridgell 2003
5    Copyright (C) James J Myers 2003 <myersjj@samba.org>
6    Copyright (C) Stefan (metze) Metzmacher 2004
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24 #include "pthread.h"
25 #ifdef HAVE_BACKTRACE
26 #include "execinfo.h"
27 #endif
28
29 static void *thread_connection_fn(void *thread_parm)
30 {
31         struct event_context *ev = thread_parm;
32         /* wait for action */
33         event_loop_wait(ev);
34
35 #if 0
36         pthread_cleanup_pop(1);  /* will invoke terminate_mt_connection() */
37 #endif
38         return NULL;
39 }
40
41 static int thread_get_id(struct smbsrv_request *req)
42 {
43         return (int)pthread_self();
44 }
45
46 /*
47   called when a listening socket becomes readable
48 */
49 static void thread_accept_connection(struct event_context *ev, struct fd_event *srv_fde, 
50                               time_t t, uint16_t flags)
51 {               
52         int accepted_fd, rc;
53         struct sockaddr addr;
54         socklen_t in_addrlen = sizeof(addr);
55         pthread_t thread_id;
56         pthread_attr_t thread_attr;
57         struct fd_event fde;
58         struct timed_event idle;
59         struct server_socket *server_socket = srv_fde->private;
60         struct server_connection *conn;
61         TALLOC_CTX *mem_ctx;
62
63         /* accept an incoming connection. */
64         accepted_fd = accept(srv_fde->fd,&addr,&in_addrlen);
65         if (accepted_fd == -1) {
66                 DEBUG(0,("standard_accept_connection: accept: %s\n",
67                          strerror(errno)));
68                 return;
69         }
70         
71         /* create new detached thread for this connection.  The new
72            thread gets a new event_context with a single fd_event for
73            receiving from the new socket. We set that thread running
74            with the main event loop, then return. When we return the
75            main event_context is continued.
76         */
77
78
79         ev = event_context_init();
80         if (!ev) {
81                 DEBUG(0,("thread_accept_connection: failed to create event_context!\n"));
82                 return; 
83         }
84
85         mem_ctx = talloc_init("server_service_connection");
86         if (!mem_ctx) {
87                 DEBUG(0,("talloc_init(server_service_connection) failed\n"));
88                 return;
89         }
90
91         conn = talloc_p(mem_ctx, struct server_connection);
92         if (!conn) {
93                 DEBUG(0,("talloc_p(mem_ctx, struct server_service_connection) failed\n"));
94                 talloc_destroy(mem_ctx);
95                 return;
96         }
97
98         ZERO_STRUCTP(conn);
99         conn->mem_ctx = mem_ctx;
100
101         fde.private     = conn;
102         fde.fd          = accepted_fd;
103         fde.flags       = EVENT_FD_READ;
104         fde.handler     = server_io_handler;
105
106         idle.private    = conn;
107         idle.next_event = t + 300;
108         idle.handler    = server_idle_handler;
109
110         conn->event.ctx         = ev;
111         conn->event.fde         = &fde;
112         conn->event.idle        = &idle;
113         conn->event.idle_time   = 300;
114
115         conn->server_socket     = server_socket;
116         conn->service           = server_socket->service;
117
118         /* TODO: we need a generic socket subsystem */
119         conn->socket            = talloc_p(conn->mem_ctx, struct socket_context);
120         if (!conn->socket) {
121                 DEBUG(0,("talloc_p(conn->mem_ctx, struct socket_context) failed\n"));
122                 talloc_destroy(mem_ctx);
123                 return;
124         }
125         conn->socket->private_data      = NULL;
126         conn->socket->ops               = NULL;
127         conn->socket->client_addr       = NULL;
128         conn->socket->pkt_count         = 0;
129         conn->socket->fde               = conn->event.fde;
130
131         /* create a smb server context and add it to out event
132            handling */
133         server_socket->service->ops->accept_connection(conn);
134
135         /* accpect_connection() of the service may changed idle.next_event */
136         conn->event.fde         = event_add_fd(ev,&fde);
137         conn->event.idle        = event_add_timed(ev,&idle);
138
139         conn->socket->fde       = conn->event.fde;
140
141         /* TODO: is this MUTEX_LOCK in the right place here?
142          *       --metze
143          */
144         MUTEX_LOCK_BY_ID(MUTEX_SMBD);
145         DLIST_ADD(server_socket->connection_list,conn);
146         MUTEX_UNLOCK_BY_ID(MUTEX_SMBD);
147         
148         pthread_attr_init(&thread_attr);
149         pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
150         rc = pthread_create(&thread_id, &thread_attr, thread_connection_fn, ev);
151         pthread_attr_destroy(&thread_attr);
152         if (rc == 0) {
153                 DEBUG(4,("accept_connection_thread: created thread_id=%lu for fd=%d\n", 
154                         (unsigned long int)thread_id, accepted_fd));
155         } else {
156                 DEBUG(0,("accept_connection_thread: thread create failed for fd=%d, rc=%d\n", accepted_fd, rc));
157         }
158 }
159
160 /* called when a SMB connection goes down */
161 static void thread_terminate_connection(struct server_connection *conn, const char *reason) 
162 {
163         DEBUG(0,("thread_terminate_connection: reason[%s]\n",reason));
164         conn->service->ops->close_connection(conn,reason);
165         /* terminate this thread */
166         pthread_exit(NULL);  /* thread cleanup routine will do actual cleanup */
167 }
168
169 /*
170   mutex init function for thread model
171 */
172 static int thread_mutex_init(smb_mutex_t *mutex, const char *name)
173 {
174         pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
175         mutex->mutex = memdup(&m, sizeof(m));
176         if (! mutex->mutex) {
177                 errno = ENOMEM;
178                 return -1;
179         }
180         return pthread_mutex_init((pthread_mutex_t *)mutex->mutex, NULL);
181 }
182
183 /*
184   mutex destroy function for thread model
185 */
186 static int thread_mutex_destroy(smb_mutex_t *mutex, const char *name)
187 {
188         return pthread_mutex_destroy((pthread_mutex_t *)mutex->mutex);
189 }
190
191 static void mutex_start_timer(struct timeval *tp1)
192 {
193         gettimeofday(tp1,NULL);
194 }
195
196 static double mutex_end_timer(struct timeval tp1)
197 {
198         struct timeval tp2;
199         gettimeofday(&tp2,NULL);
200         return((tp2.tv_sec - tp1.tv_sec) + 
201                (tp2.tv_usec - tp1.tv_usec)*1.0e-6);
202 }
203
204 /*
205   mutex lock function for thread model
206 */
207 static int thread_mutex_lock(smb_mutex_t *mutexP, const char *name)
208 {
209         pthread_mutex_t *mutex = (pthread_mutex_t *)mutexP->mutex;
210         int rc;
211         double t;
212         struct timeval tp1;
213         /* Test below is ONLY for debugging */
214         if ((rc = pthread_mutex_trylock(mutex))) {
215                 if (rc == EBUSY) {
216                         mutex_start_timer(&tp1);
217                         printf("mutex lock: thread %d, lock %s not available\n", 
218                                 (uint32_t)pthread_self(), name);
219                         print_suspicious_usage("mutex_lock", name);
220                         pthread_mutex_lock(mutex);
221                         t = mutex_end_timer(tp1);
222                         printf("mutex lock: thread %d, lock %s now available, waited %g seconds\n", 
223                                 (uint32_t)pthread_self(), name, t);
224                         return 0;
225                 }
226                 printf("mutex lock: thread %d, lock %s failed rc=%d\n", 
227                                 (uint32_t)pthread_self(), name, rc);
228                 SMB_ASSERT(errno == 0); /* force error */
229         }
230         return 0;
231 }
232
233 /* 
234    mutex unlock for thread model
235 */
236 static int thread_mutex_unlock(smb_mutex_t *mutex, const char *name)
237 {
238         return pthread_mutex_unlock((pthread_mutex_t *)mutex->mutex);
239 }
240
241 /*****************************************************************
242  Read/write lock routines.
243 *****************************************************************/  
244 /*
245   rwlock init function for thread model
246 */
247 static int thread_rwlock_init(smb_rwlock_t *rwlock, const char *name)
248 {
249         pthread_rwlock_t m = PTHREAD_RWLOCK_INITIALIZER;
250         rwlock->rwlock = memdup(&m, sizeof(m));
251         if (! rwlock->rwlock) {
252                 errno = ENOMEM;
253                 return -1;
254         }
255         return pthread_rwlock_init((pthread_rwlock_t *)rwlock->rwlock, NULL);
256 }
257
258 /*
259   rwlock destroy function for thread model
260 */
261 static int thread_rwlock_destroy(smb_rwlock_t *rwlock, const char *name)
262 {
263         return pthread_rwlock_destroy((pthread_rwlock_t *)rwlock->rwlock);
264 }
265
266 /*
267   rwlock lock for read function for thread model
268 */
269 static int thread_rwlock_lock_read(smb_rwlock_t *rwlockP, const char *name)
270 {
271         pthread_rwlock_t *rwlock = (pthread_rwlock_t *)rwlockP->rwlock;
272         int rc;
273         double t;
274         struct timeval tp1;
275         /* Test below is ONLY for debugging */
276         if ((rc = pthread_rwlock_tryrdlock(rwlock))) {
277                 if (rc == EBUSY) {
278                         mutex_start_timer(&tp1);
279                         printf("rwlock lock_read: thread %d, lock %s not available\n", 
280                                 (uint32_t)pthread_self(), name);
281                         print_suspicious_usage("rwlock_lock_read", name);
282                         pthread_rwlock_rdlock(rwlock);
283                         t = mutex_end_timer(tp1);
284                         printf("rwlock lock_read: thread %d, lock %s now available, waited %g seconds\n", 
285                                 (uint32_t)pthread_self(), name, t);
286                         return 0;
287                 }
288                 printf("rwlock lock_read: thread %d, lock %s failed rc=%d\n", 
289                                 (uint32_t)pthread_self(), name, rc);
290                 SMB_ASSERT(errno == 0); /* force error */
291         }
292         return 0;
293 }
294
295 /*
296   rwlock lock for write function for thread model
297 */
298 static int thread_rwlock_lock_write(smb_rwlock_t *rwlockP, const char *name)
299 {
300         pthread_rwlock_t *rwlock = (pthread_rwlock_t *)rwlockP->rwlock;
301         int rc;
302         double t;
303         struct timeval tp1;
304         /* Test below is ONLY for debugging */
305         if ((rc = pthread_rwlock_trywrlock(rwlock))) {
306                 if (rc == EBUSY) {
307                         mutex_start_timer(&tp1);
308                         printf("rwlock lock_write: thread %d, lock %s not available\n", 
309                                 (uint32_t)pthread_self(), name);
310                         print_suspicious_usage("rwlock_lock_write", name);
311                         pthread_rwlock_wrlock(rwlock);
312                         t = mutex_end_timer(tp1);
313                         printf("rwlock lock_write: thread %d, lock %s now available, waited %g seconds\n", 
314                                 (uint32_t)pthread_self(), name, t);
315                         return 0;
316                 }
317                 printf("rwlock lock_write: thread %d, lock %s failed rc=%d\n", 
318                                 (uint32_t)pthread_self(), name, rc);
319                 SMB_ASSERT(errno == 0); /* force error */
320         }
321         return 0;
322 }
323
324
325 /* 
326    rwlock unlock for thread model
327 */
328 static int thread_rwlock_unlock(smb_rwlock_t *rwlock, const char *name)
329 {
330         return pthread_rwlock_unlock((pthread_rwlock_t *)rwlock->rwlock);
331 }
332
333 /*****************************************************************
334  Log suspicious usage (primarily for possible thread-unsafe behavior.
335 *****************************************************************/  
336 static void thread_log_suspicious_usage(const char* from, const char* info)
337 {
338         DEBUG(1,("log_suspicious_usage: from %s info='%s'\n", from, info));
339 #ifdef HAVE_BACKTRACE
340         {
341                 void *addresses[10];
342                 int num_addresses = backtrace(addresses, 8);
343                 char **bt_symbols = backtrace_symbols(addresses, num_addresses);
344                 int i;
345
346                 if (bt_symbols) {
347                         for (i=0; i<num_addresses; i++) {
348                                 DEBUG(1,("log_suspicious_usage: %s%s\n", DEBUGTAB(1), bt_symbols[i]));
349                         }
350                         free(bt_symbols);
351                 }
352         }
353 #endif
354 }
355
356 /*****************************************************************
357  Log suspicious usage to stdout (primarily for possible thread-unsafe behavior.
358  Used in mutex code where DEBUG calls would cause recursion.
359 *****************************************************************/  
360 static void thread_print_suspicious_usage(const char* from, const char* info)
361 {
362         printf("log_suspicious_usage: from %s info='%s'\n", from, info);
363 #ifdef HAVE_BACKTRACE
364         {
365                 void *addresses[10];
366                 int num_addresses = backtrace(addresses, 8);
367                 char **bt_symbols = backtrace_symbols(addresses, num_addresses);
368                 int i;
369
370                 if (bt_symbols) {
371                         for (i=0; i<num_addresses; i++) {
372                                 printf("log_suspicious_usage: %s%s\n", DEBUGTAB(1), bt_symbols[i]);
373                         }
374                         free(bt_symbols);
375                 }
376         }
377 #endif
378 }
379
380 static uint32_t thread_get_task_id(void)
381 {
382         return (uint32_t)pthread_self();
383 }
384
385 static void thread_log_task_id(int fd)
386 {
387         char *s;
388         
389         asprintf(&s, "thread %u: ", (uint32_t)pthread_self());
390         write(fd, s, strlen(s));
391         free(s);
392 }
393 /****************************************************************************
394 catch serious errors
395 ****************************************************************************/
396 static void thread_sig_fault(int sig)
397 {
398         DEBUG(0,("===============================================================\n"));
399         DEBUG(0,("TERMINAL ERROR: Recursive signal %d in thread %lu (%s)\n",sig,(unsigned long int)pthread_self(),SAMBA_VERSION_STRING));
400         DEBUG(0,("===============================================================\n"));
401         exit(1); /* kill the whole server for now */
402 }
403
404 /*******************************************************************
405 setup our recursive fault handlers
406 ********************************************************************/
407 static void thread_fault_setup(void)
408 {
409 #ifdef SIGSEGV
410         CatchSignal(SIGSEGV,SIGNAL_CAST thread_sig_fault);
411 #endif
412 #ifdef SIGBUS
413         CatchSignal(SIGBUS,SIGNAL_CAST thread_sig_fault);
414 #endif
415 #ifdef SIGABRT
416         CatchSignal(SIGABRT,SIGNAL_CAST thread_sig_fault);
417 #endif
418 }
419
420 /*******************************************************************
421 report a fault in a thread
422 ********************************************************************/
423 static void thread_fault_handler(int sig)
424 {
425         static int counter;
426         
427         /* try to catch recursive faults */
428         thread_fault_setup();
429         
430         counter++;      /* count number of faults that have occurred */
431
432         DEBUG(0,("===============================================================\n"));
433         DEBUG(0,("INTERNAL ERROR: Signal %d in thread %lu (%s)\n",sig,(unsigned long int)pthread_self(),SAMBA_VERSION_STRING));
434         DEBUG(0,("Please read the file BUGS.txt in the distribution\n"));
435         DEBUG(0,("===============================================================\n"));
436 #ifdef HAVE_BACKTRACE
437         {
438                 void *addresses[10];
439                 int num_addresses = backtrace(addresses, 8);
440                 char **bt_symbols = backtrace_symbols(addresses, num_addresses);
441                 int i;
442
443                 if (bt_symbols) {
444                         for (i=0; i<num_addresses; i++) {
445                                 DEBUG(1,("fault_report: %s%s\n", DEBUGTAB(1), bt_symbols[i]));
446                         }
447                         free(bt_symbols);
448                 }
449         }
450 #endif
451         pthread_exit(NULL); /* terminate failing thread only */
452 }
453
454 /*
455   called when the process model is selected
456 */
457 static void thread_model_startup(void)
458 {
459         struct mutex_ops m_ops;
460         struct debug_ops d_ops;
461
462         ZERO_STRUCT(m_ops);
463         ZERO_STRUCT(d_ops);
464
465         smbd_process_init();
466
467         /* register mutex/rwlock handlers */
468         m_ops.mutex_init = thread_mutex_init;
469         m_ops.mutex_lock = thread_mutex_lock;
470         m_ops.mutex_unlock = thread_mutex_unlock;
471         m_ops.mutex_destroy = thread_mutex_destroy;
472         
473         m_ops.rwlock_init = thread_rwlock_init;
474         m_ops.rwlock_lock_write = thread_rwlock_lock_write;
475         m_ops.rwlock_lock_read = thread_rwlock_lock_read;
476         m_ops.rwlock_unlock = thread_rwlock_unlock;
477         m_ops.rwlock_destroy = thread_rwlock_destroy;
478
479         register_mutex_handlers("thread", &m_ops);
480
481         register_fault_handler("thread", thread_fault_handler);
482
483         d_ops.log_suspicious_usage = thread_log_suspicious_usage;
484         d_ops.print_suspicious_usage = thread_print_suspicious_usage;
485         d_ops.get_task_id = thread_get_task_id;
486         d_ops.log_task_id = thread_log_task_id;
487
488         register_debug_handlers("thread", &d_ops);      
489 }
490
491 static void thread_exit_server(struct server_context *srv_ctx, const char *reason)
492 {
493         DEBUG(1,("thread_exit_server: reason[%s]\n",reason));
494 }
495
496 /*
497   initialise the thread process model, registering ourselves with the model subsystem
498  */
499 NTSTATUS process_model_thread_init(void)
500 {
501         NTSTATUS ret;
502         struct model_ops ops;
503
504         ZERO_STRUCT(ops);
505
506         /* fill in our name */
507         ops.name = "thread";
508
509         /* fill in all the operations */
510         ops.model_startup = thread_model_startup;
511         ops.accept_connection = thread_accept_connection;
512         ops.terminate_connection = thread_terminate_connection;
513         ops.exit_server = thread_exit_server;
514         ops.get_id = thread_get_id;
515
516         /* register ourselves with the PROCESS_MODEL subsystem. */
517         ret = register_backend("process_model", &ops);
518         if (!NT_STATUS_IS_OK(ret)) {
519                 DEBUG(0,("Failed to register process_model 'thread'!\n"));
520                 return ret;
521         }
522
523         return ret;
524 }