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