]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bnet.c
2e247eef23c48e0bc297161563e7472f4c4950a4
[bacula/bacula] / bacula / src / lib / bnet.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2008 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from
7    many others, a complete list can be found in the file AUTHORS.
8    This program is Free Software; you can redistribute it and/or
9    modify it under the terms of version two of the GNU General Public
10    License as published by the Free Software Foundation and included
11    in the file LICENSE.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16    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., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of Kern Sibbald.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /*
29  * Network Utility Routines
30  *
31  *  by Kern Sibbald
32  *
33  * Adapted and enhanced for Bacula, originally written
34  * for inclusion in the Apcupsd package
35  *
36  *   Version $Id$
37  */
38
39
40 #include "bacula.h"
41 #include "jcr.h"
42 #include <netdb.h>
43
44 #ifndef   INADDR_NONE
45 #define   INADDR_NONE    -1
46 #endif
47
48 #ifdef HAVE_WIN32
49 #define socketRead(fd, buf, len)  recv(fd, buf, len, 0)
50 #define socketWrite(fd, buf, len) send(fd, buf, len, 0)
51 #define socketClose(fd)           closesocket(fd)
52 #else
53 #define socketRead(fd, buf, len)  read(fd, buf, len)
54 #define socketWrite(fd, buf, len) write(fd, buf, len)
55 #define socketClose(fd)           close(fd)
56 #endif
57
58 static pthread_mutex_t ip_mutex = PTHREAD_MUTEX_INITIALIZER;
59
60 /*
61  * Read a nbytes from the network.
62  * It is possible that the total bytes require in several
63  * read requests
64  */
65
66 int32_t read_nbytes(BSOCK * bsock, char *ptr, int32_t nbytes)
67 {
68    int32_t nleft, nread;
69
70 #ifdef HAVE_TLS
71    if (bsock->tls) {
72       /* TLS enabled */
73       return (tls_bsock_readn(bsock, ptr, nbytes));
74    }
75 #endif /* HAVE_TLS */
76
77    nleft = nbytes;
78    while (nleft > 0) {
79       errno = 0;
80       nread = socketRead(bsock->m_fd, ptr, nleft);
81       if (bsock->is_timed_out() || bsock->is_terminated()) {
82          return nread;
83       }
84       if (nread == -1) {
85          if (errno == EINTR) {
86             continue;
87          }
88          if (errno == EAGAIN) {
89             bmicrosleep(0, 200000);  /* try again in 200ms */
90             continue;
91          }
92       }
93       if (nread <= 0) {
94          return nread;             /* error, or EOF */
95       }
96       nleft -= nread;
97       ptr += nread;
98    }
99    return nbytes - nleft;          /* return >= 0 */
100 }
101
102 /*
103  * Write nbytes to the network.
104  * It may require several writes.
105  */
106
107 int32_t write_nbytes(BSOCK * bsock, char *ptr, int32_t nbytes)
108 {
109    int32_t nleft, nwritten;
110
111    if (bsock->is_spooling()) {
112       nwritten = fwrite(ptr, 1, nbytes, bsock->m_spool_fd);
113       if (nwritten != nbytes) {
114          berrno be;
115          bsock->b_errno = errno;
116          Qmsg1(bsock->jcr(), M_FATAL, 0, _("Attr spool write error. ERR=%s\n"),
117                be.bstrerror());
118          Dmsg2(400, "nwritten=%d nbytes=%d.\n", nwritten, nbytes);
119          errno = bsock->b_errno;
120          return -1;
121       }
122       return nbytes;
123    }
124
125 #ifdef HAVE_TLS
126    if (bsock->tls) {
127       /* TLS enabled */
128       return (tls_bsock_writen(bsock, ptr, nbytes));
129    }
130 #endif /* HAVE_TLS */
131
132    nleft = nbytes;
133    while (nleft > 0) {
134       do {
135          errno = 0;
136          nwritten = socketWrite(bsock->m_fd, ptr, nleft);
137          if (bsock->is_timed_out() || bsock->is_terminated()) {
138             return nwritten;
139          }
140       } while (nwritten == -1 && errno == EINTR);
141       /*
142        * If connection is non-blocking, we will get EAGAIN, so
143        * use select() to keep from consuming all the CPU
144        * and try again.
145        */
146       if (nwritten == -1 && errno == EAGAIN) {
147          fd_set fdset;
148          struct timeval tv;
149
150          FD_ZERO(&fdset);
151          FD_SET((unsigned)bsock->m_fd, &fdset);
152          tv.tv_sec = 10;
153          tv.tv_usec = 0;
154          select(bsock->m_fd + 1, NULL, &fdset, NULL, &tv);
155          continue;
156       }
157       if (nwritten <= 0) {
158          return nwritten;          /* error */
159       }
160       nleft -= nwritten;
161       ptr += nwritten;
162    }
163    return nbytes - nleft;
164 }
165
166 /*
167  * Receive a message from the other end. Each message consists of
168  * two packets. The first is a header that contains the size
169  * of the data that follows in the second packet.
170  * Returns number of bytes read (may return zero)
171  * Returns -1 on signal (BNET_SIGNAL)
172  * Returns -2 on hard end of file (BNET_HARDEOF)
173  * Returns -3 on error  (BNET_ERROR)
174  *
175  *  Unfortunately, it is a bit complicated because we have these
176  *    four return types:
177  *    1. Normal data
178  *    2. Signal including end of data stream
179  *    3. Hard end of file
180  *    4. Error
181  *  Using is_bnet_stop() and is_bnet_error() you can figure this all out.
182  */
183 int32_t bnet_recv(BSOCK * bsock)
184 {
185    return bsock->recv();
186 }
187
188
189 /*
190  * Return 1 if there are errors on this bsock or it is closed,
191  *   i.e. stop communicating on this line.
192  */
193 bool is_bnet_stop(BSOCK * bsock)
194 {
195    return bsock->errors || bsock->is_terminated();
196 }
197
198 /*
199  * Return number of errors on socket
200  */
201 int is_bnet_error(BSOCK * bsock)
202 {
203    errno = bsock->b_errno;
204    return bsock->errors;
205 }
206
207 /*
208  * Call here after error during closing to suppress error
209  *  messages which are due to the other end shutting down too.
210  */
211 void bnet_suppress_error_messages(BSOCK * bsock, bool flag)
212 {
213    bsock->m_suppress_error_msgs = flag;
214 }
215
216 /*
217  * Send a message over the network. The send consists of
218  * two network packets. The first is sends a 32 bit integer containing
219  * the length of the data packet which follows.
220  *
221  * Returns: false on failure
222  *          true  on success
223  */
224 bool bnet_send(BSOCK *bsock)
225 {
226    return bsock->send();
227 }
228
229
230 /*
231  * Establish a TLS connection -- server side
232  *  Returns: true  on success
233  *           false on failure
234  */
235 #ifdef HAVE_TLS
236 bool bnet_tls_server(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
237 {
238    TLS_CONNECTION *tls;
239    JCR *jcr = bsock->jcr();
240    
241    tls = new_tls_connection(ctx, bsock->m_fd);
242    if (!tls) {
243       Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS connection initialization failed.\n"));
244       return false;
245    }
246
247    bsock->tls = tls;
248
249    /* Initiate TLS Negotiation */
250    if (!tls_bsock_accept(bsock)) {
251       Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS Negotiation failed.\n"));
252       goto err;
253    }
254
255    if (verify_list) {
256       if (!tls_postconnect_verify_cn(jcr, tls, verify_list)) {
257          Qmsg1(bsock->jcr(), M_FATAL, 0, _("TLS certificate verification failed."
258                                          " Peer certificate did not match a required commonName\n"),
259                                          bsock->host());
260          goto err;
261       }
262    }
263    Dmsg0(50, "TLS server negotiation established.\n");
264    return true;
265
266 err:
267    free_tls_connection(tls);
268    bsock->tls = NULL;
269    return false;
270 }
271
272 /*
273  * Establish a TLS connection -- client side
274  * Returns: true  on success
275  *          false on failure
276  */
277 bool bnet_tls_client(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
278 {
279    TLS_CONNECTION *tls;
280    JCR *jcr = bsock->jcr();
281
282    tls  = new_tls_connection(ctx, bsock->m_fd);
283    if (!tls) {
284       Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS connection initialization failed.\n"));
285       return false;
286    }
287
288    bsock->tls = tls;
289
290    /* Initiate TLS Negotiation */
291    if (!tls_bsock_connect(bsock)) {
292       goto err;
293    }
294
295    /* If there's an Allowed CN verify list, use that to validate the remote
296     * certificate's CN. Otherwise, we use standard host/CN matching. */
297    if (verify_list) {
298       if (!tls_postconnect_verify_cn(jcr, tls, verify_list)) {
299          Qmsg1(bsock->jcr(), M_FATAL, 0, _("TLS certificate verification failed."
300                                          " Peer certificate did not match a required commonName\n"),
301                                          bsock->host());
302          goto err;
303       }
304    } else {
305       if (!tls_postconnect_verify_host(jcr, tls, bsock->host())) {
306          Qmsg1(bsock->jcr(), M_FATAL, 0, _("TLS host certificate verification failed. Host name \"%s\" did not match presented certificate\n"), 
307                bsock->host());
308          goto err;
309       }
310    }
311    Dmsg0(50, "TLS client negotiation established.\n");
312    return true;
313
314 err:
315    free_tls_connection(tls);
316    bsock->tls = NULL;
317    return false;
318 }
319 #else
320
321 bool bnet_tls_server(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
322 {
323    Jmsg(bsock->jcr(), M_ABORT, 0, _("TLS enabled but not configured.\n"));
324    return false;
325 }
326
327 bool bnet_tls_client(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
328 {
329    Jmsg(bsock->jcr(), M_ABORT, 0, _("TLS enable but not configured.\n"));
330    return false;
331 }
332
333 #endif /* HAVE_TLS */
334
335 /*
336  * Wait for a specified time for data to appear on
337  * the BSOCK connection.
338  *
339  *   Returns: 1 if data available
340  *            0 if timeout
341  *           -1 if error
342  */
343 int bnet_wait_data(BSOCK * bsock, int sec)
344 {
345    return bsock->wait_data(sec);
346 }
347
348 /*
349  * As above, but returns on interrupt
350  */
351 int bnet_wait_data_intr(BSOCK * bsock, int sec)
352 {
353    return bsock->wait_data_intr(sec);
354 }
355
356 #ifndef NETDB_INTERNAL
357 #define NETDB_INTERNAL  -1         /* See errno. */
358 #endif
359 #ifndef NETDB_SUCCESS
360 #define NETDB_SUCCESS   0          /* No problem. */
361 #endif
362 #ifndef HOST_NOT_FOUND
363 #define HOST_NOT_FOUND  1          /* Authoritative Answer Host not found. */
364 #endif
365 #ifndef TRY_AGAIN
366 #define TRY_AGAIN       2          /* Non-Authoritative Host not found, or SERVERFAIL. */
367 #endif
368 #ifndef NO_RECOVERY
369 #define NO_RECOVERY     3          /* Non recoverable errors, FORMERR, REFUSED, NOTIMP. */
370 #endif
371 #ifndef NO_DATA
372 #define NO_DATA         4          /* Valid name, no data record of requested type. */
373 #endif
374
375 /*
376  * Get human readable error for gethostbyname()
377  */
378 static const char *gethost_strerror()
379 {
380    const char *msg;
381    berrno be;
382    switch (h_errno) {
383    case NETDB_INTERNAL:
384       msg = be.bstrerror();
385       break;
386    case NETDB_SUCCESS:
387       msg = _("No problem.");
388       break;
389    case HOST_NOT_FOUND:
390       msg = _("Authoritative answer for host not found.");
391       break;
392    case TRY_AGAIN:
393       msg = _("Non-authoritative for host not found, or ServerFail.");
394       break;
395    case NO_RECOVERY:
396       msg = _("Non-recoverable errors, FORMERR, REFUSED, or NOTIMP.");
397       break;
398    case NO_DATA:
399       msg = _("Valid name, no data record of resquested type.");
400       break;
401    default:
402       msg = _("Unknown error.");
403    }
404    return msg;
405 }
406
407
408
409
410 static IPADDR *add_any(int family)
411 {
412    IPADDR *addr = New(IPADDR(family));
413    addr->set_type(IPADDR::R_MULTIPLE);
414    addr->set_addr_any();
415    return addr;
416 }
417
418 static const char *resolv_host(int family, const char *host, dlist * addr_list)
419 {
420    struct hostent *hp;
421    const char *errmsg;
422
423    P(ip_mutex);                       /* gethostbyname() is not thread safe */
424 #ifdef HAVE_GETHOSTBYNAME2
425    if ((hp = gethostbyname2(host, family)) == NULL) {
426 #else
427    if ((hp = gethostbyname(host)) == NULL) {
428 #endif
429       /* may be the strerror give not the right result -:( */
430       errmsg = gethost_strerror();
431       V(ip_mutex);
432       return errmsg;
433    } else {
434       char **p;
435       for (p = hp->h_addr_list; *p != 0; p++) {
436          IPADDR *addr =  New(IPADDR(hp->h_addrtype));
437          addr->set_type(IPADDR::R_MULTIPLE);
438          if (addr->get_family() == AF_INET) {
439              addr->set_addr4((struct in_addr*)*p);
440          }
441 #ifdef HAVE_IPV6
442          else {
443              addr->set_addr6((struct in6_addr*)*p);
444          }
445 #endif
446          addr_list->append(addr);
447       }
448       V(ip_mutex);
449    }
450    return NULL;
451 }
452
453 /*
454  * i host = 0 mean INADDR_ANY only ipv4
455  */
456 dlist *bnet_host2ipaddrs(const char *host, int family, const char **errstr)
457 {
458    struct in_addr inaddr;
459    IPADDR *addr = 0;
460    const char *errmsg;
461 #ifdef HAVE_IPV6
462    struct in6_addr inaddr6;
463 #endif
464
465    dlist *addr_list = New(dlist(addr, &addr->link));
466    if (!host || host[0] == '\0') {
467       if (family != 0) {
468          addr_list->append(add_any(family));
469       } else {
470          addr_list->append(add_any(AF_INET));
471 #ifdef HAVE_IPV6
472          addr_list->append(add_any(AF_INET6));
473 #endif
474       }
475    } else if (inet_aton(host, &inaddr)) { /* MA Bug 4 */
476       addr = New(IPADDR(AF_INET));
477       addr->set_type(IPADDR::R_MULTIPLE);
478       addr->set_addr4(&inaddr);
479       addr_list->append(addr);
480    } else
481 #ifdef HAVE_IPV6
482    if (inet_pton(AF_INET6, host, &inaddr6) > 1) {
483       addr = New(IPADDR(AF_INET6));
484       addr->set_type(IPADDR::R_MULTIPLE);
485       addr->set_addr6(&inaddr6);
486       addr_list->append(addr);
487    } else
488 #endif
489    {
490       if (family != 0) {
491          errmsg = resolv_host(family, host, addr_list);
492          if (errmsg) {
493             *errstr = errmsg;
494             free_addresses(addr_list);
495             return 0;
496          }
497       } else {
498 #ifdef HAVE_IPV6
499          /* We try to resolv host for ipv6 and ipv4, the connection procedure
500           * will try to reach the host for each protocols. We report only "Host
501           * not found" ipv4 message (no need to have ipv6 and ipv4 messages).
502           */
503          resolv_host(AF_INET6, host, addr_list);
504 #endif
505          errmsg = resolv_host(AF_INET, host, addr_list);
506
507          if (addr_list->size() == 0) {
508             *errstr = errmsg;
509             free_addresses(addr_list);
510             return 0;
511          }
512       }
513    }
514    return addr_list;
515 }
516
517 /*
518  * This is the "old" way of opening a connection.  The preferred way is
519  *   now to do what this subroutine does, but inline. That allows the 
520  *   connect() call to return error status, ...
521  */      
522 BSOCK *bnet_connect(JCR * jcr, int retry_interval, utime_t max_retry_time,
523                     utime_t heart_beat,
524                     const char *name, char *host, char *service, int port,
525                     int verbose)
526 {
527    BSOCK *bsock = new_bsock();
528    if (!bsock->connect(jcr, retry_interval, max_retry_time, heart_beat,
529                        name, host, service, port, verbose)) {
530        bsock->destroy();
531        bsock = NULL;
532    }
533    return bsock;
534 }
535
536
537
538 /*
539  * Return the string for the error that occurred
540  * on the socket. Only the first error is retained.
541  */
542 const char *bnet_strerror(BSOCK * bsock)
543 {
544    return bsock->bstrerror();
545 }
546
547 /*
548  * Format and send a message
549  *  Returns: false on error
550  *           true  on success
551  */
552 bool bnet_fsend(BSOCK * bs, const char *fmt, ...)
553 {
554    va_list arg_ptr;
555    int maxlen;
556
557    if (bs->errors || bs->is_terminated()) {
558       return false;
559    }
560    /* This probably won't work, but we vsnprintf, then if we
561     * get a negative length or a length greater than our buffer
562     * (depending on which library is used), the printf was truncated, so
563     * get a bigger buffer and try again.
564     */
565    for (;;) {
566       maxlen = sizeof_pool_memory(bs->msg) - 1;
567       va_start(arg_ptr, fmt);
568       bs->msglen = bvsnprintf(bs->msg, maxlen, fmt, arg_ptr);
569       va_end(arg_ptr);
570       if (bs->msglen > 0 && bs->msglen < (maxlen - 5)) {
571          break;
572       }
573       bs->msg = realloc_pool_memory(bs->msg, maxlen + maxlen / 2);
574    }
575    return bs->send();
576 }
577
578 int bnet_get_peer(BSOCK *bs, char *buf, socklen_t buflen) 
579 {
580    return bs->get_peer(buf, buflen);  
581 }
582
583 /*
584  * Set the network buffer size, suggested size is in size.
585  *  Actual size obtained is returned in bs->msglen
586  *
587  *  Returns: 0 on failure
588  *           1 on success
589  */
590 bool bnet_set_buffer_size(BSOCK * bs, uint32_t size, int rw)
591 {
592    return bs->set_buffer_size(size, rw);
593 }
594
595 /*
596  * Set socket non-blocking
597  * Returns previous socket flag
598  */
599 int bnet_set_nonblocking(BSOCK *bsock) 
600 {
601    return bsock->set_nonblocking();
602 }
603
604 /*
605  * Set socket blocking
606  * Returns previous socket flags
607  */
608 int bnet_set_blocking(BSOCK *bsock) 
609 {
610    return bsock->set_blocking();
611 }
612
613 /*
614  * Restores socket flags
615  */
616 void bnet_restore_blocking (BSOCK *bsock, int flags) 
617 {
618    bsock->restore_blocking(flags);
619 }
620
621
622 /*
623  * Send a network "signal" to the other end
624  *  This consists of sending a negative packet length
625  *
626  *  Returns: false on failure
627  *           true  on success
628  */
629 bool bnet_sig(BSOCK * bs, int signal)
630 {
631    return bs->signal(signal);
632 }
633
634 /*
635  * Convert a network "signal" code into
636  * human readable ASCII.
637  */
638 const char *bnet_sig_to_ascii(BSOCK * bs)
639 {
640    static char buf[30];
641    switch (bs->msglen) {
642    case BNET_EOD:
643       return "BNET_EOD";           /* end of data stream */
644    case BNET_EOD_POLL:
645       return "BNET_EOD_POLL";
646    case BNET_STATUS:
647       return "BNET_STATUS";
648    case BNET_TERMINATE:
649       return "BNET_TERMINATE";     /* terminate connection */
650    case BNET_POLL:
651       return "BNET_POLL";
652    case BNET_HEARTBEAT:
653       return "BNET_HEARTBEAT";
654    case BNET_HB_RESPONSE:
655       return "BNET_HB_RESPONSE";
656    case BNET_PROMPT:
657       return "BNET_PROMPT";
658    default:
659       sprintf(buf, _("Unknown sig %d"), (int)bs->msglen);
660       return buf;
661    }
662 }
663
664 /* Initialize internal socket structure.
665  *  This probably should be done in net_open
666  */
667 BSOCK *init_bsock(JCR * jcr, int sockfd, const char *who, const char *host, int port,
668                   struct sockaddr *client_addr)
669 {
670    Dmsg3(100, "who=%s host=%s port=%d\n", who, host, port);
671    BSOCK *bsock = (BSOCK *)malloc(sizeof(BSOCK));
672    memset(bsock, 0, sizeof(BSOCK));
673    bsock->m_fd = sockfd;
674    bsock->tls = NULL;
675    bsock->errors = 0;
676    bsock->m_blocking = 1;
677    bsock->msg = get_pool_memory(PM_MESSAGE);
678    bsock->errmsg = get_pool_memory(PM_MESSAGE);
679    bsock->set_who(bstrdup(who));
680    bsock->set_host(bstrdup(host));
681    bsock->set_port(port);
682    memset(&bsock->peer_addr, 0, sizeof(bsock->peer_addr));
683    memcpy(&bsock->client_addr, client_addr, sizeof(bsock->client_addr));
684    /*
685     * ****FIXME**** reduce this to a few hours once
686     *   heartbeats are implemented
687     */
688    bsock->timeout = 60 * 60 * 6 * 24;   /* 6 days timeout */
689    bsock->set_jcr(jcr);
690    return bsock;
691 }
692
693 BSOCK *dup_bsock(BSOCK *osock)
694 {
695    BSOCK *bsock = (BSOCK *)malloc(sizeof(BSOCK));
696    memcpy(bsock, osock, sizeof(BSOCK));
697    bsock->msg = get_pool_memory(PM_MESSAGE);
698    bsock->errmsg = get_pool_memory(PM_MESSAGE);
699    if (osock->who()) {
700       bsock->set_who(bstrdup(osock->who()));
701    }
702    if (osock->host()) {
703       bsock->set_host(bstrdup(osock->host()));
704    }
705    bsock->set_duped();
706    return bsock;
707 }
708
709 /* Close the network connection */
710 void bnet_close(BSOCK * bsock)
711 {
712    bsock->close();
713 }
714
715 void term_bsock(BSOCK * bsock)
716 {
717    bsock->destroy();
718 }