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