https://issues.shibboleth.net/jira/browse/SSPCPP-569
[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 <fcntl.h>
57 #include <errno.h>
58
59 using namespace shibsp;
60 using namespace xmltooling;
61 using namespace xercesc;
62 using namespace boost;
63 using namespace std;
64
65 namespace shibsp {
66     class TCPListener : virtual public SocketListener
67     {
68     public:
69         TCPListener(const DOMElement* e);
70         ~TCPListener() {}
71
72         bool create(ShibSocket& s) const;
73         bool bind(ShibSocket& s, bool force=false) const;
74         bool connect(ShibSocket& s) const;
75         bool close(ShibSocket& s) const;
76         bool accept(ShibSocket& listener, ShibSocket& s) const;
77
78         int send(ShibSocket& s, const char* buf, int len) const {
79             return ::send(s, buf, len, 0);
80         }
81
82         int recv(ShibSocket& s, char* buf, int buflen) const {
83             return ::recv(s, buf, buflen, 0);
84         }
85
86     private:
87         bool setup_tcp_sockaddr();
88
89         string m_address;
90         unsigned short m_port;
91         vector<IPRange> m_acl;
92         size_t m_sockaddrlen;
93 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE
94         struct sockaddr_storage m_sockaddr;
95 #else
96         struct sockaddr_in m_sockaddr;
97 #endif
98     };
99
100     ListenerService* SHIBSP_DLLLOCAL TCPListenerServiceFactory(const DOMElement* const & e)
101     {
102         return new TCPListener(e);
103     }
104
105     static const XMLCh address[] = UNICODE_LITERAL_7(a,d,d,r,e,s,s);
106     static const XMLCh port[] = UNICODE_LITERAL_4(p,o,r,t);
107     static const XMLCh acl[] = UNICODE_LITERAL_3(a,c,l);
108 };
109
110 TCPListener::TCPListener(const DOMElement* e)
111     : SocketListener(e),
112       m_address(XMLHelper::getAttrString(e, getenv("SHIBSP_LISTENER_ADDRESS"), address)),
113       m_port(XMLHelper::getAttrInt(e, 0, port))
114 {
115     if (m_address.empty())
116         m_address = "127.0.0.1";
117
118     if (m_port == 0) {
119         const char* p = getenv("SHIBSP_LISTENER_PORT");
120         if (p && *p)
121             m_port = atoi(p);
122         if (m_port == 0)
123             m_port = 1600;
124     }
125
126     vector<string> rawacls;
127     string aclbuf = XMLHelper::getAttrString(e, "127.0.0.1", acl);
128     boost::split(rawacls, aclbuf, boost::is_space(), algorithm::token_compress_on);
129     for (vector<string>::const_iterator i = rawacls.begin();  i < rawacls.end();  ++i) {
130         try {
131             m_acl.push_back(IPRange::parseCIDRBlock(i->c_str()));
132         }
133         catch (std::exception& ex) {
134             log->error("invalid CIDR block (%s): %s", i->c_str(), ex.what());
135         }
136     }
137
138     if (m_acl.empty()) {
139         log->warn("invalid CIDR range(s) in acl property, allowing 127.0.0.1 as a fall back");
140         m_acl.push_back(IPRange::parseCIDRBlock("127.0.0.1"));
141     }
142
143     if (!setup_tcp_sockaddr()) {
144         throw ConfigurationException("Unable to use configured socket address property.");
145     }
146 }
147
148 bool TCPListener::setup_tcp_sockaddr()
149 {
150     struct addrinfo* ret = nullptr;
151     struct addrinfo hints;
152
153     memset(&hints, 0, sizeof(hints));
154     hints.ai_flags = AI_NUMERICHOST;
155     hints.ai_family = AF_UNSPEC;
156
157     if (getaddrinfo(m_address.c_str(), nullptr, &hints, &ret) != 0) {
158         log->error("unable to parse server address (%s)", m_address.c_str());
159         return false;
160     }
161
162     m_sockaddrlen = ret->ai_addrlen;
163     if (ret->ai_family == AF_INET) {
164         memcpy(&m_sockaddr, ret->ai_addr, m_sockaddrlen);
165         freeaddrinfo(ret);
166         ((struct sockaddr_in*)&m_sockaddr)->sin_port=htons(m_port);
167         return true;
168     }
169 #if defined(AF_INET6) && defined(HAVE_STRUCT_SOCKADDR_STORAGE)
170     else if (ret->ai_family == AF_INET6) {
171         memcpy(&m_sockaddr, ret->ai_addr, m_sockaddrlen);
172         freeaddrinfo(ret);
173         ((struct sockaddr_in6*)&m_sockaddr)->sin6_port=htons(m_port);
174         return true;
175     }
176 #endif
177
178     log->error("unknown address type (%d)", ret->ai_family);
179     freeaddrinfo(ret);
180     return false;
181 }
182
183 bool TCPListener::create(ShibSocket& s) const
184 {
185     int type = SOCK_STREAM;
186 #ifdef HAVE_SOCK_CLOEXEC
187     type |= SOCK_CLOEXEC;
188 #endif
189
190 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE
191     s = socket(m_sockaddr.ss_family, type, 0);
192 #else
193     s = socket(m_sockaddr.sin_family, type, 0);
194 #endif
195 #ifdef WIN32
196     if(s == INVALID_SOCKET)
197 #else
198     if (s < 0)
199 #endif
200         return log_error("socket");
201
202 #if !defined(HAVE_SOCK_CLOEXEC) && defined(HAVE_FD_CLOEXEC)
203     int fdflags = fcntl(s, F_GETFD);
204     if (fdflags != -1) {
205         fdflags |= FD_CLOEXEC;
206         fcntl(s, F_SETFD, fdflags);
207     }
208 #endif
209
210     return true;
211 }
212
213 bool TCPListener::bind(ShibSocket& s, bool force) const
214 {
215     // XXX: Do we care about the return value from setsockopt?
216     int opt = 1;
217     ::setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
218
219 #ifdef WIN32
220     if (SOCKET_ERROR==::bind(s, (const struct sockaddr*)&m_sockaddr, m_sockaddrlen) || SOCKET_ERROR==::listen(s, 3)) {
221         log_error("bind");
222         close(s);
223         return false;
224     }
225 #else
226     // Newer BSDs, and Solaris, require the struct length be passed based on the socket address.
227     // All but Solaris seem to have an ss_len field in the sockaddr_storage struct.
228 # ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
229 #  ifdef HAVE_STRUCT_SOCKADDR_STORAGE
230     if (::bind(s, (const struct sockaddr*)&m_sockaddr, m_sockaddr.ss_len) < 0) {
231 #  else
232     if (::bind(s, (const struct sockaddr*)&m_sockaddr, m_sockaddr.sin_len) < 0) {
233 #  endif
234 # else
235     if (::bind(s, (const struct sockaddr*)&m_sockaddr, m_sockaddrlen) < 0) {
236 # endif
237         log_error("bind");
238         close(s);
239         return false;
240     }
241     ::listen(s, 3);
242 #endif
243     return true;
244 }
245
246 bool TCPListener::connect(ShibSocket& s) const
247 {
248 #ifdef WIN32
249     if(SOCKET_ERROR==::connect(s, (const struct sockaddr*)&m_sockaddr, m_sockaddrlen))
250         return log_error("connect");
251 #else
252     // Newer BSDs require the struct length be passed based on the socket address.
253     // Others have no field for that and take the whole struct size like Windows does.
254 # ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
255 #  ifdef HAVE_STRUCT_SOCKADDR_STORAGE
256     if (::connect(s, (const struct sockaddr*)&m_sockaddr, m_sockaddr.ss_len) < 0)
257 #  else
258     if (::connect(s, (const struct sockaddr*)&m_sockaddr, m_sockaddr.sin_len) < 0)
259 #  endif
260 # else
261     if (::connect(s, (const struct sockaddr*)&m_sockaddr, m_sockaddrlen) < 0)
262 # endif
263         return log_error("connect");
264 #endif
265     return true;
266 }
267
268 bool TCPListener::close(ShibSocket& s) const
269 {
270 #ifdef WIN32
271     closesocket(s);
272 #else
273     ::close(s);
274 #endif
275     return true;
276 }
277
278 bool TCPListener::accept(ShibSocket& listener, ShibSocket& s) const
279 {
280 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE
281     struct sockaddr_storage addr;
282 #else
283     struct sockaddr_in addr;
284 #endif
285     memset(&addr, 0, sizeof(addr));
286
287 #ifdef WIN32
288     int size=sizeof(addr);
289     s=::accept(listener, (struct sockaddr*)&addr, &size);
290     if(s==INVALID_SOCKET)
291 #else
292     socklen_t size=sizeof(addr);
293     s=::accept(listener, (struct sockaddr*)&addr, &size);
294     if (s < 0)
295 #endif
296         return log_error("accept");
297
298     static bool (IPRange::* contains)(const struct sockaddr*) const = &IPRange::contains;
299     if (find_if(m_acl.begin(), m_acl.end(), boost::bind(contains, _1, (const struct sockaddr*)&addr)) == m_acl.end()) {
300         close(s);
301         s = -1;
302         log->error("accept() rejected client with invalid address");
303         return false;
304     }
305     return true;
306 }