02df8e4a7fd009c13783979b3bd794dfe3fdf530
[shibboleth/cpp-sp.git] / shibsp / remoting / impl / TCPListener.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * TCPListener.cpp
23  *
24  * TCP-based SocketListener implementation.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "remoting/impl/SocketListener.h"
30 #include "util/IPRange.h"
31
32 #include <boost/bind.hpp>
33 #include <boost/algorithm/string.hpp>
34 #include <xercesc/util/XMLUniDefs.hpp>
35 #include <xmltooling/unicode.h>
36 #include <xmltooling/util/XMLHelper.h>
37
38 #ifdef WIN32
39 # include <winsock2.h>
40 # include <ws2tcpip.h>
41 #endif
42
43 #ifdef HAVE_UNISTD_H
44 # include <sys/socket.h>
45 # include <sys/un.h>
46 # include <netdb.h>
47 # include <unistd.h>
48 # include <arpa/inet.h>
49 # include <netinet/in.h>
50 #endif
51
52 #include <sys/types.h>
53 #include <sys/stat.h>           /* for chmod() */
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <errno.h>
57
58 using namespace shibsp;
59 using namespace xmltooling;
60 using namespace xercesc;
61 using namespace boost;
62 using namespace std;
63
64 namespace shibsp {
65     class TCPListener : virtual public SocketListener
66     {
67     public:
68         TCPListener(const DOMElement* e);
69         ~TCPListener() {}
70
71         bool create(ShibSocket& s) const;
72         bool bind(ShibSocket& s, bool force=false) const;
73         bool connect(ShibSocket& s) const;
74         bool close(ShibSocket& s) const;
75         bool accept(ShibSocket& listener, ShibSocket& s) const;
76
77         int send(ShibSocket& s, const char* buf, int len) const {
78             return ::send(s, buf, len, 0);
79         }
80
81         int recv(ShibSocket& s, char* buf, int buflen) const {
82             return ::recv(s, buf, buflen, 0);
83         }
84
85     private:
86         bool setup_tcp_sockaddr();
87
88         string m_address;
89         unsigned short m_port;
90         vector<IPRange> m_acl;
91         size_t m_sockaddrlen;
92 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE
93         struct sockaddr_storage m_sockaddr;
94 #else
95         struct sockaddr_in m_sockaddr;
96 #endif
97     };
98
99     ListenerService* SHIBSP_DLLLOCAL TCPListenerServiceFactory(const DOMElement* const & e)
100     {
101         return new TCPListener(e);
102     }
103
104     static const XMLCh address[] = UNICODE_LITERAL_7(a,d,d,r,e,s,s);
105     static const XMLCh port[] = UNICODE_LITERAL_4(p,o,r,t);
106     static const XMLCh acl[] = UNICODE_LITERAL_3(a,c,l);
107 };
108
109 TCPListener::TCPListener(const DOMElement* e)
110     : SocketListener(e),
111       m_address(XMLHelper::getAttrString(e, getenv("SHIBSP_LISTENER_ADDRESS"), address)),
112       m_port(XMLHelper::getAttrInt(e, 0, port))
113 {
114     if (m_address.empty())
115         m_address = "127.0.0.1";
116
117     if (m_port == 0) {
118         const char* p = getenv("SHIBSP_LISTENER_PORT");
119         if (p && *p)
120             m_port = atoi(p);
121         if (m_port == 0)
122             m_port = 1600;
123     }
124
125     vector<string> rawacls;
126     string aclbuf = XMLHelper::getAttrString(e, "127.0.0.1", acl);
127     boost::split(rawacls, aclbuf, boost::is_space(), algorithm::token_compress_on);
128     for (vector<string>::const_iterator i = rawacls.begin();  i < rawacls.end();  ++i) {
129         try {
130             m_acl.push_back(IPRange::parseCIDRBlock(i->c_str()));
131         }
132         catch (std::exception& ex) {
133             log->error("invalid CIDR block (%s): %s", i->c_str(), ex.what());
134         }
135     }
136
137     if (m_acl.empty()) {
138         log->warn("invalid CIDR range(s) in acl property, allowing 127.0.0.1 as a fall back");
139         m_acl.push_back(IPRange::parseCIDRBlock("127.0.0.1"));
140     }
141
142     if (!setup_tcp_sockaddr()) {
143         throw ConfigurationException("Unable to use configured socket address property.");
144     }
145 }
146
147 bool TCPListener::setup_tcp_sockaddr()
148 {
149     struct addrinfo* ret = nullptr;
150     struct addrinfo hints;
151
152     memset(&hints, 0, sizeof(hints));
153     hints.ai_flags = AI_NUMERICHOST;
154     hints.ai_family = AF_UNSPEC;
155
156     if (getaddrinfo(m_address.c_str(), nullptr, &hints, &ret) != 0) {
157         log->error("unable to parse server address (%s)", m_address.c_str());
158         return false;
159     }
160
161     m_sockaddrlen = ret->ai_addrlen;
162     if (ret->ai_family == AF_INET) {
163         memcpy(&m_sockaddr, ret->ai_addr, m_sockaddrlen);
164         freeaddrinfo(ret);
165         ((struct sockaddr_in*)&m_sockaddr)->sin_port=htons(m_port);
166         return true;
167     }
168 #if defined(AF_INET6) && defined(HAVE_STRUCT_SOCKADDR_STORAGE)
169     else if (ret->ai_family == AF_INET6) {
170         memcpy(&m_sockaddr, ret->ai_addr, m_sockaddrlen);
171         freeaddrinfo(ret);
172         ((struct sockaddr_in6*)&m_sockaddr)->sin6_port=htons(m_port);
173         return true;
174     }
175 #endif
176
177     log->error("unknown address type (%d)", ret->ai_family);
178     freeaddrinfo(ret);
179     return false;
180 }
181
182 bool TCPListener::create(ShibSocket& s) const
183 {
184 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE
185     s = socket(m_sockaddr.ss_family, SOCK_STREAM, 0);
186 #else
187     s = socket(m_sockaddr.sin_family, SOCK_STREAM, 0);
188 #endif
189 #ifdef WIN32
190     if(s == INVALID_SOCKET)
191 #else
192     if (s < 0)
193 #endif
194         return log_error("socket");
195     return true;
196 }
197
198 bool TCPListener::bind(ShibSocket& s, bool force) const
199 {
200     // XXX: Do we care about the return value from setsockopt?
201     int opt = 1;
202     ::setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
203
204 #ifdef WIN32
205     if (SOCKET_ERROR==::bind(s, (const struct sockaddr*)&m_sockaddr, m_sockaddrlen) || SOCKET_ERROR==::listen(s, 3)) {
206         log_error("bind");
207         close(s);
208         return false;
209     }
210 #else
211     // Newer BSDs, and Solaris, require the struct length be passed based on the socket address.
212     // All but Solaris seem to have an ss_len field in the sockaddr_storage struct.
213 # ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
214 #  ifdef HAVE_STRUCT_SOCKADDR_STORAGE
215     if (::bind(s, (const struct sockaddr*)&m_sockaddr, m_sockaddr.ss_len) < 0) {
216 #  else
217     if (::bind(s, (const struct sockaddr*)&m_sockaddr, m_sockaddr.sin_len) < 0) {
218 #  endif
219 # else
220     if (::bind(s, (const struct sockaddr*)&m_sockaddr, m_sockaddrlen) < 0) {
221 # endif
222         log_error("bind");
223         close(s);
224         return false;
225     }
226     ::listen(s, 3);
227 #endif
228     return true;
229 }
230
231 bool TCPListener::connect(ShibSocket& s) const
232 {
233 #ifdef WIN32
234     if(SOCKET_ERROR==::connect(s, (const struct sockaddr*)&m_sockaddr, m_sockaddrlen))
235         return log_error("connect");
236 #else
237     // Newer BSDs require the struct length be passed based on the socket address.
238     // Others have no field for that and take the whole struct size like Windows does.
239 # ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
240 #  ifdef HAVE_STRUCT_SOCKADDR_STORAGE
241     if (::connect(s, (const struct sockaddr*)&m_sockaddr, m_sockaddr.ss_len) < 0)
242 #  else
243     if (::connect(s, (const struct sockaddr*)&m_sockaddr, m_sockaddr.sin_len) < 0)
244 #  endif
245 # else
246     if (::connect(s, (const struct sockaddr*)&m_sockaddr, m_sockaddrlen) < 0)
247 # endif
248         return log_error("connect");
249 #endif
250     return true;
251 }
252
253 bool TCPListener::close(ShibSocket& s) const
254 {
255 #ifdef WIN32
256     closesocket(s);
257 #else
258     ::close(s);
259 #endif
260     return true;
261 }
262
263 bool TCPListener::accept(ShibSocket& listener, ShibSocket& s) const
264 {
265 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE
266     struct sockaddr_storage addr;
267 #else
268     struct sockaddr_in addr;
269 #endif
270     memset(&addr, 0, sizeof(addr));
271
272 #ifdef WIN32
273     int size=sizeof(addr);
274     s=::accept(listener, (struct sockaddr*)&addr, &size);
275     if(s==INVALID_SOCKET)
276 #else
277     socklen_t size=sizeof(addr);
278     s=::accept(listener, (struct sockaddr*)&addr, &size);
279     if (s < 0)
280 #endif
281         return log_error("accept");
282
283     static bool (IPRange::* contains)(const struct sockaddr*) const = &IPRange::contains;
284     if (find_if(m_acl.begin(), m_acl.end(), boost::bind(contains, _1, (const struct sockaddr*)&addr)) == m_acl.end()) {
285         close(s);
286         s = -1;
287         log->error("accept() rejected client with invalid address");
288         return false;
289     }
290     return true;
291 }