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