]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bnet_server.c
Implement user friendly time duration input editing
[bacula/bacula] / bacula / src / lib / bnet_server.c
1 /*
2    Copyright (C) 2000-2004 Kern Sibbald and John Walker
3
4    This program is free software; you can redistribute it and/or
5    modify it under the terms of the GNU General Public License as
6    published by the Free Software Foundation; either version 2 of
7    the License, or (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12    General Public License for more details.
13
14    You should have received a copy of the GNU General Public
15    License along with this program; if not, write to the Free
16    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
17    MA 02111-1307, USA.
18
19  */
20  /* 
21   * Originally written by Kern Sibbald for inclusion in apcupsd,
22   *  but heavily modified for Bacula
23   *
24   *   Version $Id$
25   */
26
27 #include "bacula.h"
28 #undef DEV_BSIZE
29 #include <netinet/in.h>
30 #include <sys/socket.h>
31 #include <stdlib.h>
32 #include <arpa/inet.h>
33 #include <netdb.h>
34 #ifdef HAVE_ARPA_NAMESER_H
35 #include <arpa/nameser.h>
36 #endif
37 #ifdef HAVE_RESOLV_H
38 #include <resolv.h>
39 #endif
40
41
42 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
43
44 #ifdef HAVE_LIBWRAP
45 #include "tcpd.h"
46 int allow_severity = LOG_NOTICE;
47 int deny_severity = LOG_WARNING;
48 #endif
49
50 static bool quit = false;
51
52 void bnet_stop_thread_server(pthread_t tid)
53 {
54    quit = true;
55    pthread_kill(tid, TIMEOUT_SIGNAL);
56 }
57
58 /* 
59         Become Threaded Network Server 
60     This function is able to handle multiple server ips in
61     ipv4 and ipv6 style. The Addresse are give in a comma
62     seperated string in bind_addr
63     In the moment it is inpossible to bind different ports.
64 */
65 void
66 bnet_thread_server(dlist *addrs, int max_clients, workq_t *client_wq,
67                    void *handle_client_request(void *bsock))
68 {
69    int newsockfd, stat;
70    socklen_t clilen;
71    struct sockaddr cli_addr;       /* client's address */
72    int tlog;
73    int turnon = 1;
74 #ifdef HAVE_LIBWRAP
75    struct request_info request;
76 #endif
77    IPADDR *p;
78    struct s_sockfd {
79       dlink link;                     /* this MUST be the first item */
80       int fd;
81       int port;
82    } *fd_ptr = NULL;
83    char buf[128];
84    dlist sockfds;
85
86    char allbuf[256 * addrs->size()];
87    Dmsg1(100, "Addresses %s\n", build_addresses_str(addrs, allbuf, sizeof(allbuf)));
88
89    foreach_dlist(p, addrs) {
90       /* Allocate on stack frame -- no need to free */
91       fd_ptr = (s_sockfd *)alloca(sizeof(s_sockfd));
92       fd_ptr->port = p->get_port();
93       /*
94        * Open a TCP socket  
95        */
96       for (tlog= 60; (fd_ptr->fd=socket(p->get_family(), SOCK_STREAM, 0)) < 0; tlog -= 10) {
97          if (tlog <= 0) {
98             berrno be;
99             char curbuf[256];
100             Emsg3(M_ABORT, 0, _("Cannot open stream socket. ERR=%s. Current %s All %s\n"),
101                        be.strerror(),
102                        p->build_address_str(curbuf, sizeof(curbuf)), 
103                        build_addresses_str(addrs, allbuf, sizeof(allbuf)));
104          }
105          bmicrosleep(10, 0);
106       }
107       /*
108        * Reuse old sockets 
109        */
110       if (setsockopt(fd_ptr->fd, SOL_SOCKET, SO_REUSEADDR, (sockopt_val_t) & turnon,
111            sizeof(turnon)) < 0) {
112          berrno be;
113          Emsg1(M_WARNING, 0, _("Cannot set SO_REUSEADDR on socket: %s\n"),
114                be.strerror());
115       }
116
117       int tmax = 30 * (60 / 5);    /* wait 30 minutes max */
118       /* FIXME i can go to a endless loop i get a invalid address */
119       for (tlog = 0; bind(fd_ptr->fd, p->get_sockaddr(), p->get_sockaddr_len()) < 0; tlog -= 5) {
120          berrno be;
121          if (tlog <= 0) {
122             tlog = 2 * 60;         /* Complain every 2 minutes */
123             Emsg2(M_WARNING, 0, _("Cannot bind port %d: ERR=%s. Retrying ...\n"),
124                   fd_ptr->port, be.strerror());
125          }
126          bmicrosleep(5, 0);
127          if (--tmax <= 0) {
128             Emsg2(M_ABORT, 0, _("Cannot bind port %d: ERR=%s.\n"), fd_ptr->port,
129                   be.strerror());
130          }
131       }
132       listen(fd_ptr->fd, 5);       /* tell system we are ready */
133       sockfds.append(fd_ptr);
134    }
135    /* Start work queue thread */
136    if ((stat = workq_init(client_wq, max_clients, handle_client_request)) != 0) {
137       berrno be;
138       be.set_errno(stat);
139       Emsg1(M_ABORT, 0, _("Could not init client queue: ERR=%s\n"), be.strerror());
140    }
141    /* 
142     * Wait for a connection from the client process.
143     */
144    for (; !quit;) {
145       unsigned int maxfd = 0;
146       fd_set sockset;
147       FD_ZERO(&sockset);
148       foreach_dlist(fd_ptr, &sockfds) {
149          FD_SET((unsigned)fd_ptr->fd, &sockset);
150          maxfd = maxfd > (unsigned)fd_ptr->fd ? maxfd : fd_ptr->fd;
151       }
152       errno = 0;
153       if ((stat = select(maxfd + 1, &sockset, NULL, NULL, NULL)) < 0) {
154          berrno be;                   /* capture errno */
155          if (errno == EINTR || errno == EAGAIN) {
156             continue;
157          }
158          /* Error, get out */
159          foreach_dlist(fd_ptr, &sockfds) {
160             close(fd_ptr->fd);
161             free((void *)fd_ptr);
162          }
163          Emsg1(M_FATAL, 0, _("Error in select: %s\n"), be.strerror());
164          break;
165       }
166
167       foreach_dlist(fd_ptr, &sockfds) {
168          if (FD_ISSET(fd_ptr->fd, &sockset)) {
169             /* Got a connection, now accept it. */
170             do {
171                clilen = sizeof(cli_addr);
172                newsockfd = accept(fd_ptr->fd, &cli_addr, &clilen);
173             } while (newsockfd < 0 && (errno == EINTR || errno == EAGAIN));
174             if (newsockfd < 0) {
175                continue;
176             }
177 #ifdef HAVE_LIBWRAP
178             P(mutex);              /* hosts_access is not thread safe */
179             request_init(&request, RQ_DAEMON, my_name, RQ_FILE, newsockfd, 0);
180             fromhost(&request);
181             if (!hosts_access(&request)) {
182                V(mutex);
183 #ifndef HAVE_INET_NTOP
184                Jmsg2(NULL, M_SECURITY, 0,
185                      _("Connection from %s:%d refused by hosts.access\n"),
186                      inet_ntoa(((sockaddr_in *)&cli_addr)->sin_addr),
187                      ntohs(((sockaddr_in *)&cli_addr)->sin_port));
188 #else
189                Jmsg2(NULL, M_SECURITY, 0,
190                      _("Connection from %s:%d refused by hosts.access\n"),
191                      inet_ntop(clilen == sizeof(sockaddr_in) ? AF_INET : AF_INET6,
192                                &clilen, buf, clilen),
193                      ntohs(clilen == sizeof(sockaddr_in) ? 
194                            ((sockaddr_in *)&cli_addr)->sin_port :
195                             ((sockaddr_in6 *)&cli_addr)->sin6_port));
196 #endif
197                close(newsockfd);
198                continue;
199             }
200             V(mutex);
201 #endif
202
203             /*
204              * Receive notification when connection dies.
205              */
206             if (setsockopt(newsockfd, SOL_SOCKET, SO_KEEPALIVE, (sockopt_val_t) & turnon,
207                  sizeof(turnon)) < 0) {
208                berrno be;
209                Emsg1(M_WARNING, 0, _("Cannot set SO_KEEPALIVE on socket: %s\n"),
210                      be.strerror());
211             }
212
213             /* see who client is. i.e. who connected to us. */
214             P(mutex);
215 #ifndef HAVE_INET_NTOP
216             bstrncpy(buf, inet_ntoa(((sockaddr_in *) & cli_addr)->sin_addr), sizeof(buf));      /* NOT thread safe, use mutex */
217 #else
218             inet_ntop(clilen == sizeof(sockaddr_in) ? AF_INET : AF_INET6, &clilen,
219                       buf, clilen);
220 #endif
221             /* possible release of the mutex */
222
223             BSOCK *bs =
224                init_bsock(NULL, newsockfd, "client", buf, fd_ptr->port, &cli_addr);
225             if (bs == NULL) {
226                Jmsg0(NULL, M_ABORT, 0, _("Could not create client BSOCK.\n"));
227             }
228
229             /* Queue client to be served */
230             if ((stat = workq_add(client_wq, (void *)bs, NULL, 0)) != 0) {
231                berrno be;
232                V(mutex);
233                be.set_errno(stat);
234                Jmsg1(NULL, M_ABORT, 0,
235                      _("Could not add job to client queue: ERR=%s\n"),
236                      be.strerror());
237             }
238             V(mutex);
239          }
240       }
241    }
242
243    /* Stop work queue thread */
244    if ((stat = workq_destroy(client_wq)) != 0) {
245       berrno be;
246       be.set_errno(stat);
247       Emsg1(M_FATAL, 0, _("Could not destroy client queue: ERR=%s\n"),
248             be.strerror());
249    }
250 }
251
252
253 #ifdef REALLY_USED
254 /*
255  * Bind an address so that we may accept connections
256  * one at a time.
257  */
258 BSOCK *bnet_bind(int port)
259 {
260    int sockfd;
261    struct sockaddr_in serv_addr;   /* our address */
262    int tlog;
263    int turnon = 1;
264
265    /*
266     * Open a TCP socket  
267     */
268    for (tlog = 0; (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0; tlog -= 10) {
269       if (errno == EINTR || errno == EAGAIN) {
270          continue;
271       }
272       if (tlog <= 0) {
273          tlog = 2 * 60;
274          Emsg1(M_ERROR, 0, _("Cannot open stream socket: %s\n"), strerror(errno));
275       }
276       bmicrosleep(60, 0);
277    }
278
279    /*
280     * Reuse old sockets 
281     */
282    if (setsockopt
283        (sockfd, SOL_SOCKET, SO_REUSEADDR, (sockopt_val_t) & turnon,
284         sizeof(turnon)) < 0) {
285       Emsg1(M_WARNING, 0, _("Cannot set SO_REUSEADDR on socket: %s\n"),
286             strerror(errno));
287    }
288
289    /* 
290     * Bind our local address so that the client can send to us.
291     */
292    bzero((char *)&serv_addr, sizeof(serv_addr));
293    serv_addr.sin_family = AF_INET;
294    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
295    serv_addr.sin_port = htons(port);
296
297    for (tlog = 0; bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0;
298         tlog -= 5) {
299       berrno be;
300       if (errno == EINTR || errno == EAGAIN) {
301          continue;
302       }
303       if (tlog <= 0) {
304          tlog = 2 * 60;
305          Emsg2(M_WARNING, 0, _("Cannot bind port %d: ERR=%s: retrying ...\n"), port,
306                be.strerror());
307       }
308       bmicrosleep(5, 0);
309    }
310    listen(sockfd, 1);              /* tell system we are ready */
311    return init_bsock(NULL, sockfd, _("Server socket"), _("client"), port,
312                      &serv_addr);
313 }
314
315 /*
316  * Accept a single connection 
317  */
318 BSOCK *bnet_accept(BSOCK * bsock, char *who)
319 {
320    fd_set ready, sockset;
321    int newsockfd, stat, len;
322    socklen_t clilen;
323    struct sockaddr_in cli_addr;    /* client's address */
324    char *caller, *buf;
325    BSOCK *bs;
326    int turnon = 1;
327 #ifdef HAVE_LIBWRAP
328    struct request_info request;
329 #endif
330
331    /* 
332     * Wait for a connection from the client process.
333     */
334    FD_ZERO(&sockset);
335    FD_SET((unsigned)bsock->fd, &sockset);
336
337    for (;;) {
338       /* 
339        * Wait for a connection from a client process.
340        */
341       ready = sockset;
342       if ((stat = select(bsock->fd + 1, &ready, NULL, NULL, NULL)) < 0) {
343          if (errno == EINTR || errno = EAGAIN) {
344             errno = 0;
345             continue;
346          }
347          Emsg1(M_FATAL, 0, _("Error in select: %s\n"), strerror(errno));
348          newsockfd = -1;
349          break;
350       }
351       do {
352          clilen = sizeof(cli_addr);
353          newsockfd = accept(bsock->fd, (struct sockaddr *)&cli_addr, &clilen);
354       } while (newsockfd < 0 && (errno == EINTR || errno = EAGAIN));
355       if (newsockfd >= 0) {
356          break;
357       }
358    }
359
360 #ifdef HAVE_LIBWRAP
361    P(mutex);
362    request_init(&request, RQ_DAEMON, my_name, RQ_FILE, newsockfd, 0);
363    fromhost(&request);
364    if (!hosts_access(&request)) {
365       V(mutex);
366       Emsg2(M_SECURITY, 0, _("Connection from %s:%d refused by hosts.access\n"),
367             inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
368       close(newsockfd);
369       return NULL;
370    }
371    V(mutex);
372 #endif
373
374    /*
375     * Receive notification when connection dies.
376     */
377    if (setsockopt
378        (newsockfd, SOL_SOCKET, SO_KEEPALIVE, (sockopt_val_t) & turnon,
379         sizeof(turnon)) < 0) {
380       Emsg1(M_WARNING, 0, _("Cannot set SO_KEEPALIVE on socket: %s\n"),
381             strerror(errno));
382    }
383
384    /* see who client is. I.e. who connected to us.
385     * return it in the input message buffer.
386     */
387    if ((caller = inet_ntoa(cli_addr.sin_addr)) != NULL) {
388       pm_strcpy(&bsock->msg, caller);
389    } else {
390       bsock->msg[0] = 0;
391    }
392    bsock->msglen = strlen(bsock->msg);
393
394    if (newsockfd < 0) {
395       Emsg2(M_FATAL, 0, _("Socket accept error for %s. ERR=%s\n"), who,
396             strerror(errno));
397       return NULL;
398    } else {
399       if (caller == NULL) {
400          caller = "unknown";
401       }
402       len = strlen(caller) + strlen(who) + 3;
403       buf = (char *)malloc(len);
404       bstrncpy(buf, len, who);
405       bstrncat(buf, len, ": ");
406       bstrncat(buf, len, caller);
407       bs = init_bsock(NULL, newsockfd, "client", buf, bsock->port, &cli_addr);
408       free(buf);
409       return bs;                   /* return new BSOCK */
410    }
411 }
412
413 #endif