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