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