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