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