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
44 #define INADDR_NONE -1
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)
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)
57 static pthread_mutex_t ip_mutex = PTHREAD_MUTEX_INITIALIZER;
60 * Read a nbytes from the network.
61 * 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 * Get human readable error for gethostbyname()
414 static const char *gethost_strerror()
420 msg = be.bstrerror();
423 msg = _("No problem.");
426 msg = _("Authoritative answer for host not found.");
429 msg = _("Non-authoritative for host not found, or ServerFail.");
432 msg = _("Non-recoverable errors, FORMERR, REFUSED, or NOTIMP.");
435 msg = _("Valid name, no data record of resquested type.");
438 msg = _("Unknown error.");
446 static IPADDR *add_any(int family)
448 IPADDR *addr = New(IPADDR(family));
449 addr->set_type(IPADDR::R_MULTIPLE);
450 addr->set_addr_any();
454 static const char *resolv_host(int family, const char *host, dlist * addr_list)
459 P(ip_mutex); /* gethostbyname() is not thread safe */
460 #ifdef HAVE_GETHOSTBYNAME2
461 if ((hp = gethostbyname2(host, family)) == NULL) {
463 if ((hp = gethostbyname(host)) == NULL) {
465 /* may be the strerror give not the right result -:( */
466 errmsg = gethost_strerror();
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);
479 addr->set_addr6((struct in6_addr*)*p);
482 addr_list->append(addr);
490 * i host = 0 mean INADDR_ANY only ipv4
492 dlist *bnet_host2ipaddrs(const char *host, int family, const char **errstr)
494 struct in_addr inaddr;
498 struct in6_addr inaddr6;
501 dlist *addr_list = New(dlist(addr, &addr->link));
502 if (!host || host[0] == '\0') {
504 addr_list->append(add_any(family));
506 addr_list->append(add_any(AF_INET));
508 addr_list->append(add_any(AF_INET6));
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);
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);
527 errmsg = resolv_host(family, host, addr_list);
530 free_addresses(addr_list);
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).
539 resolv_host(AF_INET6, host, addr_list);
541 errmsg = resolv_host(AF_INET, host, addr_list);
543 if (addr_list->size() == 0) {
545 free_addresses(addr_list);
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, ...
558 BSOCK *bnet_connect(JCR * jcr, int retry_interval, utime_t max_retry_time,
560 const char *name, char *host, char *service, int port,
563 BSOCK *bsock = new_bsock();
564 if (!bsock->connect(jcr, retry_interval, max_retry_time, heart_beat,
565 name, host, service, port, verbose)) {
575 * Return the string for the error that occurred
576 * on the socket. Only the first error is retained.
578 const char *bnet_strerror(BSOCK * bsock)
580 return bsock->bstrerror();
584 * Format and send a message
585 * Returns: false on error
588 bool bnet_fsend(BSOCK * bs, const char *fmt, ...)
593 if (bs->errors || bs->is_terminated()) {
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.
602 maxlen = sizeof_pool_memory(bs->msg) - 1;
603 va_start(arg_ptr, fmt);
604 bs->msglen = bvsnprintf(bs->msg, maxlen, fmt, arg_ptr);
606 if (bs->msglen > 0 && bs->msglen < (maxlen - 5)) {
609 bs->msg = realloc_pool_memory(bs->msg, maxlen + maxlen / 2);
614 int bnet_get_peer(BSOCK *bs, char *buf, socklen_t buflen)
616 return bs->get_peer(buf, buflen);
620 * Set the network buffer size, suggested size is in size.
621 * Actual size obtained is returned in bs->msglen
623 * Returns: 0 on failure
626 bool bnet_set_buffer_size(BSOCK * bs, uint32_t size, int rw)
628 return bs->set_buffer_size(size, rw);
632 * Set socket non-blocking
633 * Returns previous socket flag
635 int bnet_set_nonblocking(BSOCK *bsock)
637 return bsock->set_nonblocking();
641 * Set socket blocking
642 * Returns previous socket flags
644 int bnet_set_blocking(BSOCK *bsock)
646 return bsock->set_blocking();
650 * Restores socket flags
652 void bnet_restore_blocking (BSOCK *bsock, int flags)
654 bsock->restore_blocking(flags);
659 * Send a network "signal" to the other end
660 * This consists of sending a negative packet length
662 * Returns: false on failure
665 bool bnet_sig(BSOCK * bs, int signal)
667 return bs->signal(signal);
671 * Convert a network "signal" code into
672 * human readable ASCII.
674 const char *bnet_sig_to_ascii(BSOCK * bs)
677 switch (bs->msglen) {
679 return "BNET_EOD"; /* end of data stream */
681 return "BNET_EOD_POLL";
683 return "BNET_STATUS";
685 return "BNET_TERMINATE"; /* terminate connection */
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";
697 sprintf(buf, _("Unknown sig %d"), (int)bs->msglen);
702 /* Initialize internal socket structure.
703 * This probably should be done in net_open
705 BSOCK *init_bsock(JCR * jcr, int sockfd, const char *who, const char *host, int port,
706 struct sockaddr *client_addr)
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;
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));
723 * ****FIXME**** reduce this to a few hours once
724 * heartbeats are implemented
726 bsock->timeout = 60 * 60 * 6 * 24; /* 6 days timeout */
731 BSOCK *dup_bsock(BSOCK *osock)
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);
738 bsock->set_who(bstrdup(osock->who()));
741 bsock->set_host(bstrdup(osock->host()));
743 if (osock->src_addr) {
744 bsock->src_addr = New( IPADDR( *(osock->src_addr)) );
750 /* Close the network connection */
751 void bnet_close(BSOCK * bsock)
756 void term_bsock(BSOCK * bsock)