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