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 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
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()) {
87 * For Windows, we must simulate Unix errno on a socket
88 * error in order to handle errors correctly.
90 if (nread == SOCKET_ERROR) {
91 DWORD err = WSAGetLastError();
93 if (err == WSAEINTR) {
95 } else if (err == WSAEWOULDBLOCK) {
98 errno = EIO; /* some other error */
104 if (errno == EINTR) {
107 if (errno == EAGAIN) {
108 bmicrosleep(0, 20000); /* try again in 20ms */
113 return -1; /* error, or EOF */
118 return nbytes - nleft; /* return >= 0 */
122 * Write nbytes to the network.
123 * It may require several writes.
126 int32_t write_nbytes(BSOCK * bsock, char *ptr, int32_t nbytes)
128 int32_t nleft, nwritten;
130 if (bsock->is_spooling()) {
131 nwritten = fwrite(ptr, 1, nbytes, bsock->m_spool_fd);
132 if (nwritten != nbytes) {
134 bsock->b_errno = errno;
135 Qmsg1(bsock->jcr(), M_FATAL, 0, _("Attr spool write error. ERR=%s\n"),
137 Dmsg2(400, "nwritten=%d nbytes=%d.\n", nwritten, nbytes);
138 errno = bsock->b_errno;
147 return (tls_bsock_writen(bsock, ptr, nbytes));
149 #endif /* HAVE_TLS */
155 nwritten = socketWrite(bsock->m_fd, ptr, nleft);
156 if (bsock->is_timed_out() || bsock->is_terminated()) {
162 * For Windows, we must simulate Unix errno on a socket
163 * error in order to handle errors correctly.
165 if (nwritten == SOCKET_ERROR) {
166 DWORD err = WSAGetLastError();
168 if (err == WSAEINTR) {
170 } else if (err == WSAEWOULDBLOCK) {
173 errno = EIO; /* some other error */
178 } while (nwritten == -1 && errno == EINTR);
180 * If connection is non-blocking, we will get EAGAIN, so
181 * use select() to keep from consuming all the CPU
184 if (nwritten == -1 && errno == EAGAIN) {
189 FD_SET((unsigned)bsock->m_fd, &fdset);
192 select(bsock->m_fd + 1, NULL, &fdset, NULL, &tv);
196 return -1; /* error */
201 return nbytes - nleft;
205 * Receive a message from the other end. Each message consists of
206 * two packets. The first is a header that contains the size
207 * of the data that follows in the second packet.
208 * Returns number of bytes read (may return zero)
209 * Returns -1 on signal (BNET_SIGNAL)
210 * Returns -2 on hard end of file (BNET_HARDEOF)
211 * Returns -3 on error (BNET_ERROR)
213 * Unfortunately, it is a bit complicated because we have these
216 * 2. Signal including end of data stream
217 * 3. Hard end of file
219 * Using is_bnet_stop() and is_bnet_error() you can figure this all out.
221 int32_t bnet_recv(BSOCK * bsock)
223 return bsock->recv();
228 * Return 1 if there are errors on this bsock or it is closed,
229 * i.e. stop communicating on this line.
231 bool is_bnet_stop(BSOCK * bsock)
233 return bsock->is_stop();
237 * Return number of errors on socket
239 int is_bnet_error(BSOCK * bsock)
241 return bsock->is_error();
245 * Call here after error during closing to suppress error
246 * messages which are due to the other end shutting down too.
248 void bnet_suppress_error_messages(BSOCK * bsock, bool flag)
250 bsock->m_suppress_error_msgs = flag;
254 * Send a message over the network. The send consists of
255 * two network packets. The first is sends a 32 bit integer containing
256 * the length of the data packet which follows.
258 * Returns: false on failure
261 bool bnet_send(BSOCK *bsock)
263 return bsock->send();
268 * Establish a TLS connection -- server side
269 * Returns: true on success
273 bool bnet_tls_server(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
276 JCR *jcr = bsock->jcr();
278 tls = new_tls_connection(ctx, bsock->m_fd);
280 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS connection initialization failed.\n"));
286 /* Initiate TLS Negotiation */
287 if (!tls_bsock_accept(bsock)) {
288 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS Negotiation failed.\n"));
293 if (!tls_postconnect_verify_cn(jcr, tls, verify_list)) {
294 Qmsg1(bsock->jcr(), M_FATAL, 0, _("TLS certificate verification failed."
295 " Peer certificate did not match a required commonName\n"),
300 Dmsg0(50, "TLS server negotiation established.\n");
304 free_tls_connection(tls);
310 * Establish a TLS connection -- client side
311 * Returns: true on success
314 bool bnet_tls_client(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
317 JCR *jcr = bsock->jcr();
319 tls = new_tls_connection(ctx, bsock->m_fd);
321 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS connection initialization failed.\n"));
327 /* Initiate TLS Negotiation */
328 if (!tls_bsock_connect(bsock)) {
332 /* If there's an Allowed CN verify list, use that to validate the remote
333 * certificate's CN. Otherwise, we use standard host/CN matching. */
335 if (!tls_postconnect_verify_cn(jcr, tls, verify_list)) {
336 Qmsg1(bsock->jcr(), M_FATAL, 0, _("TLS certificate verification failed."
337 " Peer certificate did not match a required commonName\n"),
342 if (!tls_postconnect_verify_host(jcr, tls, bsock->host())) {
343 Qmsg1(bsock->jcr(), M_FATAL, 0, _("TLS host certificate verification failed. Host name \"%s\" did not match presented certificate\n"),
348 Dmsg0(50, "TLS client negotiation established.\n");
352 free_tls_connection(tls);
358 bool bnet_tls_server(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
360 Jmsg(bsock->jcr(), M_ABORT, 0, _("TLS enabled but not configured.\n"));
364 bool bnet_tls_client(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
366 Jmsg(bsock->jcr(), M_ABORT, 0, _("TLS enable but not configured.\n"));
370 #endif /* HAVE_TLS */
373 * Wait for a specified time for data to appear on
374 * the BSOCK connection.
376 * Returns: 1 if data available
380 int bnet_wait_data(BSOCK * bsock, int sec)
382 return bsock->wait_data(sec);
386 * As above, but returns on interrupt
388 int bnet_wait_data_intr(BSOCK * bsock, int sec)
390 return bsock->wait_data_intr(sec);
393 #ifndef NETDB_INTERNAL
394 #define NETDB_INTERNAL -1 /* See errno. */
396 #ifndef NETDB_SUCCESS
397 #define NETDB_SUCCESS 0 /* No problem. */
399 #ifndef HOST_NOT_FOUND
400 #define HOST_NOT_FOUND 1 /* Authoritative Answer Host not found. */
403 #define TRY_AGAIN 2 /* Non-Authoritative Host not found, or SERVERFAIL. */
406 #define NO_RECOVERY 3 /* Non recoverable errors, FORMERR, REFUSED, NOTIMP. */
409 #define NO_DATA 4 /* Valid name, no data record of requested type. */
413 * Get human readable error for gethostbyname()
415 static const char *gethost_strerror()
421 msg = be.bstrerror();
424 msg = _("No problem.");
427 msg = _("Authoritative answer for host not found.");
430 msg = _("Non-authoritative for host not found, or ServerFail.");
433 msg = _("Non-recoverable errors, FORMERR, REFUSED, or NOTIMP.");
436 msg = _("Valid name, no data record of resquested type.");
439 msg = _("Unknown error.");
447 static IPADDR *add_any(int family)
449 IPADDR *addr = New(IPADDR(family));
450 addr->set_type(IPADDR::R_MULTIPLE);
451 addr->set_addr_any();
455 static const char *resolv_host(int family, const char *host, dlist * addr_list)
460 P(ip_mutex); /* gethostbyname() is not thread safe */
461 #ifdef HAVE_GETHOSTBYNAME2
462 if ((hp = gethostbyname2(host, family)) == NULL) {
464 if ((hp = gethostbyname(host)) == NULL) {
466 /* may be the strerror give not the right result -:( */
467 errmsg = gethost_strerror();
472 for (p = hp->h_addr_list; *p != 0; p++) {
473 IPADDR *addr = New(IPADDR(hp->h_addrtype));
474 addr->set_type(IPADDR::R_MULTIPLE);
475 if (addr->get_family() == AF_INET) {
476 addr->set_addr4((struct in_addr*)*p);
480 addr->set_addr6((struct in6_addr*)*p);
483 addr_list->append(addr);
491 * i host = 0 mean INADDR_ANY only ipv4
493 dlist *bnet_host2ipaddrs(const char *host, int family, const char **errstr)
495 struct in_addr inaddr;
499 struct in6_addr inaddr6;
502 dlist *addr_list = New(dlist(addr, &addr->link));
503 if (!host || host[0] == '\0') {
505 addr_list->append(add_any(family));
507 addr_list->append(add_any(AF_INET));
509 addr_list->append(add_any(AF_INET6));
512 } else if (inet_aton(host, &inaddr)) { /* MA Bug 4 */
513 addr = New(IPADDR(AF_INET));
514 addr->set_type(IPADDR::R_MULTIPLE);
515 addr->set_addr4(&inaddr);
516 addr_list->append(addr);
519 if (inet_pton(AF_INET6, host, &inaddr6) > 1) {
520 addr = New(IPADDR(AF_INET6));
521 addr->set_type(IPADDR::R_MULTIPLE);
522 addr->set_addr6(&inaddr6);
523 addr_list->append(addr);
528 errmsg = resolv_host(family, host, addr_list);
531 free_addresses(addr_list);
536 /* We try to resolv host for ipv6 and ipv4, the connection procedure
537 * will try to reach the host for each protocols. We report only "Host
538 * not found" ipv4 message (no need to have ipv6 and ipv4 messages).
540 resolv_host(AF_INET6, host, addr_list);
542 errmsg = resolv_host(AF_INET, host, addr_list);
544 if (addr_list->size() == 0) {
546 free_addresses(addr_list);
555 * This is the "old" way of opening a connection. The preferred way is
556 * now to do what this subroutine does, but inline. That allows the
557 * connect() call to return error status, ...
559 BSOCK *bnet_connect(JCR * jcr, int retry_interval, utime_t max_retry_time,
561 const char *name, char *host, char *service, int port,
564 BSOCK *bsock = new_bsock();
565 if (!bsock->connect(jcr, retry_interval, max_retry_time, heart_beat,
566 name, host, service, port, verbose)) {
576 * Return the string for the error that occurred
577 * on the socket. Only the first error is retained.
579 const char *bnet_strerror(BSOCK * bsock)
581 return bsock->bstrerror();
585 * Format and send a message
586 * Returns: false on error
589 bool bnet_fsend(BSOCK * bs, const char *fmt, ...)
594 if (bs->errors || bs->is_terminated()) {
597 /* This probably won't work, but we vsnprintf, then if we
598 * get a negative length or a length greater than our buffer
599 * (depending on which library is used), the printf was truncated, so
600 * get a bigger buffer and try again.
603 maxlen = sizeof_pool_memory(bs->msg) - 1;
604 va_start(arg_ptr, fmt);
605 bs->msglen = bvsnprintf(bs->msg, maxlen, fmt, arg_ptr);
607 if (bs->msglen > 0 && bs->msglen < (maxlen - 5)) {
610 bs->msg = realloc_pool_memory(bs->msg, maxlen + maxlen / 2);
615 int bnet_get_peer(BSOCK *bs, char *buf, socklen_t buflen)
617 return bs->get_peer(buf, buflen);
621 * Set the network buffer size, suggested size is in size.
622 * Actual size obtained is returned in bs->msglen
624 * Returns: 0 on failure
627 bool bnet_set_buffer_size(BSOCK * bs, uint32_t size, int rw)
629 return bs->set_buffer_size(size, rw);
633 * Set socket non-blocking
634 * Returns previous socket flag
636 int bnet_set_nonblocking(BSOCK *bsock)
638 return bsock->set_nonblocking();
642 * Set socket blocking
643 * Returns previous socket flags
645 int bnet_set_blocking(BSOCK *bsock)
647 return bsock->set_blocking();
651 * Restores socket flags
653 void bnet_restore_blocking (BSOCK *bsock, int flags)
655 bsock->restore_blocking(flags);
660 * Send a network "signal" to the other end
661 * This consists of sending a negative packet length
663 * Returns: false on failure
666 bool bnet_sig(BSOCK * bs, int signal)
668 return bs->signal(signal);
672 * Convert a network "signal" code into
673 * human readable ASCII.
675 const char *bnet_sig_to_ascii(BSOCK * bs)
678 switch (bs->msglen) {
680 return "BNET_EOD"; /* end of data stream */
682 return "BNET_EOD_POLL";
684 return "BNET_STATUS";
686 return "BNET_TERMINATE"; /* terminate connection */
690 return "BNET_HEARTBEAT";
691 case BNET_HB_RESPONSE:
692 return "BNET_HB_RESPONSE";
693 case BNET_SUB_PROMPT:
694 return "BNET_SUB_PROMPT";
695 case BNET_TEXT_INPUT:
696 return "BNET_TEXT_INPUT";
698 sprintf(buf, _("Unknown sig %d"), (int)bs->msglen);
703 /* Initialize internal socket structure.
704 * This probably should be done in net_open
706 BSOCK *init_bsock(JCR * jcr, int sockfd, const char *who, const char *host, int port,
707 struct sockaddr *client_addr)
709 Dmsg3(100, "who=%s host=%s port=%d\n", who, host, port);
710 BSOCK *bsock = (BSOCK *)malloc(sizeof(BSOCK));
711 memset(bsock, 0, sizeof(BSOCK));
712 bsock->m_fd = sockfd;
715 bsock->m_blocking = 1;
716 bsock->msg = get_pool_memory(PM_BSOCK);
717 bsock->errmsg = get_pool_memory(PM_MESSAGE);
718 bsock->set_who(bstrdup(who));
719 bsock->set_host(bstrdup(host));
720 bsock->set_port(port);
721 memset(&bsock->peer_addr, 0, sizeof(bsock->peer_addr));
722 memcpy(&bsock->client_addr, client_addr, sizeof(bsock->client_addr));
724 * ****FIXME**** reduce this to a few hours once
725 * heartbeats are implemented
727 bsock->timeout = 60 * 60 * 6 * 24; /* 6 days timeout */
732 BSOCK *dup_bsock(BSOCK *osock)
734 BSOCK *bsock = (BSOCK *)malloc(sizeof(BSOCK));
735 memcpy(bsock, osock, sizeof(BSOCK));
736 bsock->msg = get_pool_memory(PM_BSOCK);
737 bsock->errmsg = get_pool_memory(PM_MESSAGE);
739 bsock->set_who(bstrdup(osock->who()));
742 bsock->set_host(bstrdup(osock->host()));
744 if (osock->src_addr) {
745 bsock->src_addr = New( IPADDR( *(osock->src_addr)) );
751 /* Close the network connection */
752 void bnet_close(BSOCK * bsock)
757 void term_bsock(BSOCK * bsock)