/ src / libserver / lltcp.cpp
lltcp.cpp
 1  /*
 2      EIBD eib bus access and management daemon
 3      Copyright (C) 2005-2011 Martin Koegler <mkoegler@auto.tuwien.ac.at>
 4  
 5      This program is free software; you can redistribute it and/or modify
 6      it under the terms of the GNU General Public License as published by
 7      the Free Software Foundation; either version 2 of the License, or
 8      (at your option) any later version.
 9  
10      This program is distributed in the hope that it will be useful,
11      but WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13      GNU General Public License for more details.
14  
15      You should have received a copy of the GNU General Public License
16      along with this program; if not, write to the Free Software
17      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19  
20  #include "lltcp.h"
21  #include "config.h"
22  
23  #include <cerrno>
24  #include <fcntl.h>
25  #include <netinet/in.h>
26  #include <netinet/tcp.h>
27  #include <sys/socket.h>
28  #include <unistd.h>
29  
30  #include "ipsupport.h"
31  
32  bool
33  LLtcp::setup()
34  {
35    if(!FDdriver::setup())
36      return false;
37  
38    dest = cfg->value("ip-address","");
39    port = cfg->value("dest-port",0);
40    if (dest.size() == 0)
41      {
42        ERRORPRINTF (t, E_ERROR | 52, "%s: 'ip-address=<host>' required", cfg->name);
43        return false;
44      }
45    if (port == 0)
46      {
47        ERRORPRINTF (t, E_ERROR | 72, "%s: 'port=<num>' required", cfg->name);
48        return false;
49      }
50  
51    return true;
52  }
53  
54  void
55  LLtcp::start()
56  {
57    int reuse = 1;
58    int nodelay = 1;
59    struct sockaddr_in addr;
60  
61    if (!GetHostIP (t, &addr, dest.c_str()))
62      {
63        ERRORPRINTF (t, E_ERROR | 73, "Lookup of %s failed: %s", dest, strerror(errno));
64        goto ex1;
65      }
66    addr.sin_port = htons (port);
67  
68    fd = socket (AF_INET, SOCK_STREAM, 0);
69    if (fd == -1)
70      {
71        ERRORPRINTF (t, E_ERROR | 74, "Opening %s:%d failed: %s", dest,port, strerror(errno));
72        goto ex1;
73      }
74  
75    if (connect (fd, (struct sockaddr *) &addr, sizeof (addr)) == -1)
76      {
77        ERRORPRINTF (t, E_ERROR | 53, "Connect %s:%d: connect: %s", dest,port, strerror(errno));
78        goto ex2;
79      }
80    setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof (reuse));
81    setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof (nodelay));
82  
83    TRACEPRINTF (t, 2, "Opened");
84    FDdriver::start();
85    return;
86  
87  ex2:
88    close (fd);
89    fd = -1;
90  ex1:
91    stopped(true);
92  }
93