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