]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bsock.c
kes Ensure that when labelling a tape with Slot=0 that InChanger
[bacula/bacula] / bacula / src / lib / bsock.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2007-2007 Free Software Foundation Europe e.V.
5
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 plus additions
11    that are listed in the file LICENSE.
12
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.
17
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
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of John Walker.
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.
27 */
28 /*
29  * Network Utility Routines
30  *
31  *  by Kern Sibbald
32  *
33  *   Version $Id: $
34  */
35
36
37 #include "bacula.h"
38 #include "jcr.h"
39 #include <netdb.h>
40
41 #ifndef ENODATA                    /* not defined on BSD systems */
42 #define ENODATA EPIPE
43 #endif
44
45 #ifdef HAVE_WIN32
46 #define socketRead(fd, buf, len)  ::recv(fd, buf, len, 0)
47 #define socketWrite(fd, buf, len) ::send(fd, buf, len, 0)
48 #define socketClose(fd)           ::closesocket(fd)
49 #else
50 #define socketRead(fd, buf, len)  ::read(fd, buf, len)
51 #define socketWrite(fd, buf, len) ::write(fd, buf, len)
52 #define socketClose(fd)           ::close(fd)
53 #endif
54
55 /*
56  * This is a non-class BSOCK "constructor"  because we want to 
57  *   call the Bacula smartalloc routines instead of new.
58  */
59 BSOCK *new_bsock()
60 {
61    BSOCK *bsock = (BSOCK *)malloc(sizeof(BSOCK));
62    bsock->init();
63    return bsock;
64 }
65
66 void BSOCK::init()
67 {
68    memset(this, 0, sizeof(BSOCK));
69    m_blocking = 1;
70    msg = get_pool_memory(PM_MESSAGE);
71    errmsg = get_pool_memory(PM_MESSAGE);
72    /*
73     * ****FIXME**** reduce this to a few hours once
74     *   heartbeats are implemented
75     */
76    timeout = 60 * 60 * 6 * 24;   /* 6 days timeout */
77 }
78
79 /*
80  * This is our "class destructor" that ensures that we use
81  *   smartalloc rather than the system free().
82  */
83 void BSOCK::free_bsock()
84 {
85    destroy();
86 }
87
88 /*
89  * Try to connect to host for max_retry_time at retry_time intervals.
90  *   Note, you must have called the constructor prior to calling
91  *   this routine.
92  */
93 bool BSOCK::connect(JCR * jcr, int retry_interval, utime_t max_retry_time,
94                     utime_t heart_beat,
95                     const char *name, char *host, char *service, int port,
96                     int verbose)
97 {
98    bool ok = false;
99    int i;
100    int fatal = 0;
101    time_t begin_time = time(NULL);
102    time_t now;
103    btimer_t *tid = NULL;
104
105    /* Try to trap out of OS call when time expires */
106    if (max_retry_time) {
107       tid = start_thread_timer(pthread_self(), (uint32_t)max_retry_time);
108    }
109    
110    for (i = 0; !open(jcr, name, host, service, port, heart_beat, &fatal);
111         i -= retry_interval) {
112       berrno be;
113       if (fatal || (jcr && job_canceled(jcr))) {
114          goto bail_out;
115       }
116       Dmsg4(100, "Unable to connect to %s on %s:%d. ERR=%s\n",
117             name, host, port, be.bstrerror());
118       if (i < 0) {
119          i = 60 * 5;               /* complain again in 5 minutes */
120          if (verbose)
121             Qmsg4(jcr, M_WARNING, 0, _(
122                "Could not connect to %s on %s:%d. ERR=%s\n"
123                "Retrying ...\n"), name, host, port, be.bstrerror());
124       }
125       bmicrosleep(retry_interval, 0);
126       now = time(NULL);
127       if (begin_time + max_retry_time <= now) {
128          Qmsg4(jcr, M_FATAL, 0, _("Unable to connect to %s on %s:%d. ERR=%s\n"),
129                name, host, port, be.bstrerror());
130          goto bail_out;
131       }
132    }
133    ok = true;
134
135 bail_out:
136    if (tid) {
137       stop_thread_timer(tid);
138    }
139    return ok;
140 }
141
142
143 /*       
144  * Finish initialization of the pocket structure.
145  */
146 void BSOCK::fin_init(JCR * jcr, int sockfd, const char *who, const char *host, int port,
147             struct sockaddr *lclient_addr)
148 {
149    Dmsg3(100, "who=%s host=%s port=%d\n", who, host, port);
150    m_fd = sockfd;
151    set_who(bstrdup(who));
152    set_host(bstrdup(host));
153    set_port(port);
154    memcpy(&client_addr, lclient_addr, sizeof(client_addr));
155    set_jcr(jcr);
156 }
157
158 /*
159  * Open a TCP connection to the server
160  * Returns NULL
161  * Returns BSOCK * pointer on success
162  *
163  */
164 bool BSOCK::open(JCR *jcr, const char *name, char *host, char *service,
165             int port, utime_t heart_beat, int *fatal)
166 {
167    int sockfd = -1;
168    dlist *addr_list;
169    IPADDR *ipaddr;
170    bool connected = false;
171    int turnon = 1;
172    const char *errstr;
173    int save_errno = 0;
174
175    /*
176     * Fill in the structure serv_addr with the address of
177     * the server that we want to connect with.
178     */
179    if ((addr_list = bnet_host2ipaddrs(host, 0, &errstr)) == NULL) {
180       /* Note errstr is not malloc'ed */
181       Qmsg2(jcr, M_ERROR, 0, _("gethostbyname() for host \"%s\" failed: ERR=%s\n"),
182             host, errstr);
183       Dmsg2(100, "bnet_host2ipaddrs() for host %s failed: ERR=%s\n",
184             host, errstr);
185       *fatal = 1;
186       return false;
187    }
188
189    foreach_dlist(ipaddr, addr_list) {
190       ipaddr->set_port_net(htons(port));
191       char allbuf[256 * 10];
192       char curbuf[256];
193       Dmsg2(100, "Current %sAll %s\n",
194                    ipaddr->build_address_str(curbuf, sizeof(curbuf)),
195                    build_addresses_str(addr_list, allbuf, sizeof(allbuf)));
196       /* Open a TCP socket */
197       if ((sockfd = socket(ipaddr->get_family(), SOCK_STREAM, 0)) < 0) {
198          berrno be;
199          save_errno = errno;
200          *fatal = 1;
201          Pmsg3(000, _("Socket open error. proto=%d port=%d. ERR=%s\n"),
202             ipaddr->get_family(), ipaddr->get_port_host_order(), be.bstrerror());
203          continue;
204       }
205       /*
206        * Keep socket from timing out from inactivity
207        */
208       if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (sockopt_val_t)&turnon, sizeof(turnon)) < 0) {
209          berrno be;
210          Qmsg1(jcr, M_WARNING, 0, _("Cannot set SO_KEEPALIVE on socket: %s\n"),
211                be.bstrerror());
212       }
213 #if defined(TCP_KEEPIDLE)
214       if (heart_beat) {
215          int opt = heart_beat
216          if (setsockopt(sockfd, IPPROTO_IP, TCP_KEEPIDLE, (sockopt_val_t)&opt, sizeof(opt)) < 0) {
217             berrno be;
218             Qmsg1(jcr, M_WARNING, 0, _("Cannot set SO_KEEPIDLE on socket: %s\n"),
219                   be.bstrerror());
220          }
221       }
222 #endif
223
224       /* connect to server */
225       if (::connect(sockfd, ipaddr->get_sockaddr(), ipaddr->get_sockaddr_len()) < 0) {
226          save_errno = errno;
227          socketClose(sockfd);
228          continue;
229       }
230       *fatal = 0;
231       connected = true;
232       break;
233    }
234
235    if (!connected) {
236       free_addresses(addr_list);
237       errno = save_errno | b_errno_win32;
238       return false;
239    }
240    /*
241     * Keep socket from timing out from inactivity
242     *   Do this a second time out of paranoia
243     */
244    if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (sockopt_val_t)&turnon, sizeof(turnon)) < 0) {
245       berrno be;
246       Qmsg1(jcr, M_WARNING, 0, _("Cannot set SO_KEEPALIVE on socket: %s\n"),
247             be.bstrerror());
248    }
249    fin_init(jcr, sockfd, name, host, port, ipaddr->get_sockaddr());
250    free_addresses(addr_list);
251    return true;
252 }
253
254
255
256 /*
257  * Send a message over the network. The send consists of
258  * two network packets. The first is sends a 32 bit integer containing
259  * the length of the data packet which follows.
260  *
261  * Returns: false on failure
262  *          true  on success
263  */
264 bool BSOCK::send()
265 {
266    int32_t rc;
267    int32_t pktsiz;
268    int32_t *hdr;
269
270    if (errors || is_terminated() || msglen > 1000000) {
271       return false;
272    }
273    /* Compute total packet length */
274    if (msglen <= 0) {
275       pktsiz = sizeof(pktsiz);               /* signal, no data */
276    } else {
277       pktsiz = msglen + sizeof(pktsiz);      /* data */
278    }
279    /* Store packet length at head of message -- note, we
280     *  have reserved an int32_t just before msg, so we can
281     *  store there 
282     */
283    hdr = (int32_t *)(msg - (int)sizeof(pktsiz));
284    *hdr = htonl(msglen);                     /* store signal/length */
285
286    out_msg_no++;            /* increment message number */
287
288    /* send data packet */
289    timer_start = watchdog_time;  /* start timer */
290    m_timed_out = 0;
291    /* Full I/O done in one write */
292    rc = write_nbytes(this, (char *)hdr, pktsiz);
293    timer_start = 0;         /* clear timer */
294    if (rc != pktsiz) {
295       errors++;
296       if (errno == 0) {
297          b_errno = EIO;
298       } else {
299          b_errno = errno;
300       }
301       if (rc < 0) {
302          if (!m_suppress_error_msgs) {
303             Qmsg5(m_jcr, M_ERROR, 0,
304                   _("Write error sending %d bytes to %s:%s:%d: ERR=%s\n"), 
305                   msglen, m_who,
306                   m_host, m_port, this->bstrerror());
307          }
308       } else {
309          Qmsg5(m_jcr, M_ERROR, 0,
310                _("Wrote %d bytes to %s:%s:%d, but only %d accepted.\n"),
311                msglen, m_who, m_host, m_port, rc);
312       }
313       return false;
314    }
315    return true;
316 }
317
318 /*
319  * Format and send a message
320  *  Returns: false on error
321  *           true  on success
322  */
323 bool BSOCK::fsend(const char *fmt, ...)
324 {
325    va_list arg_ptr;
326    int maxlen;
327
328    if (errors || is_terminated()) {
329       return false;
330    }
331    /* This probably won't work, but we vsnprintf, then if we
332     * get a negative length or a length greater than our buffer
333     * (depending on which library is used), the printf was truncated, so
334     * get a bigger buffer and try again.
335     */
336    for (;;) {
337       maxlen = sizeof_pool_memory(msg) - 1;
338       va_start(arg_ptr, fmt);
339       msglen = bvsnprintf(msg, maxlen, fmt, arg_ptr);
340       va_end(arg_ptr);
341       if (msglen > 0 && msglen < (maxlen - 5)) {
342          break;
343       }
344       msg = realloc_pool_memory(msg, maxlen + maxlen / 2);
345    }
346    return send();
347 }
348
349 /*
350  * Receive a message from the other end. Each message consists of
351  * two packets. The first is a header that contains the size
352  * of the data that follows in the second packet.
353  * Returns number of bytes read (may return zero)
354  * Returns -1 on signal (BNET_SIGNAL)
355  * Returns -2 on hard end of file (BNET_HARDEOF)
356  * Returns -3 on error  (BNET_ERROR)
357  *
358  *  Unfortunately, it is a bit complicated because we have these
359  *    four return types:
360  *    1. Normal data
361  *    2. Signal including end of data stream
362  *    3. Hard end of file
363  *    4. Error
364  *  Using is_bnet_stop() and is_bnet_error() you can figure this all out.
365  */
366 int32_t BSOCK::recv()
367 {
368    int32_t nbytes;
369    int32_t pktsiz;
370
371    msg[0] = 0;
372    msglen = 0;
373    if (errors || is_terminated()) {
374       return BNET_HARDEOF;
375    }
376
377    read_seqno++;            /* bump sequence number */
378    timer_start = watchdog_time;  /* set start wait time */
379    m_timed_out = 0;
380    /* get data size -- in int32_t */
381    if ((nbytes = read_nbytes(this, (char *)&pktsiz, sizeof(int32_t))) <= 0) {
382       timer_start = 0;      /* clear timer */
383       /* probably pipe broken because client died */
384       if (errno == 0) {
385          b_errno = ENODATA;
386       } else {
387          b_errno = errno;
388       }
389       errors++;
390       return BNET_HARDEOF;         /* assume hard EOF received */
391    }
392    timer_start = 0;         /* clear timer */
393    if (nbytes != sizeof(int32_t)) {
394       errors++;
395       b_errno = EIO;
396       Qmsg5(m_jcr, M_ERROR, 0, _("Read expected %d got %d from %s:%s:%d\n"),
397             sizeof(int32_t), nbytes, m_who, m_host, m_port);
398       return BNET_ERROR;
399    }
400
401    pktsiz = ntohl(pktsiz);         /* decode no. of bytes that follow */
402
403    if (pktsiz == 0) {              /* No data transferred */
404       timer_start = 0;      /* clear timer */
405       in_msg_no++;
406       msglen = 0;
407       return 0;                    /* zero bytes read */
408    }
409
410    /* If signal or packet size too big */
411    if (pktsiz < 0 || pktsiz > 1000000) {
412       if (pktsiz > 0) {            /* if packet too big */
413          Qmsg3(m_jcr, M_FATAL, 0,
414                _("Packet size too big from \"%s:%s:%d. Terminating connection.\n"),
415                m_who, m_host, m_port);
416          pktsiz = BNET_TERMINATE;  /* hang up */
417       }
418       if (pktsiz == BNET_TERMINATE) {
419          set_terminated();
420       }
421       timer_start = 0;      /* clear timer */
422       b_errno = ENODATA;
423       msglen = pktsiz;      /* signal code */
424       return BNET_SIGNAL;          /* signal */
425    }
426
427    /* Make sure the buffer is big enough + one byte for EOS */
428    if (pktsiz >= (int32_t) sizeof_pool_memory(msg)) {
429       msg = realloc_pool_memory(msg, pktsiz + 100);
430    }
431
432    timer_start = watchdog_time;  /* set start wait time */
433    m_timed_out = 0;
434    /* now read the actual data */
435    if ((nbytes = read_nbytes(this, msg, pktsiz)) <= 0) {
436       timer_start = 0;      /* clear timer */
437       if (errno == 0) {
438          b_errno = ENODATA;
439       } else {
440          b_errno = errno;
441       }
442       errors++;
443       Qmsg4(m_jcr, M_ERROR, 0, _("Read error from %s:%s:%d: ERR=%s\n"),
444             m_who, m_host, m_port, this->bstrerror());
445       return BNET_ERROR;
446    }
447    timer_start = 0;         /* clear timer */
448    in_msg_no++;
449    msglen = nbytes;
450    if (nbytes != pktsiz) {
451       b_errno = EIO;
452       errors++;
453       Qmsg5(m_jcr, M_ERROR, 0, _("Read expected %d got %d from %s:%s:%d\n"),
454             pktsiz, nbytes, m_who, m_host, m_port);
455       return BNET_ERROR;
456    }
457    /* always add a zero by to properly terminate any
458     * string that was send to us. Note, we ensured above that the
459     * buffer is at least one byte longer than the message length.
460     */
461    msg[nbytes] = 0; /* terminate in case it is a string */
462    sm_check(__FILE__, __LINE__, false);
463    return nbytes;                  /* return actual length of message */
464 }
465
466
467 /*
468  * Send a signal
469  */
470 bool BSOCK::signal(int signal)
471 {
472    msglen = signal;
473    if (signal == BNET_TERMINATE) {
474       m_suppress_error_msgs = true;
475    }
476    return send();
477 }
478
479 /* 
480  * Despool spooled attributes
481  */
482 bool BSOCK::despool(void update_attr_spool_size(ssize_t size), ssize_t tsize)
483 {
484    int32_t pktsiz;
485    size_t nbytes;
486    ssize_t last = 0, size = 0;
487    int count = 0;
488
489    rewind(m_spool_fd);
490
491 #if defined(HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
492    posix_fadvise(fileno(m_spool_fd), 0, 0, POSIX_FADV_WILLNEED);
493 #endif
494
495    while (fread((char *)&pktsiz, 1, sizeof(int32_t), m_spool_fd) ==
496           sizeof(int32_t)) {
497       size += sizeof(int32_t);
498       msglen = ntohl(pktsiz);
499       if (msglen > 0) {
500          if (msglen > (int32_t) sizeof_pool_memory(msg)) {
501             msg = realloc_pool_memory(msg, msglen + 1);
502          }
503          nbytes = fread(msg, 1, msglen, m_spool_fd);
504          if (nbytes != (size_t) msglen) {
505             berrno be;
506             Dmsg2(400, "nbytes=%d msglen=%d\n", nbytes, msglen);
507             Qmsg1(get_jcr(), M_FATAL, 0, _("fread attr spool error. ERR=%s\n"),
508                   be.bstrerror());
509             update_attr_spool_size(tsize - last);
510             return false;
511          }
512          size += nbytes;
513          if ((++count & 0x3F) == 0) {
514             update_attr_spool_size(size - last);
515             last = size;
516          }
517       }
518       send();
519    }
520    update_attr_spool_size(tsize - last);
521    if (ferror(m_spool_fd)) {
522       berrno be;
523       Qmsg1(get_jcr(), M_FATAL, 0, _("fread attr spool error. ERR=%s\n"),
524             be.bstrerror());
525       return false;
526    }
527    return true;
528 }
529
530 /*
531  * Return the string for the error that occurred
532  * on the socket. Only the first error is retained.
533  */
534 const char *BSOCK::bstrerror()
535 {
536    berrno be;
537    if (errmsg == NULL) {
538       errmsg = get_pool_memory(PM_MESSAGE);
539    }
540    pm_strcpy(errmsg, be.bstrerror(b_errno));
541    return errmsg;
542 }
543
544 int BSOCK::get_peer(char *buf, socklen_t buflen) 
545 {
546 #if !defined(HAVE_WIN32)
547     if (peer_addr.sin_family == 0) {
548         socklen_t salen = sizeof(peer_addr);
549         int rval = (getpeername)(m_fd, (struct sockaddr *)&peer_addr, &salen);
550         if (rval < 0) return rval;
551     }
552     if (!inet_ntop(peer_addr.sin_family, &peer_addr.sin_addr, buf, buflen))
553         return -1;
554
555     return 0;
556 #else
557     return -1;
558 #endif
559 }
560
561 /*
562  * Set the network buffer size, suggested size is in size.
563  *  Actual size obtained is returned in bs->msglen
564  *
565  *  Returns: false on failure
566  *           true  on success
567  */
568 bool BSOCK::set_buffer_size(uint32_t size, int rw)
569 {
570    uint32_t dbuf_size, start_size;
571 #if defined(IP_TOS) && defined(IPTOS_THROUGHPUT)
572    int opt;
573    opt = IPTOS_THROUGHPUT;
574    setsockopt(fd, IPPROTO_IP, IP_TOS, (sockopt_val_t)&opt, sizeof(opt));
575 #endif
576
577    if (size != 0) {
578       dbuf_size = size;
579    } else {
580       dbuf_size = DEFAULT_NETWORK_BUFFER_SIZE;
581    }
582    start_size = dbuf_size;
583    if ((msg = realloc_pool_memory(msg, dbuf_size + 100)) == NULL) {
584       Qmsg0(get_jcr(), M_FATAL, 0, _("Could not malloc BSOCK data buffer\n"));
585       return false;
586    }
587    if (rw & BNET_SETBUF_READ) {
588       while ((dbuf_size > TAPE_BSIZE) && (setsockopt(m_fd, SOL_SOCKET,
589               SO_RCVBUF, (sockopt_val_t) & dbuf_size, sizeof(dbuf_size)) < 0)) {
590          berrno be;
591          Qmsg1(get_jcr(), M_ERROR, 0, _("sockopt error: %s\n"), be.bstrerror());
592          dbuf_size -= TAPE_BSIZE;
593       }
594       Dmsg1(200, "set network buffer size=%d\n", dbuf_size);
595       if (dbuf_size != start_size) {
596          Qmsg1(get_jcr(), M_WARNING, 0,
597                _("Warning network buffer = %d bytes not max size.\n"), dbuf_size);
598       }
599       if (dbuf_size % TAPE_BSIZE != 0) {
600          Qmsg1(get_jcr(), M_ABORT, 0,
601                _("Network buffer size %d not multiple of tape block size.\n"),
602                dbuf_size);
603       }
604    }
605    if (size != 0) {
606       dbuf_size = size;
607    } else {
608       dbuf_size = DEFAULT_NETWORK_BUFFER_SIZE;
609    }
610    start_size = dbuf_size;
611    if (rw & BNET_SETBUF_WRITE) {
612       while ((dbuf_size > TAPE_BSIZE) && (setsockopt(m_fd, SOL_SOCKET,
613               SO_SNDBUF, (sockopt_val_t) & dbuf_size, sizeof(dbuf_size)) < 0)) {
614          berrno be;
615          Qmsg1(get_jcr(), M_ERROR, 0, _("sockopt error: %s\n"), be.bstrerror());
616          dbuf_size -= TAPE_BSIZE;
617       }
618       Dmsg1(900, "set network buffer size=%d\n", dbuf_size);
619       if (dbuf_size != start_size) {
620          Qmsg1(get_jcr(), M_WARNING, 0,
621                _("Warning network buffer = %d bytes not max size.\n"), dbuf_size);
622       }
623       if (dbuf_size % TAPE_BSIZE != 0) {
624          Qmsg1(get_jcr(), M_ABORT, 0,
625                _("Network buffer size %d not multiple of tape block size.\n"),
626                dbuf_size);
627       }
628    }
629
630    msglen = dbuf_size;
631    return true;
632 }
633
634 /*
635  * Set socket non-blocking
636  * Returns previous socket flag
637  */
638 int BSOCK::set_nonblocking()
639 {
640 #ifndef HAVE_WIN32
641    int oflags;
642
643    /* Get current flags */
644    if ((oflags = fcntl(m_fd, F_GETFL, 0)) < 0) {
645       berrno be;
646       Jmsg1(get_jcr(), M_ABORT, 0, _("fcntl F_GETFL error. ERR=%s\n"), be.bstrerror());
647    }
648
649    /* Set O_NONBLOCK flag */
650    if ((fcntl(m_fd, F_SETFL, oflags|O_NONBLOCK)) < 0) {
651       berrno be;
652       Jmsg1(get_jcr(), M_ABORT, 0, _("fcntl F_SETFL error. ERR=%s\n"), be.bstrerror());
653    }
654
655    m_blocking = 0;
656    return oflags;
657 #else
658    int flags;
659    u_long ioctlArg = 1;
660
661    flags = m_blocking;
662    ioctlsocket(m_fd, FIONBIO, &ioctlArg);
663    m_blocking = 0;
664
665    return flags;
666 #endif
667 }
668
669 /*
670  * Set socket blocking
671  * Returns previous socket flags
672  */
673 int BSOCK::set_blocking()
674 {
675 #ifndef HAVE_WIN32
676    int oflags;
677    /* Get current flags */
678    if ((oflags = fcntl(m_fd, F_GETFL, 0)) < 0) {
679       berrno be;
680       Jmsg1(get_jcr(), M_ABORT, 0, _("fcntl F_GETFL error. ERR=%s\n"), be.bstrerror());
681    }
682
683    /* Set O_NONBLOCK flag */
684    if ((fcntl(m_fd, F_SETFL, oflags & ~O_NONBLOCK)) < 0) {
685       berrno be;
686       Jmsg1(get_jcr(), M_ABORT, 0, _("fcntl F_SETFL error. ERR=%s\n"), be.bstrerror());
687    }
688
689    m_blocking = 1;
690    return oflags;
691 #else
692    int flags;
693    u_long ioctlArg = 0;
694
695    flags = m_blocking;
696    ioctlsocket(m_fd, FIONBIO, &ioctlArg);
697    m_blocking = 1;
698
699    return flags;
700 #endif
701 }
702
703 /*
704  * Restores socket flags
705  */
706 void BSOCK::restore_blocking (int flags) 
707 {
708 #ifndef HAVE_WIN32
709    if ((fcntl(m_fd, F_SETFL, flags)) < 0) {
710       berrno be;
711       Jmsg1(get_jcr(), M_ABORT, 0, _("fcntl F_SETFL error. ERR=%s\n"), be.bstrerror());
712    }
713
714    m_blocking = (flags & O_NONBLOCK) ? true : false;
715 #else
716    u_long ioctlArg = flags;
717
718    ioctlsocket(m_fd, FIONBIO, &ioctlArg);
719    m_blocking = 1;
720 #endif
721 }
722
723 /*
724  * Wait for a specified time for data to appear on
725  * the BSOCK connection.
726  *
727  *   Returns: 1 if data available
728  *            0 if timeout
729  *           -1 if error
730  */
731 int BSOCK::wait_data(int sec)
732 {
733    fd_set fdset;
734    struct timeval tv;
735
736    FD_ZERO(&fdset);
737    FD_SET((unsigned)m_fd, &fdset);
738    for (;;) {
739       tv.tv_sec = sec;
740       tv.tv_usec = 0;
741       switch (select(m_fd + 1, &fdset, NULL, NULL, &tv)) {
742       case 0:                      /* timeout */
743          b_errno = 0;
744          return 0;
745       case -1:
746          b_errno = errno;
747          if (errno == EINTR) {
748             continue;
749          }
750          return -1;                /* error return */
751       default:
752          b_errno = 0;
753          return 1;
754       }
755    }
756 }
757
758 /*
759  * As above, but returns on interrupt
760  */
761 int BSOCK::wait_data_intr(int sec)
762 {
763    fd_set fdset;
764    struct timeval tv;
765
766    FD_ZERO(&fdset);
767    FD_SET((unsigned)m_fd, &fdset);
768    tv.tv_sec = sec;
769    tv.tv_usec = 0;
770    switch (select(m_fd + 1, &fdset, NULL, NULL, &tv)) {
771    case 0:                      /* timeout */
772       b_errno = 0;
773       return 0;
774    case -1:
775       b_errno = errno;
776       return -1;                /* error return */
777    default:
778       b_errno = 0;
779    }
780    return 1;
781 }
782
783 /*
784  * Note, this routine closes and destroys all the sockets
785  *  that are open including the duped ones.
786  */
787 void BSOCK::close()
788 {
789    BSOCK *bsock = this;
790    BSOCK *next;
791
792    for (; bsock; bsock = next) {
793       next = bsock->m_next;           /* get possible pointer to next before destoryed */
794       if (!bsock->m_duped) {
795          /* Shutdown tls cleanly. */
796          if (bsock->tls) {
797             tls_bsock_shutdown(bsock);
798             free_tls_connection(bsock->tls);
799             bsock->tls = NULL;
800          }
801          if (bsock->is_timed_out()) {
802             shutdown(bsock->m_fd, 2);   /* discard any pending I/O */
803          }
804          socketClose(bsock->m_fd);      /* normal close */
805       }
806       bsock->destroy();
807    }
808    return;
809 }
810
811 void BSOCK::destroy()
812 {
813    if (msg) {
814       free_pool_memory(msg);
815       msg = NULL;
816    } else {
817       ASSERT(1 == 0);              /* double close */
818    }
819    if (errmsg) {
820       free_pool_memory(errmsg);
821       errmsg = NULL;
822    }
823    if (m_who) {
824       free(m_who);
825       m_who = NULL;
826    }
827    if (m_host) {
828       free(m_host);
829       m_host = NULL;
830    }
831    free(this);
832 }
833
834 /* Commands sent to Director */
835 static char hello[]    = "Hello %s calling\n";
836
837 /* Response from Director */
838 static char OKhello[]   = "1000 OK:";
839
840 /*
841  * Authenticate Director
842  */
843 bool BSOCK::authenticate_director(const char *name, const char *password,
844                TLS_CONTEXT *tls_ctx, char *msg, int msglen)
845 {
846    int tls_local_need = BNET_TLS_NONE;
847    int tls_remote_need = BNET_TLS_NONE;
848    int compatible = true;
849    char bashed_name[MAX_NAME_LENGTH];
850    BSOCK *dir = this;        /* for readability */
851
852    msg[0] = 0;
853    /*
854     * Send my name to the Director then do authentication
855     */
856
857    /* Timeout Hello after 15 secs */
858    dir->start_timer(15);
859    dir->fsend(hello, bashed_name);
860
861    if (get_tls_enable(tls_ctx)) {
862       tls_local_need = get_tls_enable(tls_ctx) ? BNET_TLS_REQUIRED : BNET_TLS_OK;
863    }
864
865    /* respond to Dir challenge */
866    if (!cram_md5_respond(dir, password, &tls_remote_need, &compatible) ||
867        /* Now challenge dir */
868        !cram_md5_challenge(dir, password, tls_local_need, compatible)) {
869       bsnprintf(msg, msglen, _("Director authorization problem at \"%s:%d\"\n"),
870          dir->host(), dir->port());
871       goto bail_out;
872    }
873
874    /* Verify that the remote host is willing to meet our TLS requirements */
875    if (tls_remote_need < tls_local_need && tls_local_need != BNET_TLS_OK && tls_remote_need != BNET_TLS_OK) {
876       bsnprintf(msg, msglen, _("Authorization problem:"
877              " Remote server at \"%s:%d\" did not advertise required TLS support.\n"),
878              dir->host(), dir->port());
879       goto bail_out;
880    }
881
882    /* Verify that we are willing to meet the remote host's requirements */
883    if (tls_remote_need > tls_local_need && tls_local_need != BNET_TLS_OK && tls_remote_need != BNET_TLS_OK) {
884       bsnprintf(msg, msglen, _("Authorization problem with Director at \"%s:%d\":"
885                      " Remote server requires TLS.\n"),
886                      dir->host(), dir->port());
887
888       goto bail_out;
889    }
890
891    /* Is TLS Enabled? */
892    if (have_tls) {
893       if (tls_local_need >= BNET_TLS_OK && tls_remote_need >= BNET_TLS_OK) {
894          /* Engage TLS! Full Speed Ahead! */
895          if (!bnet_tls_client(tls_ctx, dir, NULL)) {
896             bsnprintf(msg, msglen, _("TLS negotiation failed with Director at \"%s:%d\"\n"),
897                dir->host(), dir->port());
898             goto bail_out;
899          }
900       }
901    }
902
903    Dmsg1(6, ">dird: %s", dir->msg);
904    if (dir->recv() <= 0) {
905       dir->stop_timer();
906       bsnprintf(msg, msglen, _("Bad response to Hello command: ERR=%s\n"
907                       "The Director at \"%s:%d\" is probably not running.\n"),
908                     dir->bstrerror(), dir->host(), dir->port());
909       return false;
910    }
911
912   dir->stop_timer();
913    Dmsg1(10, "<dird: %s", dir->msg);
914    if (strncmp(dir->msg, OKhello, sizeof(OKhello)-1) != 0) {
915       bsnprintf(msg, msglen, _("Director at \"%s:%d\" rejected Hello command\n"),
916          dir->host(), dir->port());
917       return false;
918    } else {
919       bsnprintf(msg, msglen, "%s", dir->msg);
920    }
921    return true;
922
923 bail_out:
924    dir->stop_timer();
925    bsnprintf(msg, msglen, _("Authorization problem with Director at \"%s:%d\"\n"
926              "Most likely the passwords do not agree.\n"
927              "If you are using TLS, there may have been a certificate validation error during the TLS handshake.\n"
928              "Please see http://www.bacula.org/rel-manual/faq.html#AuthorizationErrors for help.\n"), 
929              dir->host(), dir->port());
930    return false;
931 }