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