2 Bacula® - The Network Backup Solution
4 Copyright (C) 2000-2011 Free Software Foundation Europe e.V.
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
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.
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
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.
29 * Network Utility Routines
33 * Adapted and enhanced for Bacula, originally written
34 * for inclusion in the Apcupsd package
43 #define INADDR_NONE -1
47 #define socketRead(fd, buf, len) recv(fd, buf, len, 0)
48 #define socketWrite(fd, buf, len) send(fd, buf, len, 0)
49 #define socketClose(fd) closesocket(fd)
51 #define socketRead(fd, buf, len) read(fd, buf, len)
52 #define socketWrite(fd, buf, len) write(fd, buf, len)
53 #define socketClose(fd) close(fd)
56 #ifndef HAVE_GETADDRINFO
57 static pthread_mutex_t ip_mutex = PTHREAD_MUTEX_INITIALIZER;
61 * Read a nbytes from the network.
62 * It is possible that the total bytes require in several
65 int32_t read_nbytes(BSOCK * bsock, char *ptr, int32_t nbytes)
72 return (tls_bsock_readn(bsock, ptr, nbytes));
79 nread = socketRead(bsock->m_fd, ptr, nleft);
80 if (bsock->is_timed_out() || bsock->is_terminated()) {
86 * For Windows, we must simulate Unix errno on a socket
87 * error in order to handle errors correctly.
89 if (nread == SOCKET_ERROR) {
90 DWORD err = WSAGetLastError();
92 if (err == WSAEINTR) {
94 } else if (err == WSAEWOULDBLOCK) {
97 errno = EIO; /* some other error */
103 if (errno == EINTR) {
106 if (errno == EAGAIN) {
107 bmicrosleep(0, 20000); /* try again in 20ms */
112 return -1; /* error, or EOF */
117 return nbytes - nleft; /* return >= 0 */
121 * Write nbytes to the network.
122 * It may require several writes.
125 int32_t write_nbytes(BSOCK * bsock, char *ptr, int32_t nbytes)
127 int32_t nleft, nwritten;
129 if (bsock->is_spooling()) {
130 nwritten = fwrite(ptr, 1, nbytes, bsock->m_spool_fd);
131 if (nwritten != nbytes) {
133 bsock->b_errno = errno;
134 Qmsg1(bsock->jcr(), M_FATAL, 0, _("Attr spool write error. ERR=%s\n"),
136 Dmsg2(400, "nwritten=%d nbytes=%d.\n", nwritten, nbytes);
137 errno = bsock->b_errno;
146 return (tls_bsock_writen(bsock, ptr, nbytes));
148 #endif /* HAVE_TLS */
154 nwritten = socketWrite(bsock->m_fd, ptr, nleft);
155 if (bsock->is_timed_out() || bsock->is_terminated()) {
161 * For Windows, we must simulate Unix errno on a socket
162 * error in order to handle errors correctly.
164 if (nwritten == SOCKET_ERROR) {
165 DWORD err = WSAGetLastError();
167 if (err == WSAEINTR) {
169 } else if (err == WSAEWOULDBLOCK) {
172 errno = EIO; /* some other error */
177 } while (nwritten == -1 && errno == EINTR);
179 * If connection is non-blocking, we will get EAGAIN, so
180 * use select() to keep from consuming all the CPU
183 if (nwritten == -1 && errno == EAGAIN) {
188 FD_SET((unsigned)bsock->m_fd, &fdset);
191 select(bsock->m_fd + 1, NULL, &fdset, NULL, &tv);
195 return -1; /* error */
200 return nbytes - nleft;
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)
212 * Unfortunately, it is a bit complicated because we have these
215 * 2. Signal including end of data stream
216 * 3. Hard end of file
218 * Using is_bnet_stop() and is_bnet_error() you can figure this all out.
220 int32_t bnet_recv(BSOCK * bsock)
222 return bsock->recv();
227 * Return 1 if there are errors on this bsock or it is closed,
228 * i.e. stop communicating on this line.
230 bool is_bnet_stop(BSOCK * bsock)
232 return bsock->is_stop();
236 * Return number of errors on socket
238 int is_bnet_error(BSOCK * bsock)
240 return bsock->is_error();
244 * Call here after error during closing to suppress error
245 * messages which are due to the other end shutting down too.
247 void bnet_suppress_error_messages(BSOCK * bsock, bool flag)
249 bsock->m_suppress_error_msgs = flag;
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.
257 * Returns: false on failure
260 bool bnet_send(BSOCK *bsock)
262 return bsock->send();
267 * Establish a TLS connection -- server side
268 * Returns: true on success
272 bool bnet_tls_server(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
275 JCR *jcr = bsock->jcr();
277 tls = new_tls_connection(ctx, bsock->m_fd);
279 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS connection initialization failed.\n"));
285 /* Initiate TLS Negotiation */
286 if (!tls_bsock_accept(bsock)) {
287 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS Negotiation failed.\n"));
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"),
299 Dmsg0(50, "TLS server negotiation established.\n");
303 free_tls_connection(tls);
309 * Establish a TLS connection -- client side
310 * Returns: true on success
313 bool bnet_tls_client(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
316 JCR *jcr = bsock->jcr();
318 tls = new_tls_connection(ctx, bsock->m_fd);
320 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS connection initialization failed.\n"));
326 /* Initiate TLS Negotiation */
327 if (!tls_bsock_connect(bsock)) {
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. */
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"),
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"),
347 Dmsg0(50, "TLS client negotiation established.\n");
351 free_tls_connection(tls);
357 bool bnet_tls_server(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
359 Jmsg(bsock->jcr(), M_ABORT, 0, _("TLS enabled but not configured.\n"));
363 bool bnet_tls_client(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
365 Jmsg(bsock->jcr(), M_ABORT, 0, _("TLS enable but not configured.\n"));
369 #endif /* HAVE_TLS */
372 * Wait for a specified time for data to appear on
373 * the BSOCK connection.
375 * Returns: 1 if data available
379 int bnet_wait_data(BSOCK * bsock, int sec)
381 return bsock->wait_data(sec);
385 * As above, but returns on interrupt
387 int bnet_wait_data_intr(BSOCK * bsock, int sec)
389 return bsock->wait_data_intr(sec);
392 #ifndef NETDB_INTERNAL
393 #define NETDB_INTERNAL -1 /* See errno. */
395 #ifndef NETDB_SUCCESS
396 #define NETDB_SUCCESS 0 /* No problem. */
398 #ifndef HOST_NOT_FOUND
399 #define HOST_NOT_FOUND 1 /* Authoritative Answer Host not found. */
402 #define TRY_AGAIN 2 /* Non-Authoritative Host not found, or SERVERFAIL. */
405 #define NO_RECOVERY 3 /* Non recoverable errors, FORMERR, REFUSED, NOTIMP. */
408 #define NO_DATA 4 /* Valid name, no data record of requested type. */
412 const char *resolv_host(int family, const char *host, dlist *addr_list)
415 struct addrinfo hints;
416 struct addrinfo *ai, *rp;
419 memset(&hints, 0, sizeof(struct addrinfo));
420 hints.ai_family = family;
421 hints.ai_socktype = 0;
422 hints.ai_protocol = 0;
425 res = getaddrinfo(host, NULL, &hints, &ai);
427 return gai_strerror(res);
430 for (rp = ai; rp != NULL; rp = rp->ai_next) {
431 switch (rp->ai_addr->sa_family) {
433 addr = New(IPADDR(rp->ai_addr->sa_family));
434 addr->set_type(IPADDR::R_MULTIPLE);
436 * Some serious casting to get the struct in_addr *
437 * rp->ai_addr == struct sockaddr
438 * as this is AF_INET family we can cast that
439 * to struct_sockaddr_in. Of that we need the
440 * address of the sin_addr member which contains a
443 addr->set_addr4(&(((struct sockaddr_in *)rp->ai_addr)->sin_addr));
447 addr = New(IPADDR(rp->ai_addr->sa_family));
448 addr->set_type(IPADDR::R_MULTIPLE);
450 * Some serious casting to get the struct in6_addr *
451 * rp->ai_addr == struct sockaddr
452 * as this is AF_INET6 family we can cast that
453 * to struct_sockaddr_in6. Of that we need the
454 * address of the sin6_addr member which contains a
457 addr->set_addr6(&(((struct sockaddr_in6 *)rp->ai_addr)->sin6_addr));
463 addr_list->append(addr);
470 * Get human readable error for gethostbyname()
472 static const char *gethost_strerror()
478 msg = be.bstrerror();
481 msg = _("No problem.");
484 msg = _("Authoritative answer for host not found.");
487 msg = _("Non-authoritative for host not found, or ServerFail.");
490 msg = _("Non-recoverable errors, FORMERR, REFUSED, or NOTIMP.");
493 msg = _("Valid name, no data record of resquested type.");
496 msg = _("Unknown error.");
501 static const char *resolv_host(int family, const char *host, dlist *addr_list)
508 P(ip_mutex); /* gethostbyname() is not thread safe */
509 #ifdef HAVE_GETHOSTBYNAME2
510 if ((hp = gethostbyname2(host, family)) == NULL) {
512 if ((hp = gethostbyname(host)) == NULL) {
514 /* may be the strerror give not the right result -:( */
515 errmsg = gethost_strerror();
519 for (p = hp->h_addr_list; *p != 0; p++) {
520 switch (hp->h_addrtype) {
522 addr = New(IPADDR(hp->h_addrtype));
523 addr->set_type(IPADDR::R_MULTIPLE);
524 addr->set_addr4((struct in_addr *)*p);
528 addr = New(IPADDR(hp->h_addrtype));
529 addr->set_type(IPADDR::R_MULTIPLE);
530 addr->set_addr6((struct in6_addr *)*p);
536 addr_list->append(addr);
544 static IPADDR *add_any(int family)
546 IPADDR *addr = New(IPADDR(family));
547 addr->set_type(IPADDR::R_MULTIPLE);
548 addr->set_addr_any();
553 * i host = 0 mean INADDR_ANY only ipv4
555 dlist *bnet_host2ipaddrs(const char *host, int family, const char **errstr)
557 struct in_addr inaddr;
561 struct in6_addr inaddr6;
564 dlist *addr_list = New(dlist(addr, &addr->link));
565 if (!host || host[0] == '\0') {
567 addr_list->append(add_any(family));
569 addr_list->append(add_any(AF_INET));
571 addr_list->append(add_any(AF_INET6));
574 } else if (inet_aton(host, &inaddr)) { /* MA Bug 4 */
575 addr = New(IPADDR(AF_INET));
576 addr->set_type(IPADDR::R_MULTIPLE);
577 addr->set_addr4(&inaddr);
578 addr_list->append(addr);
581 if (inet_pton(AF_INET6, host, &inaddr6) > 1) {
582 addr = New(IPADDR(AF_INET6));
583 addr->set_type(IPADDR::R_MULTIPLE);
584 addr->set_addr6(&inaddr6);
585 addr_list->append(addr);
590 errmsg = resolv_host(family, host, addr_list);
593 free_addresses(addr_list);
598 /* We try to resolv host for ipv6 and ipv4, the connection procedure
599 * will try to reach the host for each protocols. We report only "Host
600 * not found" ipv4 message (no need to have ipv6 and ipv4 messages).
602 resolv_host(AF_INET6, host, addr_list);
604 errmsg = resolv_host(AF_INET, host, addr_list);
606 if (addr_list->size() == 0) {
608 free_addresses(addr_list);
617 * This is the "old" way of opening a connection. The preferred way is
618 * now to do what this subroutine does, but inline. That allows the
619 * connect() call to return error status, ...
621 BSOCK *bnet_connect(JCR * jcr, int retry_interval, utime_t max_retry_time,
623 const char *name, char *host, char *service, int port,
626 BSOCK *bsock = new_bsock();
627 if (!bsock->connect(jcr, retry_interval, max_retry_time, heart_beat,
628 name, host, service, port, verbose)) {
636 * Return the string for the error that occurred
637 * on the socket. Only the first error is retained.
639 const char *bnet_strerror(BSOCK * bsock)
641 return bsock->bstrerror();
645 * Format and send a message
646 * Returns: false on error
649 bool bnet_fsend(BSOCK * bs, const char *fmt, ...)
654 if (bs->errors || bs->is_terminated()) {
657 /* This probably won't work, but we vsnprintf, then if we
658 * get a negative length or a length greater than our buffer
659 * (depending on which library is used), the printf was truncated, so
660 * get a bigger buffer and try again.
663 maxlen = sizeof_pool_memory(bs->msg) - 1;
664 va_start(arg_ptr, fmt);
665 bs->msglen = bvsnprintf(bs->msg, maxlen, fmt, arg_ptr);
667 if (bs->msglen > 0 && bs->msglen < (maxlen - 5)) {
670 bs->msg = realloc_pool_memory(bs->msg, maxlen + maxlen / 2);
675 int bnet_get_peer(BSOCK *bs, char *buf, socklen_t buflen)
677 return bs->get_peer(buf, buflen);
681 * Set the network buffer size, suggested size is in size.
682 * Actual size obtained is returned in bs->msglen
684 * Returns: 0 on failure
687 bool bnet_set_buffer_size(BSOCK * bs, uint32_t size, int rw)
689 return bs->set_buffer_size(size, rw);
693 * Set socket non-blocking
694 * Returns previous socket flag
696 int bnet_set_nonblocking(BSOCK *bsock)
698 return bsock->set_nonblocking();
702 * Set socket blocking
703 * Returns previous socket flags
705 int bnet_set_blocking(BSOCK *bsock)
707 return bsock->set_blocking();
711 * Restores socket flags
713 void bnet_restore_blocking (BSOCK *bsock, int flags)
715 bsock->restore_blocking(flags);
719 * Send a network "signal" to the other end
720 * This consists of sending a negative packet length
722 * Returns: false on failure
725 bool bnet_sig(BSOCK * bs, int signal)
727 return bs->signal(signal);
731 * Convert a network "signal" code into
732 * human readable ASCII.
734 const char *bnet_sig_to_ascii(BSOCK * bs)
737 switch (bs->msglen) {
739 return "BNET_EOD"; /* end of data stream */
741 return "BNET_EOD_POLL";
743 return "BNET_STATUS";
745 return "BNET_TERMINATE"; /* terminate connection */
749 return "BNET_HEARTBEAT";
750 case BNET_HB_RESPONSE:
751 return "BNET_HB_RESPONSE";
752 case BNET_SUB_PROMPT:
753 return "BNET_SUB_PROMPT";
754 case BNET_TEXT_INPUT:
755 return "BNET_TEXT_INPUT";
757 sprintf(buf, _("Unknown sig %d"), (int)bs->msglen);
762 /* Initialize internal socket structure.
763 * This probably should be done in net_open
765 BSOCK *init_bsock(JCR * jcr, int sockfd, const char *who, const char *host, int port,
766 struct sockaddr *client_addr)
768 Dmsg3(100, "who=%s host=%s port=%d\n", who, host, port);
769 BSOCK *bsock = (BSOCK *)malloc(sizeof(BSOCK));
770 memset(bsock, 0, sizeof(BSOCK));
771 bsock->m_fd = sockfd;
774 bsock->m_blocking = 1;
775 bsock->msg = get_pool_memory(PM_BSOCK);
776 bsock->errmsg = get_pool_memory(PM_MESSAGE);
777 bsock->set_who(bstrdup(who));
778 bsock->set_host(bstrdup(host));
779 bsock->set_port(port);
780 memset(&bsock->peer_addr, 0, sizeof(bsock->peer_addr));
781 memcpy(&bsock->client_addr, client_addr, sizeof(bsock->client_addr));
783 * ****FIXME**** reduce this to a few hours once
784 * heartbeats are implemented
786 bsock->timeout = 60 * 60 * 6 * 24; /* 6 days timeout */
791 BSOCK *dup_bsock(BSOCK *osock)
793 BSOCK *bsock = (BSOCK *)malloc(sizeof(BSOCK));
794 memcpy(bsock, osock, sizeof(BSOCK));
795 bsock->msg = get_pool_memory(PM_BSOCK);
796 bsock->errmsg = get_pool_memory(PM_MESSAGE);
798 bsock->set_who(bstrdup(osock->who()));
801 bsock->set_host(bstrdup(osock->host()));
803 if (osock->src_addr) {
804 bsock->src_addr = New( IPADDR( *(osock->src_addr)) );
810 /* Close the network connection */
811 void bnet_close(BSOCK * bsock)
816 void term_bsock(BSOCK * bsock)