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()) {
87 if (errno == EAGAIN) {
88 bmicrosleep(0, 20000); /* try again in 20ms */
93 return nread; /* error, or EOF */
98 return nbytes - nleft; /* return >= 0 */
102 * Write nbytes to the network.
103 * It may require several writes.
106 int32_t write_nbytes(BSOCK * bsock, char *ptr, int32_t nbytes)
108 int32_t nleft, nwritten;
110 if (bsock->is_spooling()) {
111 nwritten = fwrite(ptr, 1, nbytes, bsock->m_spool_fd);
112 if (nwritten != nbytes) {
114 bsock->b_errno = errno;
115 Qmsg1(bsock->jcr(), M_FATAL, 0, _("Attr spool write error. ERR=%s\n"),
117 Dmsg2(400, "nwritten=%d nbytes=%d.\n", nwritten, nbytes);
118 errno = bsock->b_errno;
127 return (tls_bsock_writen(bsock, ptr, nbytes));
129 #endif /* HAVE_TLS */
135 nwritten = socketWrite(bsock->m_fd, ptr, nleft);
136 if (bsock->is_timed_out() || bsock->is_terminated()) {
139 } while (nwritten == -1 && errno == EINTR);
141 * If connection is non-blocking, we will get EAGAIN, so
142 * use select() to keep from consuming all the CPU
145 if (nwritten == -1 && errno == EAGAIN) {
150 FD_SET((unsigned)bsock->m_fd, &fdset);
153 select(bsock->m_fd + 1, NULL, &fdset, NULL, &tv);
157 return nwritten; /* error */
162 return nbytes - nleft;
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)
174 * Unfortunately, it is a bit complicated because we have these
177 * 2. Signal including end of data stream
178 * 3. Hard end of file
180 * Using is_bnet_stop() and is_bnet_error() you can figure this all out.
182 int32_t bnet_recv(BSOCK * bsock)
184 return bsock->recv();
189 * Return 1 if there are errors on this bsock or it is closed,
190 * i.e. stop communicating on this line.
192 bool is_bnet_stop(BSOCK * bsock)
194 return bsock->is_stop();
198 * Return number of errors on socket
200 int is_bnet_error(BSOCK * bsock)
202 return bsock->is_error();
206 * Call here after error during closing to suppress error
207 * messages which are due to the other end shutting down too.
209 void bnet_suppress_error_messages(BSOCK * bsock, bool flag)
211 bsock->m_suppress_error_msgs = flag;
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.
219 * Returns: false on failure
222 bool bnet_send(BSOCK *bsock)
224 return bsock->send();
229 * Establish a TLS connection -- server side
230 * Returns: true on success
234 bool bnet_tls_server(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
237 JCR *jcr = bsock->jcr();
239 tls = new_tls_connection(ctx, bsock->m_fd);
241 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS connection initialization failed.\n"));
247 /* Initiate TLS Negotiation */
248 if (!tls_bsock_accept(bsock)) {
249 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS Negotiation failed.\n"));
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"),
261 Dmsg0(50, "TLS server negotiation established.\n");
265 free_tls_connection(tls);
271 * Establish a TLS connection -- client side
272 * Returns: true on success
275 bool bnet_tls_client(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
278 JCR *jcr = bsock->jcr();
280 tls = new_tls_connection(ctx, bsock->m_fd);
282 Qmsg0(bsock->jcr(), M_FATAL, 0, _("TLS connection initialization failed.\n"));
288 /* Initiate TLS Negotiation */
289 if (!tls_bsock_connect(bsock)) {
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. */
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"),
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"),
309 Dmsg0(50, "TLS client negotiation established.\n");
313 free_tls_connection(tls);
319 bool bnet_tls_server(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
321 Jmsg(bsock->jcr(), M_ABORT, 0, _("TLS enabled but not configured.\n"));
325 bool bnet_tls_client(TLS_CONTEXT *ctx, BSOCK * bsock, alist *verify_list)
327 Jmsg(bsock->jcr(), M_ABORT, 0, _("TLS enable but not configured.\n"));
331 #endif /* HAVE_TLS */
334 * Wait for a specified time for data to appear on
335 * the BSOCK connection.
337 * Returns: 1 if data available
341 int bnet_wait_data(BSOCK * bsock, int sec)
343 return bsock->wait_data(sec);
347 * As above, but returns on interrupt
349 int bnet_wait_data_intr(BSOCK * bsock, int sec)
351 return bsock->wait_data_intr(sec);
354 #ifndef NETDB_INTERNAL
355 #define NETDB_INTERNAL -1 /* See errno. */
357 #ifndef NETDB_SUCCESS
358 #define NETDB_SUCCESS 0 /* No problem. */
360 #ifndef HOST_NOT_FOUND
361 #define HOST_NOT_FOUND 1 /* Authoritative Answer Host not found. */
364 #define TRY_AGAIN 2 /* Non-Authoritative Host not found, or SERVERFAIL. */
367 #define NO_RECOVERY 3 /* Non recoverable errors, FORMERR, REFUSED, NOTIMP. */
370 #define NO_DATA 4 /* Valid name, no data record of requested type. */
374 * Get human readable error for gethostbyname()
376 static const char *gethost_strerror()
382 msg = be.bstrerror();
385 msg = _("No problem.");
388 msg = _("Authoritative answer for host not found.");
391 msg = _("Non-authoritative for host not found, or ServerFail.");
394 msg = _("Non-recoverable errors, FORMERR, REFUSED, or NOTIMP.");
397 msg = _("Valid name, no data record of resquested type.");
400 msg = _("Unknown error.");
408 static IPADDR *add_any(int family)
410 IPADDR *addr = New(IPADDR(family));
411 addr->set_type(IPADDR::R_MULTIPLE);
412 addr->set_addr_any();
416 static const char *resolv_host(int family, const char *host, dlist * addr_list)
421 P(ip_mutex); /* gethostbyname() is not thread safe */
422 #ifdef HAVE_GETHOSTBYNAME2
423 if ((hp = gethostbyname2(host, family)) == NULL) {
425 if ((hp = gethostbyname(host)) == NULL) {
427 /* may be the strerror give not the right result -:( */
428 errmsg = gethost_strerror();
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);
441 addr->set_addr6((struct in6_addr*)*p);
444 addr_list->append(addr);
452 * i host = 0 mean INADDR_ANY only ipv4
454 dlist *bnet_host2ipaddrs(const char *host, int family, const char **errstr)
456 struct in_addr inaddr;
460 struct in6_addr inaddr6;
463 dlist *addr_list = New(dlist(addr, &addr->link));
464 if (!host || host[0] == '\0') {
466 addr_list->append(add_any(family));
468 addr_list->append(add_any(AF_INET));
470 addr_list->append(add_any(AF_INET6));
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);
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);
489 errmsg = resolv_host(family, host, addr_list);
492 free_addresses(addr_list);
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).
501 resolv_host(AF_INET6, host, addr_list);
503 errmsg = resolv_host(AF_INET, host, addr_list);
505 if (addr_list->size() == 0) {
507 free_addresses(addr_list);
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, ...
520 BSOCK *bnet_connect(JCR * jcr, int retry_interval, utime_t max_retry_time,
522 const char *name, char *host, char *service, int port,
525 BSOCK *bsock = new_bsock();
526 if (!bsock->connect(jcr, retry_interval, max_retry_time, heart_beat,
527 name, host, service, port, verbose)) {
537 * Return the string for the error that occurred
538 * on the socket. Only the first error is retained.
540 const char *bnet_strerror(BSOCK * bsock)
542 return bsock->bstrerror();
546 * Format and send a message
547 * Returns: false on error
550 bool bnet_fsend(BSOCK * bs, const char *fmt, ...)
555 if (bs->errors || bs->is_terminated()) {
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.
564 maxlen = sizeof_pool_memory(bs->msg) - 1;
565 va_start(arg_ptr, fmt);
566 bs->msglen = bvsnprintf(bs->msg, maxlen, fmt, arg_ptr);
568 if (bs->msglen > 0 && bs->msglen < (maxlen - 5)) {
571 bs->msg = realloc_pool_memory(bs->msg, maxlen + maxlen / 2);
576 int bnet_get_peer(BSOCK *bs, char *buf, socklen_t buflen)
578 return bs->get_peer(buf, buflen);
582 * Set the network buffer size, suggested size is in size.
583 * Actual size obtained is returned in bs->msglen
585 * Returns: 0 on failure
588 bool bnet_set_buffer_size(BSOCK * bs, uint32_t size, int rw)
590 return bs->set_buffer_size(size, rw);
594 * Set socket non-blocking
595 * Returns previous socket flag
597 int bnet_set_nonblocking(BSOCK *bsock)
599 return bsock->set_nonblocking();
603 * Set socket blocking
604 * Returns previous socket flags
606 int bnet_set_blocking(BSOCK *bsock)
608 return bsock->set_blocking();
612 * Restores socket flags
614 void bnet_restore_blocking (BSOCK *bsock, int flags)
616 bsock->restore_blocking(flags);
621 * Send a network "signal" to the other end
622 * This consists of sending a negative packet length
624 * Returns: false on failure
627 bool bnet_sig(BSOCK * bs, int signal)
629 return bs->signal(signal);
633 * Convert a network "signal" code into
634 * human readable ASCII.
636 const char *bnet_sig_to_ascii(BSOCK * bs)
639 switch (bs->msglen) {
641 return "BNET_EOD"; /* end of data stream */
643 return "BNET_EOD_POLL";
645 return "BNET_STATUS";
647 return "BNET_TERMINATE"; /* terminate connection */
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";
659 sprintf(buf, _("Unknown sig %d"), (int)bs->msglen);
664 /* Initialize internal socket structure.
665 * This probably should be done in net_open
667 BSOCK *init_bsock(JCR * jcr, int sockfd, const char *who, const char *host, int port,
668 struct sockaddr *client_addr)
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;
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));
685 * ****FIXME**** reduce this to a few hours once
686 * heartbeats are implemented
688 bsock->timeout = 60 * 60 * 6 * 24; /* 6 days timeout */
693 BSOCK *dup_bsock(BSOCK *osock)
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);
700 bsock->set_who(bstrdup(osock->who()));
703 bsock->set_host(bstrdup(osock->host()));
705 if (osock->src_addr) {
706 bsock->src_addr = New( IPADDR( *(osock->src_addr)) );
712 /* Close the network connection */
713 void bnet_close(BSOCK * bsock)
718 void term_bsock(BSOCK * bsock)