]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bsock.c
Create and put data into RestoreObject table
[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 || is_terminated() || msglen > 1000000) {
338       if (!m_suppress_error_msgs) {
339          Qmsg6(m_jcr, M_ERROR, 0,
340             _("Socket has errors=%d; is_terminated=%d; or has insane msglen=%d on call to %s:%s:%d\n"),
341              errors, is_terminated(), msglen, m_who,
342              m_host, m_port);
343       }
344       return false;
345    }
346    if (m_use_locking) P(m_mutex);
347    /* Compute total packet length */
348    if (msglen <= 0) {
349       pktsiz = sizeof(pktsiz);               /* signal, no data */
350    } else {
351       pktsiz = msglen + sizeof(pktsiz);      /* data */
352    }
353    /* Store packet length at head of message -- note, we
354     *  have reserved an int32_t just before msg, so we can
355     *  store there 
356     */
357    hdr = (int32_t *)(msg - (int)sizeof(pktsiz));
358    *hdr = htonl(msglen);                     /* store signal/length */
359
360    out_msg_no++;            /* increment message number */
361
362    /* send data packet */
363    timer_start = watchdog_time;  /* start timer */
364    clear_timed_out();
365    /* Full I/O done in one write */
366    rc = write_nbytes(this, (char *)hdr, pktsiz);
367    timer_start = 0;         /* clear timer */
368    if (rc != pktsiz) {
369       errors++;
370       if (errno == 0) {
371          b_errno = EIO;
372       } else {
373          b_errno = errno;
374       }
375       if (rc < 0) {
376          if (!m_suppress_error_msgs) {
377             Qmsg5(m_jcr, M_ERROR, 0,
378                   _("Write error sending %d bytes to %s:%s:%d: ERR=%s\n"), 
379                   msglen, m_who,
380                   m_host, m_port, this->bstrerror());
381          }
382       } else {
383          Qmsg5(m_jcr, M_ERROR, 0,
384                _("Wrote %d bytes to %s:%s:%d, but only %d accepted.\n"),
385                msglen, m_who, m_host, m_port, rc);
386       }
387       ok = false;
388    }
389    if (m_use_locking) V(m_mutex);
390    return ok;
391 }
392
393 /*
394  * Format and send a message
395  *  Returns: false on error
396  *           true  on success
397  */
398 bool BSOCK::fsend(const char *fmt, ...)
399 {
400    va_list arg_ptr;
401    int maxlen;
402
403    if (errors || is_terminated()) {
404       return false;
405    }
406    /* This probably won't work, but we vsnprintf, then if we
407     * get a negative length or a length greater than our buffer
408     * (depending on which library is used), the printf was truncated, so
409     * get a bigger buffer and try again.
410     */
411    for (;;) {
412       maxlen = sizeof_pool_memory(msg) - 1;
413       va_start(arg_ptr, fmt);
414       msglen = bvsnprintf(msg, maxlen, fmt, arg_ptr);
415       va_end(arg_ptr);
416       if (msglen > 0 && msglen < (maxlen - 5)) {
417          break;
418       }
419       msg = realloc_pool_memory(msg, maxlen + maxlen / 2);
420    }
421    return send();
422 }
423
424 /*
425  * Receive a message from the other end. Each message consists of
426  * two packets. The first is a header that contains the size
427  * of the data that follows in the second packet.
428  * Returns number of bytes read (may return zero)
429  * Returns -1 on signal (BNET_SIGNAL)
430  * Returns -2 on hard end of file (BNET_HARDEOF)
431  * Returns -3 on error  (BNET_ERROR)
432  *
433  *  Unfortunately, it is a bit complicated because we have these
434  *    four return types:
435  *    1. Normal data
436  *    2. Signal including end of data stream
437  *    3. Hard end of file
438  *    4. Error
439  *  Using is_bnet_stop() and is_bnet_error() you can figure this all out.
440  */
441 int32_t BSOCK::recv()
442 {
443    int32_t nbytes;
444    int32_t pktsiz;
445
446    msg[0] = 0;
447    msglen = 0;
448    if (errors || is_terminated()) {
449       return BNET_HARDEOF;
450    }
451
452    if (m_use_locking) P(m_mutex);
453    read_seqno++;            /* bump sequence number */
454    timer_start = watchdog_time;  /* set start wait time */
455    clear_timed_out();
456    /* get data size -- in int32_t */
457    if ((nbytes = read_nbytes(this, (char *)&pktsiz, sizeof(int32_t))) <= 0) {
458       timer_start = 0;      /* clear timer */
459       /* probably pipe broken because client died */
460       if (errno == 0) {
461          b_errno = ENODATA;
462       } else {
463          b_errno = errno;
464       }
465       errors++;
466       nbytes = BNET_HARDEOF;        /* assume hard EOF received */
467       goto get_out;
468    }
469    timer_start = 0;         /* clear timer */
470    if (nbytes != sizeof(int32_t)) {
471       errors++;
472       b_errno = EIO;
473       Qmsg5(m_jcr, M_ERROR, 0, _("Read expected %d got %d from %s:%s:%d\n"),
474             sizeof(int32_t), nbytes, m_who, m_host, m_port);
475       nbytes = BNET_ERROR;
476       goto get_out;
477    }
478
479    pktsiz = ntohl(pktsiz);         /* decode no. of bytes that follow */
480
481    if (pktsiz == 0) {              /* No data transferred */
482       timer_start = 0;             /* clear timer */
483       in_msg_no++;
484       msglen = 0;
485       nbytes = 0;                  /* zero bytes read */
486       goto get_out;
487    }
488
489    /* If signal or packet size too big */
490    if (pktsiz < 0 || pktsiz > 1000000) {
491       if (pktsiz > 0) {            /* if packet too big */
492          Qmsg3(m_jcr, M_FATAL, 0,
493                _("Packet size too big from \"%s:%s:%d. Terminating connection.\n"),
494                m_who, m_host, m_port);
495          pktsiz = BNET_TERMINATE;  /* hang up */
496       }
497       if (pktsiz == BNET_TERMINATE) {
498          set_terminated();
499       }
500       timer_start = 0;                /* clear timer */
501       b_errno = ENODATA;
502       msglen = pktsiz;                /* signal code */
503       nbytes =  BNET_SIGNAL;          /* signal */
504       goto get_out;
505    }
506
507    /* Make sure the buffer is big enough + one byte for EOS */
508    if (pktsiz >= (int32_t) sizeof_pool_memory(msg)) {
509       msg = realloc_pool_memory(msg, pktsiz + 100);
510    }
511
512    timer_start = watchdog_time;  /* set start wait time */
513    clear_timed_out();
514    /* now read the actual data */
515    if ((nbytes = read_nbytes(this, msg, pktsiz)) <= 0) {
516       timer_start = 0;      /* clear timer */
517       if (errno == 0) {
518          b_errno = ENODATA;
519       } else {
520          b_errno = errno;
521       }
522       errors++;
523       Qmsg4(m_jcr, M_ERROR, 0, _("Read error from %s:%s:%d: ERR=%s\n"),
524             m_who, m_host, m_port, this->bstrerror());
525       nbytes = BNET_ERROR;
526       goto get_out;
527    }
528    timer_start = 0;         /* clear timer */
529    in_msg_no++;
530    msglen = nbytes;
531    if (nbytes != pktsiz) {
532       b_errno = EIO;
533       errors++;
534       Qmsg5(m_jcr, M_ERROR, 0, _("Read expected %d got %d from %s:%s:%d\n"),
535             pktsiz, nbytes, m_who, m_host, m_port);
536       nbytes = BNET_ERROR;
537       goto get_out;
538    }
539    /* always add a zero by to properly terminate any
540     * string that was send to us. Note, we ensured above that the
541     * buffer is at least one byte longer than the message length.
542     */
543    msg[nbytes] = 0; /* terminate in case it is a string */
544    sm_check(__FILE__, __LINE__, false);
545
546 get_out:
547    if (m_use_locking) V(m_mutex);
548    return nbytes;                  /* return actual length of message */
549 }
550
551
552 /*
553  * Send a signal
554  */
555 bool BSOCK::signal(int signal)
556 {
557    msglen = signal;
558    if (signal == BNET_TERMINATE) {
559       m_suppress_error_msgs = true;
560    }
561    return send();
562 }
563
564 /* 
565  * Despool spooled attributes
566  */
567 bool BSOCK::despool(void update_attr_spool_size(ssize_t size), ssize_t tsize)
568 {
569    int32_t pktsiz;
570    size_t nbytes;
571    ssize_t last = 0, size = 0;
572    int count = 0;
573    JCR *jcr = get_jcr();
574
575    rewind(m_spool_fd);
576
577 #if defined(HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
578    posix_fadvise(fileno(m_spool_fd), 0, 0, POSIX_FADV_WILLNEED);
579 #endif
580
581    while (fread((char *)&pktsiz, 1, sizeof(int32_t), m_spool_fd) ==
582           sizeof(int32_t)) {
583       size += sizeof(int32_t);
584       msglen = ntohl(pktsiz);
585       if (msglen > 0) {
586          if (msglen > (int32_t)sizeof_pool_memory(msg)) {
587             msg = realloc_pool_memory(msg, msglen + 1);
588          }
589          nbytes = fread(msg, 1, msglen, m_spool_fd);
590          if (nbytes != (size_t)msglen) {
591             berrno be;
592             Dmsg2(400, "nbytes=%d msglen=%d\n", nbytes, msglen);
593             Qmsg1(get_jcr(), M_FATAL, 0, _("fread attr spool error. ERR=%s\n"),
594                   be.bstrerror());
595             update_attr_spool_size(tsize - last);
596             return false;
597          }
598          size += nbytes;
599          if ((++count & 0x3F) == 0) {
600             update_attr_spool_size(size - last);
601             last = size;
602          }
603       }
604       send();
605       if (jcr && job_canceled(jcr)) {
606          return false;
607       }
608    }
609    update_attr_spool_size(tsize - last);
610    if (ferror(m_spool_fd)) {
611       Qmsg(jcr, M_FATAL, 0, _("fread attr spool I/O error.\n"));
612       return false;
613    }
614    return true;
615 }
616
617 /*
618  * Return the string for the error that occurred
619  * on the socket. Only the first error is retained.
620  */
621 const char *BSOCK::bstrerror()
622 {
623    berrno be;
624    if (errmsg == NULL) {
625       errmsg = get_pool_memory(PM_MESSAGE);
626    }
627    pm_strcpy(errmsg, be.bstrerror(b_errno));
628    return errmsg;
629 }
630
631 int BSOCK::get_peer(char *buf, socklen_t buflen) 
632 {
633 #if !defined(HAVE_WIN32)
634     if (peer_addr.sin_family == 0) {
635         socklen_t salen = sizeof(peer_addr);
636         int rval = (getpeername)(m_fd, (struct sockaddr *)&peer_addr, &salen);
637         if (rval < 0) return rval;
638     }
639     if (!inet_ntop(peer_addr.sin_family, &peer_addr.sin_addr, buf, buflen))
640         return -1;
641
642     return 0;
643 #else
644     return -1;
645 #endif
646 }
647
648 /*
649  * Set the network buffer size, suggested size is in size.
650  *  Actual size obtained is returned in bs->msglen
651  *
652  *  Returns: false on failure
653  *           true  on success
654  */
655 bool BSOCK::set_buffer_size(uint32_t size, int rw)
656 {
657    uint32_t dbuf_size, start_size;
658 #if defined(IP_TOS) && defined(IPTOS_THROUGHPUT)
659    int opt;
660    opt = IPTOS_THROUGHPUT;
661    setsockopt(fd, IPPROTO_IP, IP_TOS, (sockopt_val_t)&opt, sizeof(opt));
662 #endif
663
664    if (size != 0) {
665       dbuf_size = size;
666    } else {
667       dbuf_size = DEFAULT_NETWORK_BUFFER_SIZE;
668    }
669    start_size = dbuf_size;
670    if ((msg = realloc_pool_memory(msg, dbuf_size + 100)) == NULL) {
671       Qmsg0(get_jcr(), M_FATAL, 0, _("Could not malloc BSOCK data buffer\n"));
672       return false;
673    }
674    if (rw & BNET_SETBUF_READ) {
675       while ((dbuf_size > TAPE_BSIZE) && (setsockopt(m_fd, SOL_SOCKET,
676               SO_RCVBUF, (sockopt_val_t) & dbuf_size, sizeof(dbuf_size)) < 0)) {
677          berrno be;
678          Qmsg1(get_jcr(), M_ERROR, 0, _("sockopt error: %s\n"), be.bstrerror());
679          dbuf_size -= TAPE_BSIZE;
680       }
681       Dmsg1(200, "set network buffer size=%d\n", dbuf_size);
682       if (dbuf_size != start_size) {
683          Qmsg1(get_jcr(), M_WARNING, 0,
684                _("Warning network buffer = %d bytes not max size.\n"), dbuf_size);
685       }
686       if (dbuf_size % TAPE_BSIZE != 0) {
687          Qmsg1(get_jcr(), M_ABORT, 0,
688                _("Network buffer size %d not multiple of tape block size.\n"),
689                dbuf_size);
690       }
691    }
692    if (size != 0) {
693       dbuf_size = size;
694    } else {
695       dbuf_size = DEFAULT_NETWORK_BUFFER_SIZE;
696    }
697    start_size = dbuf_size;
698    if (rw & BNET_SETBUF_WRITE) {
699       while ((dbuf_size > TAPE_BSIZE) && (setsockopt(m_fd, SOL_SOCKET,
700               SO_SNDBUF, (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(900, "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
717    msglen = dbuf_size;
718    return true;
719 }
720
721 /*
722  * Set socket non-blocking
723  * Returns previous socket flag
724  */
725 int BSOCK::set_nonblocking()
726 {
727 #ifndef HAVE_WIN32
728    int oflags;
729
730    /* Get current flags */
731    if ((oflags = fcntl(m_fd, F_GETFL, 0)) < 0) {
732       berrno be;
733       Qmsg1(get_jcr(), M_ABORT, 0, _("fcntl F_GETFL error. ERR=%s\n"), be.bstrerror());
734    }
735
736    /* Set O_NONBLOCK flag */
737    if ((fcntl(m_fd, F_SETFL, oflags|O_NONBLOCK)) < 0) {
738       berrno be;
739       Qmsg1(get_jcr(), M_ABORT, 0, _("fcntl F_SETFL error. ERR=%s\n"), be.bstrerror());
740    }
741
742    m_blocking = 0;
743    return oflags;
744 #else
745    int flags;
746    u_long ioctlArg = 1;
747
748    flags = m_blocking;
749    ioctlsocket(m_fd, FIONBIO, &ioctlArg);
750    m_blocking = 0;
751
752    return flags;
753 #endif
754 }
755
756 /*
757  * Set socket blocking
758  * Returns previous socket flags
759  */
760 int BSOCK::set_blocking()
761 {
762 #ifndef HAVE_WIN32
763    int oflags;
764    /* Get current flags */
765    if ((oflags = fcntl(m_fd, F_GETFL, 0)) < 0) {
766       berrno be;
767       Qmsg1(get_jcr(), M_ABORT, 0, _("fcntl F_GETFL error. ERR=%s\n"), be.bstrerror());
768    }
769
770    /* Set O_NONBLOCK flag */
771    if ((fcntl(m_fd, F_SETFL, oflags & ~O_NONBLOCK)) < 0) {
772       berrno be;
773       Qmsg1(get_jcr(), M_ABORT, 0, _("fcntl F_SETFL error. ERR=%s\n"), be.bstrerror());
774    }
775
776    m_blocking = 1;
777    return oflags;
778 #else
779    int flags;
780    u_long ioctlArg = 0;
781
782    flags = m_blocking;
783    ioctlsocket(m_fd, FIONBIO, &ioctlArg);
784    m_blocking = 1;
785
786    return flags;
787 #endif
788 }
789
790 /*
791  * Restores socket flags
792  */
793 void BSOCK::restore_blocking (int flags) 
794 {
795 #ifndef HAVE_WIN32
796    if ((fcntl(m_fd, F_SETFL, flags)) < 0) {
797       berrno be;
798       Qmsg1(get_jcr(), M_ABORT, 0, _("fcntl F_SETFL error. ERR=%s\n"), be.bstrerror());
799    }
800
801    m_blocking = (flags & O_NONBLOCK) ? true : false;
802 #else
803    u_long ioctlArg = flags;
804
805    ioctlsocket(m_fd, FIONBIO, &ioctlArg);
806    m_blocking = 1;
807 #endif
808 }
809
810 /*
811  * Wait for a specified time for data to appear on
812  * the BSOCK connection.
813  *
814  *   Returns: 1 if data available
815  *            0 if timeout
816  *           -1 if error
817  */
818 int BSOCK::wait_data(int sec, int usec)
819 {
820    fd_set fdset;
821    struct timeval tv;
822
823    FD_ZERO(&fdset);
824    FD_SET((unsigned)m_fd, &fdset);
825    for (;;) {
826       tv.tv_sec = sec;
827       tv.tv_usec = usec;
828       switch (select(m_fd + 1, &fdset, NULL, NULL, &tv)) {
829       case 0:                      /* timeout */
830          b_errno = 0;
831          return 0;
832       case -1:
833          b_errno = errno;
834          if (errno == EINTR) {
835             continue;
836          }
837          return -1;                /* error return */
838       default:
839          b_errno = 0;
840          return 1;
841       }
842    }
843 }
844
845 /*
846  * As above, but returns on interrupt
847  */
848 int BSOCK::wait_data_intr(int sec, int usec)
849 {
850    fd_set fdset;
851    struct timeval tv;
852
853    if (this == NULL) {
854       return -1;
855    }
856    FD_ZERO(&fdset);
857    FD_SET((unsigned)m_fd, &fdset);
858    tv.tv_sec = sec;
859    tv.tv_usec = usec;
860    switch (select(m_fd + 1, &fdset, NULL, NULL, &tv)) {
861    case 0:                      /* timeout */
862       b_errno = 0;
863       return 0;
864    case -1:
865       b_errno = errno;
866       return -1;                /* error return */
867    default:
868       b_errno = 0;
869       break;
870    }
871    return 1;
872 }
873
874 /*
875  * Note, this routine closes and destroys all the sockets
876  *  that are open including the duped ones.
877  */
878 #ifndef SHUT_RDWR
879 #define SHUT_RDWR 2
880 #endif
881
882 void BSOCK::close()
883 {
884    BSOCK *bsock = this;
885    BSOCK *next;
886
887    if (!m_duped) {
888       clear_locking();
889    }
890    for (; bsock; bsock = next) {
891       next = bsock->m_next;           /* get possible pointer to next before destoryed */
892       if (!bsock->m_duped) {
893          /* Shutdown tls cleanly. */
894          if (bsock->tls) {
895             tls_bsock_shutdown(bsock);
896             free_tls_connection(bsock->tls);
897             bsock->tls = NULL;
898          }
899          if (bsock->is_timed_out()) {
900             shutdown(bsock->m_fd, SHUT_RDWR);   /* discard any pending I/O */
901          }
902          socketClose(bsock->m_fd);      /* normal close */
903       }
904       bsock->destroy();
905    }
906    return;
907 }
908
909 void BSOCK::destroy()
910 {
911    if (msg) {
912       free_pool_memory(msg);
913       msg = NULL;
914    } else {
915       ASSERT(1 == 0);              /* double close */
916    }
917    if (errmsg) {
918       free_pool_memory(errmsg);
919       errmsg = NULL;
920    }
921    if (m_who) {
922       free(m_who);
923       m_who = NULL;
924    }
925    if (m_host) {
926       free(m_host);
927       m_host = NULL;
928    }
929    if (src_addr) {
930       free(src_addr);
931       src_addr = NULL;
932    } 
933    free(this);
934 }
935
936 /* Commands sent to Director */
937 static char hello[]    = "Hello %s calling\n";
938
939 /* Response from Director */
940 static char OKhello[]   = "1000 OK:";
941
942 /*
943  * Authenticate Director
944  */
945 bool BSOCK::authenticate_director(const char *name, const char *password,
946                TLS_CONTEXT *tls_ctx, char *msg, int msglen)
947 {
948    int tls_local_need = BNET_TLS_NONE;
949    int tls_remote_need = BNET_TLS_NONE;
950    int compatible = true;
951    char bashed_name[MAX_NAME_LENGTH];
952    BSOCK *dir = this;        /* for readability */
953
954    msg[0] = 0;
955    /*
956     * Send my name to the Director then do authentication
957     */
958
959    /* Timeout Hello after 15 secs */
960    dir->start_timer(15);
961    dir->fsend(hello, bashed_name);
962
963    if (get_tls_enable(tls_ctx)) {
964       tls_local_need = get_tls_enable(tls_ctx) ? BNET_TLS_REQUIRED : BNET_TLS_OK;
965    }
966
967    /* respond to Dir challenge */
968    if (!cram_md5_respond(dir, password, &tls_remote_need, &compatible) ||
969        /* Now challenge dir */
970        !cram_md5_challenge(dir, password, tls_local_need, compatible)) {
971       bsnprintf(msg, msglen, _("Director authorization problem at \"%s:%d\"\n"),
972          dir->host(), dir->port());
973       goto bail_out;
974    }
975
976    /* Verify that the remote host is willing to meet our TLS requirements */
977    if (tls_remote_need < tls_local_need && tls_local_need != BNET_TLS_OK && tls_remote_need != BNET_TLS_OK) {
978       bsnprintf(msg, msglen, _("Authorization problem:"
979              " Remote server at \"%s:%d\" did not advertise required TLS support.\n"),
980              dir->host(), dir->port());
981       goto bail_out;
982    }
983
984    /* Verify that we are willing to meet the remote host's requirements */
985    if (tls_remote_need > tls_local_need && tls_local_need != BNET_TLS_OK && tls_remote_need != BNET_TLS_OK) {
986       bsnprintf(msg, msglen, _("Authorization problem with Director at \"%s:%d\":"
987                      " Remote server requires TLS.\n"),
988                      dir->host(), dir->port());
989
990       goto bail_out;
991    }
992
993    /* Is TLS Enabled? */
994    if (have_tls) {
995       if (tls_local_need >= BNET_TLS_OK && tls_remote_need >= BNET_TLS_OK) {
996          /* Engage TLS! Full Speed Ahead! */
997          if (!bnet_tls_client(tls_ctx, dir, NULL)) {
998             bsnprintf(msg, msglen, _("TLS negotiation failed with Director at \"%s:%d\"\n"),
999                dir->host(), dir->port());
1000             goto bail_out;
1001          }
1002       }
1003    }
1004
1005    Dmsg1(6, ">dird: %s", dir->msg);
1006    if (dir->recv() <= 0) {
1007       dir->stop_timer();
1008       bsnprintf(msg, msglen, _("Bad response to Hello command: ERR=%s\n"
1009                       "The Director at \"%s:%d\" is probably not running.\n"),
1010                     dir->bstrerror(), dir->host(), dir->port());
1011       return false;
1012    }
1013
1014   dir->stop_timer();
1015    Dmsg1(10, "<dird: %s", dir->msg);
1016    if (strncmp(dir->msg, OKhello, sizeof(OKhello)-1) != 0) {
1017       bsnprintf(msg, msglen, _("Director at \"%s:%d\" rejected Hello command\n"),
1018          dir->host(), dir->port());
1019       return false;
1020    } else {
1021       bsnprintf(msg, msglen, "%s", dir->msg);
1022    }
1023    return true;
1024
1025 bail_out:
1026    dir->stop_timer();
1027    bsnprintf(msg, msglen, _("Authorization problem with Director at \"%s:%d\"\n"
1028              "Most likely the passwords do not agree.\n"
1029              "If you are using TLS, there may have been a certificate validation error during the TLS handshake.\n"
1030              "Please see http://www.bacula.org/en/rel-manual/Bacula_Freque_Asked_Questi.html#SECTION003760000000000000000 for help.\n"), 
1031              dir->host(), dir->port());
1032    return false;
1033 }