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