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