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