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