2 Bacula® - The Network Backup Solution
4 Copyright (C) 2000-2008 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 two of the GNU 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 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
45 #define INADDR_NONE -1
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)
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)
58 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
66 int32_t read_nbytes(BSOCK * bsock, char *ptr, int32_t nbytes)
73 return (tls_bsock_readn(bsock, ptr, nbytes));
80 nread = socketRead(bsock->m_fd, ptr, nleft);
81 if (bsock->is_timed_out() || bsock->is_terminated()) {
88 if (errno == EAGAIN) {
89 bmicrosleep(0, 200000); /* try again in 200ms */
94 return nread; /* error, or EOF */
99 return nbytes - nleft; /* return >= 0 */
103 * Write nbytes to the network.
104 * It may require several writes.
107 int32_t write_nbytes(BSOCK * bsock, char *ptr, int32_t nbytes)
109 int32_t nleft, nwritten;
111 if (bsock->is_spooling()) {
112 nwritten = fwrite(ptr, 1, nbytes, bsock->m_spool_fd);
113 if (nwritten != nbytes) {
115 bsock->b_errno = errno;
116 Qmsg1(bsock->jcr(), M_FATAL, 0, _("Attr spool write error. ERR=%s\n"),
118 Dmsg2(400, "nwritten=%d nbytes=%d.\n", nwritten, nbytes);
119 errno = bsock->b_errno;
128 return (tls_bsock_writen(bsock, ptr, nbytes));
130 #endif /* HAVE_TLS */
136 nwritten = socketWrite(bsock->m_fd, ptr, nleft);
137 if (bsock->is_timed_out() || bsock->is_terminated()) {
140 } while (nwritten == -1 && errno == EINTR);
142 * If connection is non-blocking, we will get EAGAIN, so
143 * use select() to keep from consuming all the CPU
146 if (nwritten == -1 && errno == EAGAIN) {
151 FD_SET((unsigned)bsock->m_fd, &fdset);
154 select(bsock->m_fd + 1, NULL, &fdset, NULL, &tv);
158 return nwritten; /* error */
163 return nbytes - nleft;
167 * Receive a message from the other end. Each message consists of
168 * two packets. The first is a header that contains the size
169 * of the data that follows in the second packet.
170 * Returns number of bytes read (may return zero)
171 * Returns -1 on signal (BNET_SIGNAL)
172 * Returns -2 on hard end of file (BNET_HARDEOF)
173 * Returns -3 on error (BNET_ERROR)
175 * Unfortunately, it is a bit complicated because we have these
178 * 2. Signal including end of data stream
179 * 3. Hard end of file
181 * Using is_bnet_stop() and is_bnet_error() you can figure this all out.
183 int32_t bnet_recv(BSOCK * bsock)
185 return bsock->recv();
190 * Return 1 if there are errors on this bsock or it is closed,
191 * i.e. stop communicating on this line.
193 bool is_bnet_stop(BSOCK * bsock)
195 return bsock->errors || bsock->is_terminated();
199 * Return number of errors on socket
201 int is_bnet_error(BSOCK * bsock)
203 errno = bsock->b_errno;
204 return bsock->errors;
208 * Call here after error during closing to suppress error
209 * messages which are due to the other end shutting down too.
211 void bnet_suppress_error_messages(BSOCK * bsock, bool flag)
213 bsock->m_suppress_error_msgs = flag;
217 * Send a message over the network. The send consists of
218 * two network packets. The first is sends a 32 bit integer containing
219 * the length of the data packet which follows.
221 * Returns: false on failure
224 bool bnet_send(BSOCK *bsock)
226 return bsock->send();
231 * Establish a TLS connection -- server side
232 * Returns: true on success
236 bool bnet_tls_server(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
239 JCR *jcr = bsock->jcr();
241 tls = new_tls_connection(ctx, bsock->m_fd);
243 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS connection initialization failed.\n"));
249 /* Initiate TLS Negotiation */
250 if (!tls_bsock_accept(bsock)) {
251 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS Negotiation failed.\n"));
256 if (!tls_postconnect_verify_cn(jcr, tls, verify_list)) {
257 Qmsg1(bsock->jcr(), M_FATAL, 0, _("TLS certificate verification failed."
258 " Peer certificate did not match a required commonName\n"),
263 Dmsg0(50, "TLS server negotiation established.\n");
267 free_tls_connection(tls);
273 * Establish a TLS connection -- client side
274 * Returns: true on success
277 bool bnet_tls_client(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
280 JCR *jcr = bsock->jcr();
282 tls = new_tls_connection(ctx, bsock->m_fd);
284 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS connection initialization failed.\n"));
290 /* Initiate TLS Negotiation */
291 if (!tls_bsock_connect(bsock)) {
295 /* If there's an Allowed CN verify list, use that to validate the remote
296 * certificate's CN. Otherwise, we use standard host/CN matching. */
298 if (!tls_postconnect_verify_cn(jcr, tls, verify_list)) {
299 Qmsg1(bsock->jcr(), M_FATAL, 0, _("TLS certificate verification failed."
300 " Peer certificate did not match a required commonName\n"),
305 if (!tls_postconnect_verify_host(jcr, tls, bsock->host())) {
306 Qmsg1(bsock->jcr(), M_FATAL, 0, _("TLS host certificate verification failed. Host name \"%s\" did not match presented certificate\n"),
311 Dmsg0(50, "TLS client negotiation established.\n");
315 free_tls_connection(tls);
321 bool bnet_tls_server(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
323 Jmsg(bsock->jcr(), M_ABORT, 0, _("TLS enabled but not configured.\n"));
327 bool bnet_tls_client(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
329 Jmsg(bsock->jcr(), M_ABORT, 0, _("TLS enable but not configured.\n"));
333 #endif /* HAVE_TLS */
336 * Wait for a specified time for data to appear on
337 * the BSOCK connection.
339 * Returns: 1 if data available
343 int bnet_wait_data(BSOCK * bsock, int sec)
345 return bsock->wait_data(sec);
349 * As above, but returns on interrupt
351 int bnet_wait_data_intr(BSOCK * bsock, int sec)
353 return bsock->wait_data_intr(sec);
356 #ifndef NETDB_INTERNAL
357 #define NETDB_INTERNAL -1 /* See errno. */
359 #ifndef NETDB_SUCCESS
360 #define NETDB_SUCCESS 0 /* No problem. */
362 #ifndef HOST_NOT_FOUND
363 #define HOST_NOT_FOUND 1 /* Authoritative Answer Host not found. */
366 #define TRY_AGAIN 2 /* Non-Authoritative Host not found, or SERVERFAIL. */
369 #define NO_RECOVERY 3 /* Non recoverable errors, FORMERR, REFUSED, NOTIMP. */
372 #define NO_DATA 4 /* Valid name, no data record of requested type. */
376 * Get human readable error for gethostbyname()
378 static const char *gethost_strerror()
384 msg = be.bstrerror();
387 msg = _("No problem.");
390 msg = _("Authoritative answer for host not found.");
393 msg = _("Non-authoritative for host not found, or ServerFail.");
396 msg = _("Non-recoverable errors, FORMERR, REFUSED, or NOTIMP.");
399 msg = _("Valid name, no data record of resquested type.");
402 msg = _("Unknown error.");
410 static IPADDR *add_any(int family)
412 IPADDR *addr = New(IPADDR(family));
413 addr->set_type(IPADDR::R_MULTIPLE);
414 addr->set_addr_any();
418 static const char *resolv_host(int family, const char *host, dlist * addr_list)
423 P(ip_mutex); /* gethostbyname() is not thread safe */
424 #ifdef HAVE_GETHOSTBYNAME2
425 if ((hp = gethostbyname2(host, family)) == NULL) {
427 if ((hp = gethostbyname(host)) == NULL) {
429 /* may be the strerror give not the right result -:( */
430 errmsg = gethost_strerror();
435 for (p = hp->h_addr_list; *p != 0; p++) {
436 IPADDR *addr = New(IPADDR(hp->h_addrtype));
437 addr->set_type(IPADDR::R_MULTIPLE);
438 if (addr->get_family() == AF_INET) {
439 addr->set_addr4((struct in_addr*)*p);
443 addr->set_addr6((struct in6_addr*)*p);
446 addr_list->append(addr);
454 * i host = 0 mean INADDR_ANY only ipv4
456 dlist *bnet_host2ipaddrs(const char *host, int family, const char **errstr)
458 struct in_addr inaddr;
462 struct in6_addr inaddr6;
465 dlist *addr_list = New(dlist(addr, &addr->link));
466 if (!host || host[0] == '\0') {
468 addr_list->append(add_any(family));
470 addr_list->append(add_any(AF_INET));
472 addr_list->append(add_any(AF_INET6));
475 } else if (inet_aton(host, &inaddr)) { /* MA Bug 4 */
476 addr = New(IPADDR(AF_INET));
477 addr->set_type(IPADDR::R_MULTIPLE);
478 addr->set_addr4(&inaddr);
479 addr_list->append(addr);
482 if (inet_pton(AF_INET6, host, &inaddr6) > 1) {
483 addr = New(IPADDR(AF_INET6));
484 addr->set_type(IPADDR::R_MULTIPLE);
485 addr->set_addr6(&inaddr6);
486 addr_list->append(addr);
491 errmsg = resolv_host(family, host, addr_list);
494 free_addresses(addr_list);
498 errmsg = resolv_host(AF_INET, host, addr_list);
501 errmsg = resolv_host(AF_INET6, host, addr_list);
506 free_addresses(addr_list);
515 * This is the "old" way of opening a connection. The preferred way is
516 * now to do what this subroutine does, but inline. That allows the
517 * connect() call to return error status, ...
519 BSOCK *bnet_connect(JCR * jcr, int retry_interval, utime_t max_retry_time,
521 const char *name, char *host, char *service, int port,
524 BSOCK *bsock = new_bsock();
525 if (!bsock->connect(jcr, retry_interval, max_retry_time, heart_beat,
526 name, host, service, port, verbose)) {
536 * Return the string for the error that occurred
537 * on the socket. Only the first error is retained.
539 const char *bnet_strerror(BSOCK * bsock)
541 return bsock->bstrerror();
545 * Format and send a message
546 * Returns: false on error
549 bool bnet_fsend(BSOCK * bs, const char *fmt, ...)
554 if (bs->errors || bs->is_terminated()) {
557 /* This probably won't work, but we vsnprintf, then if we
558 * get a negative length or a length greater than our buffer
559 * (depending on which library is used), the printf was truncated, so
560 * get a bigger buffer and try again.
563 maxlen = sizeof_pool_memory(bs->msg) - 1;
564 va_start(arg_ptr, fmt);
565 bs->msglen = bvsnprintf(bs->msg, maxlen, fmt, arg_ptr);
567 if (bs->msglen > 0 && bs->msglen < (maxlen - 5)) {
570 bs->msg = realloc_pool_memory(bs->msg, maxlen + maxlen / 2);
575 int bnet_get_peer(BSOCK *bs, char *buf, socklen_t buflen)
577 return bs->get_peer(buf, buflen);
581 * Set the network buffer size, suggested size is in size.
582 * Actual size obtained is returned in bs->msglen
584 * Returns: 0 on failure
587 bool bnet_set_buffer_size(BSOCK * bs, uint32_t size, int rw)
589 return bs->set_buffer_size(size, rw);
593 * Set socket non-blocking
594 * Returns previous socket flag
596 int bnet_set_nonblocking(BSOCK *bsock)
598 return bsock->set_nonblocking();
602 * Set socket blocking
603 * Returns previous socket flags
605 int bnet_set_blocking(BSOCK *bsock)
607 return bsock->set_blocking();
611 * Restores socket flags
613 void bnet_restore_blocking (BSOCK *bsock, int flags)
615 bsock->restore_blocking(flags);
620 * Send a network "signal" to the other end
621 * This consists of sending a negative packet length
623 * Returns: false on failure
626 bool bnet_sig(BSOCK * bs, int signal)
628 return bs->signal(signal);
632 * Convert a network "signal" code into
633 * human readable ASCII.
635 const char *bnet_sig_to_ascii(BSOCK * bs)
638 switch (bs->msglen) {
640 return "BNET_EOD"; /* end of data stream */
642 return "BNET_EOD_POLL";
644 return "BNET_STATUS";
646 return "BNET_TERMINATE"; /* terminate connection */
650 return "BNET_HEARTBEAT";
651 case BNET_HB_RESPONSE:
652 return "BNET_HB_RESPONSE";
654 return "BNET_PROMPT";
656 sprintf(buf, _("Unknown sig %d"), (int)bs->msglen);
661 /* Initialize internal socket structure.
662 * This probably should be done in net_open
664 BSOCK *init_bsock(JCR * jcr, int sockfd, const char *who, const char *host, int port,
665 struct sockaddr *client_addr)
667 Dmsg3(100, "who=%s host=%s port=%d\n", who, host, port);
668 BSOCK *bsock = (BSOCK *)malloc(sizeof(BSOCK));
669 memset(bsock, 0, sizeof(BSOCK));
670 bsock->m_fd = sockfd;
673 bsock->m_blocking = 1;
674 bsock->msg = get_pool_memory(PM_MESSAGE);
675 bsock->errmsg = get_pool_memory(PM_MESSAGE);
676 bsock->set_who(bstrdup(who));
677 bsock->set_host(bstrdup(host));
678 bsock->set_port(port);
679 memset(&bsock->peer_addr, 0, sizeof(bsock->peer_addr));
680 memcpy(&bsock->client_addr, client_addr, sizeof(bsock->client_addr));
682 * ****FIXME**** reduce this to a few hours once
683 * heartbeats are implemented
685 bsock->timeout = 60 * 60 * 6 * 24; /* 6 days timeout */
690 BSOCK *dup_bsock(BSOCK *osock)
692 BSOCK *bsock = (BSOCK *)malloc(sizeof(BSOCK));
693 memcpy(bsock, osock, sizeof(BSOCK));
694 bsock->msg = get_pool_memory(PM_MESSAGE);
695 bsock->errmsg = get_pool_memory(PM_MESSAGE);
697 bsock->set_who(bstrdup(osock->who()));
700 bsock->set_host(bstrdup(osock->host()));
706 /* Close the network connection */
707 void bnet_close(BSOCK * bsock)
712 void term_bsock(BSOCK * bsock)