]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bnet_server.c
Win32 fix -- remove debug O_NONBLOCK code
[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             free((void *)fd_ptr);
157          }
158          Emsg1(M_FATAL, 0, _("Error in select: %s\n"), be.strerror());
159          break;
160       }
161
162       foreach_dlist(fd_ptr, &sockfds) {
163          if (FD_ISSET(fd_ptr->fd, &sockset)) {
164             /* Got a connection, now accept it. */
165             do {
166                clilen = sizeof(cli_addr);
167                newsockfd = accept(fd_ptr->fd, &cli_addr, &clilen);
168             } while (newsockfd < 0 && errno == EINTR);
169             if (newsockfd < 0) {
170                continue;
171             }
172 #ifdef HAVE_LIBWRAP
173             P(mutex);              /* hosts_access is not thread safe */
174             request_init(&request, RQ_DAEMON, my_name, RQ_FILE, newsockfd, 0);
175             fromhost(&request);
176             if (!hosts_access(&request)) {
177                V(mutex);
178                Jmsg2(NULL, M_SECURITY, 0,
179                      _("Connection from %s:%d refused by hosts.access\n"),
180                      sockaddr_to_ascii(&cli_addr, buf, sizeof(buf)),
181                      sockaddr_get_port(&cli_addr));
182                close(newsockfd);
183                continue;
184             }
185             V(mutex);
186 #endif
187
188             /*
189              * Receive notification when connection dies.
190              */
191             if (setsockopt(newsockfd, SOL_SOCKET, SO_KEEPALIVE, (sockopt_val_t)&turnon,
192                  sizeof(turnon)) < 0) {
193                berrno be;
194                Emsg1(M_WARNING, 0, _("Cannot set SO_KEEPALIVE on socket: %s\n"),
195                      be.strerror());
196             }
197
198             /* see who client is. i.e. who connected to us. */
199             P(mutex);
200             sockaddr_to_ascii(&cli_addr, buf, sizeof(buf));
201             V(mutex);
202             BSOCK *bs;
203             bs = init_bsock(NULL, newsockfd, "client", buf, fd_ptr->port, &cli_addr);
204             if (bs == NULL) {
205                Jmsg0(NULL, M_ABORT, 0, _("Could not create client BSOCK.\n"));
206             }
207
208             /* Queue client to be served */
209             if ((stat = workq_add(client_wq, (void *)bs, NULL, 0)) != 0) {
210                berrno be;
211                be.set_errno(stat);
212                Jmsg1(NULL, M_ABORT, 0, _("Could not add job to client queue: ERR=%s\n"),
213                      be.strerror());
214             }
215          }
216       }
217    }
218
219    /* Stop work queue thread */
220    if ((stat = workq_destroy(client_wq)) != 0) {
221       berrno be;
222       be.set_errno(stat);
223       Emsg1(M_FATAL, 0, _("Could not destroy client queue: ERR=%s\n"),
224             be.strerror());
225    }
226 }
227
228
229 #ifdef REALLY_USED
230 /*
231  * Bind an address so that we may accept connections
232  * one at a time.
233  */
234 BSOCK *bnet_bind(int port)
235 {
236    int sockfd;
237    struct sockaddr_in serv_addr;   /* our address */
238    int tlog;
239    int turnon = 1;
240
241    /*
242     * Open a TCP socket
243     */
244    for (tlog = 0; (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0; tlog -= 10) {
245       if (errno == EINTR || errno == EAGAIN) {
246          continue;
247       }
248       if (tlog <= 0) {
249          tlog = 2 * 60;
250          Emsg1(M_ERROR, 0, _("Cannot open stream socket: %s\n"), strerror(errno));
251       }
252       bmicrosleep(60, 0);
253    }
254
255    /*
256     * Reuse old sockets
257     */
258    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (sockopt_val_t)&turnon, sizeof(turnon)) < 0) {
259       Emsg1(M_WARNING, 0, _("Cannot set SO_REUSEADDR on socket: %s\n"),
260             strerror(errno));
261    }
262
263    /*
264     * Bind our local address so that the client can send to us.
265     */
266    bzero((char *)&serv_addr, sizeof(serv_addr));
267    serv_addr.sin_family = AF_INET;
268    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
269    serv_addr.sin_port = htons(port);
270
271    for (tlog = 0; bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0;
272         tlog -= 5) {
273       berrno be;
274       if (errno == EINTR || errno == EAGAIN) {
275          continue;
276       }
277       if (tlog <= 0) {
278          tlog = 2 * 60;
279          Emsg2(M_WARNING, 0, _("Cannot bind port %d: ERR=%s: retrying ...\n"), port,
280                be.strerror());
281       }
282       bmicrosleep(5, 0);
283    }
284    listen(sockfd, 1);              /* tell system we are ready */
285    return init_bsock(NULL, sockfd, _("Server socket"), _("client"), port,
286                      &serv_addr);
287 }
288
289 /*
290  * Accept a single connection
291  */
292 BSOCK *bnet_accept(BSOCK * bsock, char *who)
293 {
294    fd_set ready, sockset;
295    int newsockfd, stat, len;
296    socklen_t clilen;
297    struct sockaddr_in cli_addr;    /* client's address */
298    char *caller, *buf;
299    BSOCK *bs;
300    int turnon = 1;
301 #ifdef HAVE_LIBWRAP
302    struct request_info request;
303 #endif
304
305    /*
306     * Wait for a connection from the client process.
307     */
308    FD_ZERO(&sockset);
309    FD_SET((unsigned)bsock->fd, &sockset);
310
311    for (;;) {
312       /*
313        * Wait for a connection from a client process.
314        */
315       ready = sockset;
316       if ((stat = select(bsock->fd + 1, &ready, NULL, NULL, NULL)) < 0) {
317          if (errno == EINTR || errno = EAGAIN) {
318             errno = 0;
319             continue;
320          }
321          Emsg1(M_FATAL, 0, _("Error in select: %s\n"), strerror(errno));
322          newsockfd = -1;
323          break;
324       }
325       do {
326          clilen = sizeof(cli_addr);
327          newsockfd = accept(bsock->fd, (struct sockaddr *)&cli_addr, &clilen);
328       } while (newsockfd < 0 && (errno == EINTR || errno = EAGAIN));
329       if (newsockfd >= 0) {
330          break;
331       }
332    }
333
334 #ifdef HAVE_LIBWRAP
335    P(mutex);
336    request_init(&request, RQ_DAEMON, my_name, RQ_FILE, newsockfd, 0);
337    fromhost(&request);
338    if (!hosts_access(&request)) {
339       V(mutex);
340       Emsg2(M_SECURITY, 0, _("Connection from %s:%d refused by hosts.access\n"),
341             inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
342       close(newsockfd);
343       return NULL;
344    }
345    V(mutex);
346 #endif
347
348    /*
349     * Receive notification when connection dies.
350     */
351    if (setsockopt(newsockfd, SOL_SOCKET, SO_KEEPALIVE, (sockopt_val_t)&turnon, sizeof(turnon)) < 0) {
352       Emsg1(M_WARNING, 0, _("Cannot set SO_KEEPALIVE on socket: %s\n"),
353             strerror(errno));
354    }
355
356    /* see who client is. I.e. who connected to us.
357     * return it in the input message buffer.
358     */
359    if ((caller = inet_ntoa(cli_addr.sin_addr)) != NULL) {
360       pm_strcpy(&bsock->msg, caller);
361    } else {
362       bsock->msg[0] = 0;
363    }
364    bsock->msglen = strlen(bsock->msg);
365
366    if (newsockfd < 0) {
367       Emsg2(M_FATAL, 0, _("Socket accept error for %s. ERR=%s\n"), who,
368             strerror(errno));
369       return NULL;
370    } else {
371       if (caller == NULL) {
372          caller = _("unknown");
373       }
374       len = strlen(caller) + strlen(who) + 3;
375       buf = (char *)malloc(len);
376       bstrncpy(buf, len, who);
377       bstrncat(buf, len, ": ");
378       bstrncat(buf, len, caller);
379       bs = init_bsock(NULL, newsockfd, _("client"), buf, bsock->port, &cli_addr);
380       free(buf);
381       return bs;                   /* return new BSOCK */
382    }
383 }
384
385 #endif