WIP: Fix the Proxy-State issue.
[libradsec.git] / tcp.c
1 /* Copyright (c) 2007-2009, UNINETT AS
2  * Copyright (c) 2012, NORDUnet A/S */
3 /* See LICENSE for licensing information. */
4
5 #include <signal.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <netdb.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <limits.h>
12 #ifdef SYS_SOLARIS9
13 #include <fcntl.h>
14 #endif
15 #include <sys/time.h>
16 #include <sys/types.h>
17 #include <sys/select.h>
18 #include <ctype.h>
19 #include <sys/wait.h>
20 #include <arpa/inet.h>
21 #include <regex.h>
22 #include <pthread.h>
23 #include "radsecproxy.h"
24 #include "hostport.h"
25
26 #ifdef RADPROT_TCP
27 #include "debug.h"
28 #include "util.h"
29 static void setprotoopts(struct commonprotoopts *opts);
30 static char **getlistenerargs();
31 void *tcplistener(void *arg);
32 int tcpconnect(struct server *server, struct timeval *when, int timeout, char * text);
33 void *tcpclientrd(void *arg);
34 int clientradputtcp(struct server *server, unsigned char *rad);
35 void tcpsetsrcres();
36
37 static const struct protodefs protodefs = {
38     "tcp",
39     NULL, /* secretdefault */
40     SOCK_STREAM, /* socktype */
41     "1812", /* portdefault */
42     0, /* retrycountdefault */
43     0, /* retrycountmax */
44     REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
45     60, /* retryintervalmax */
46     DUPLICATE_INTERVAL, /* duplicateintervaldefault */
47     setprotoopts, /* setprotoopts */
48     getlistenerargs, /* getlistenerargs */
49     tcplistener, /* listener */
50     tcpconnect, /* connecter */
51     tcpclientrd, /* clientconnreader */
52     clientradputtcp, /* clientradput */
53     NULL, /* addclient */
54     NULL, /* addserverextra */
55     tcpsetsrcres, /* setsrcres */
56     NULL /* initextra */
57 };
58
59 static struct addrinfo *srcres = NULL;
60 static uint8_t handle;
61 static struct commonprotoopts *protoopts = NULL;
62 const struct protodefs *tcpinit(uint8_t h) {
63     handle = h;
64     return &protodefs;
65 }
66
67 static void setprotoopts(struct commonprotoopts *opts) {
68     protoopts = opts;
69 }
70
71 static char **getlistenerargs() {
72     return protoopts ? protoopts->listenargs : NULL;
73 }
74
75 void tcpsetsrcres() {
76     if (!srcres)
77         srcres =
78             resolvepassiveaddrinfo(protoopts ? protoopts->sourcearg : NULL,
79                                    AF_UNSPEC, NULL, protodefs.socktype);
80 }
81
82 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
83     struct timeval now;
84     time_t elapsed;
85
86     debug(DBG_DBG, "tcpconnect: called from %s", text);
87     pthread_mutex_lock(&server->lock);
88     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
89         /* already reconnected, nothing to do */
90         debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
91         pthread_mutex_unlock(&server->lock);
92         return 1;
93     }
94
95     for (;;) {
96         gettimeofday(&now, NULL);
97         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
98         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
99             debug(DBG_DBG, "tcpconnect: timeout");
100             if (server->sock >= 0)
101                 close(server->sock);
102             pthread_mutex_unlock(&server->lock);
103             return 0;
104         }
105         if (server->connectionok) {
106             server->connectionok = 0;
107             sleep(2);
108         } else if (elapsed < 1)
109             sleep(2);
110         else if (elapsed < 60) {
111             debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
112             sleep(elapsed);
113         } else if (elapsed < 100000) {
114             debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
115             sleep(60);
116         } else
117             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
118
119         if (server->sock >= 0)
120             close(server->sock);
121         if ((server->sock = connecttcphostlist(server->conf->hostports, srcres)) >= 0)
122             break;
123     }
124     server->connectionok = 1;
125     gettimeofday(&server->lastconnecttry, NULL);
126     pthread_mutex_unlock(&server->lock);
127     return 1;
128 }
129
130 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
131 /* returns 0 on timeout, -1 on error and num if ok */
132 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
133     int ndesc, cnt, len;
134     fd_set readfds, writefds;
135     struct timeval timer;
136
137     if (s < 0)
138         return -1;
139     /* make socket non-blocking? */
140     for (len = 0; len < num; len += cnt) {
141         FD_ZERO(&readfds);
142         FD_SET(s, &readfds);
143         writefds = readfds;
144         if (timeout) {
145             timer.tv_sec = timeout;
146             timer.tv_usec = 0;
147         }
148         ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
149         if (ndesc < 1)
150             return ndesc;
151
152         cnt = read(s, buf + len, num - len);
153         if (cnt <= 0)
154             return -1;
155     }
156     return num;
157 }
158
159 /* timeout in seconds, 0 means no timeout (blocking) */
160 unsigned char *radtcpget(int s, int timeout) {
161     int cnt, len;
162     unsigned char buf[4], *rad;
163
164     for (;;) {
165         cnt = tcpreadtimeout(s, buf, 4, timeout);
166         if (cnt < 1) {
167             debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
168             return NULL;
169         }
170
171         len = RADLEN(buf);
172         rad = malloc(len);
173         if (!rad) {
174             debug(DBG_ERR, "radtcpget: malloc failed");
175             continue;
176         }
177         memcpy(rad, buf, 4);
178
179         cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
180         if (cnt < 1) {
181             debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
182             free(rad);
183             return NULL;
184         }
185
186         if (len >= 20)
187             break;
188
189         free(rad);
190         debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
191     }
192
193     debug(DBG_DBG, "radtcpget: got %d bytes", len);
194     return rad;
195 }
196
197 int clientradputtcp(struct server *server, unsigned char *rad) {
198     int cnt;
199     size_t len;
200     struct clsrvconf *conf = server->conf;
201
202     if (!server->connectionok)
203         return 0;
204     len = RADLEN(rad);
205     if ((cnt = write(server->sock, rad, len)) <= 0) {
206         debug(DBG_ERR, "clientradputtcp: write error");
207         return 0;
208     }
209     debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->name);
210     return 1;
211 }
212
213 void *tcpclientrd(void *arg) {
214     struct server *server = (struct server *)arg;
215     unsigned char *buf;
216     struct timeval lastconnecttry;
217
218     for (;;) {
219         /* yes, lastconnecttry is really necessary */
220         lastconnecttry = server->lastconnecttry;
221         buf = radtcpget(server->sock, 0);
222         if (!buf) {
223             tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
224             continue;
225         }
226
227         replyh(server, buf);
228     }
229     server->clientrdgone = 1;
230     return NULL;
231 }
232
233 void *tcpserverwr(void *arg) {
234     int cnt;
235     struct client *client = (struct client *)arg;
236     struct gqueue *replyq;
237     struct request *reply;
238
239     debug(DBG_DBG, "tcpserverwr: starting for %s", addr2string(client->addr));
240     replyq = client->replyq;
241     for (;;) {
242         pthread_mutex_lock(&replyq->mutex);
243         while (!list_first(replyq->entries)) {
244             if (client->sock >= 0) {
245                 debug(DBG_DBG, "tcpserverwr: waiting for signal");
246                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
247                 debug(DBG_DBG, "tcpserverwr: got signal");
248             }
249             if (client->sock < 0) {
250                 /* s might have changed while waiting */
251                 pthread_mutex_unlock(&replyq->mutex);
252                 debug(DBG_DBG, "tcpserverwr: exiting as requested");
253                 pthread_exit(NULL);
254             }
255         }
256         reply = (struct request *)list_shift(replyq->entries);
257         pthread_mutex_unlock(&replyq->mutex);
258         cnt = write(client->sock, reply->replybuf, RADLEN(reply->replybuf));
259         if (cnt > 0)
260             debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d to %s",
261                   cnt, RADLEN(reply->replybuf), addr2string(client->addr));
262         else
263             debug(DBG_ERR, "tcpserverwr: write error for %s", addr2string(client->addr));
264         freerq(reply);
265     }
266 }
267
268 void tcpserverrd(struct client *client) {
269     struct request *rq;
270     uint8_t *buf;
271     pthread_t tcpserverwrth;
272
273     debug(DBG_DBG, "tcpserverrd: starting for %s", addr2string(client->addr));
274
275     if (pthread_create(&tcpserverwrth, &pthread_attr, tcpserverwr, (void *)client)) {
276         debug(DBG_ERR, "tcpserverrd: pthread_create failed");
277         return;
278     }
279
280     for (;;) {
281         buf = radtcpget(client->sock, 0);
282         if (!buf) {
283             debug(DBG_ERR, "tcpserverrd: connection from %s lost", addr2string(client->addr));
284             break;
285         }
286         debug(DBG_DBG, "tcpserverrd: got Radius message from %s", addr2string(client->addr));
287         rq = newrequest();
288         if (!rq) {
289             free(buf);
290             continue;
291         }
292         rq->buf = buf;
293         rq->from = client;
294         if (!radsrv(rq)) {
295             debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
296             break;
297         }
298     }
299
300     /* stop writer by setting s to -1 and give signal in case waiting for data */
301     client->sock = -1;
302     pthread_mutex_lock(&client->replyq->mutex);
303     pthread_cond_signal(&client->replyq->cond);
304     pthread_mutex_unlock(&client->replyq->mutex);
305     debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
306     pthread_join(tcpserverwrth, NULL);
307     debug(DBG_DBG, "tcpserverrd: reader for %s exiting", addr2string(client->addr));
308 }
309 void *tcpservernew(void *arg) {
310     int s;
311     struct sockaddr_storage from;
312     socklen_t fromlen = sizeof(from);
313     struct clsrvconf *conf;
314     struct client *client;
315
316     s = *(int *)arg;
317     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
318         debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
319         goto exit;
320     }
321     debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from));
322
323     conf = find_clconf(handle, (struct sockaddr *)&from, NULL);
324     if (conf) {
325         client = addclient(conf, 1);
326         if (client) {
327             client->sock = s;
328             client->addr = addr_copy((struct sockaddr *)&from);
329             tcpserverrd(client);
330             removeclient(client);
331         } else
332             debug(DBG_WARN, "tcpservernew: failed to create new client instance");
333     } else
334         debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
335
336 exit:
337     shutdown(s, SHUT_RDWR);
338     close(s);
339     pthread_exit(NULL);
340 }
341
342 void *tcplistener(void *arg) {
343     pthread_t tcpserverth;
344     int s, *sp = (int *)arg;
345     struct sockaddr_storage from;
346     socklen_t fromlen = sizeof(from);
347
348     listen(*sp, 0);
349
350     for (;;) {
351         s = accept(*sp, (struct sockaddr *)&from, &fromlen);
352         if (s < 0) {
353             debug(DBG_WARN, "accept failed");
354             continue;
355         }
356         if (pthread_create(&tcpserverth, &pthread_attr, tcpservernew, (void *)&s)) {
357             debug(DBG_ERR, "tcplistener: pthread_create failed");
358             shutdown(s, SHUT_RDWR);
359             close(s);
360             continue;
361         }
362         pthread_detach(tcpserverth);
363     }
364     free(sp);
365     return NULL;
366 }
367 #else
368 const struct protodefs *tcpinit(uint8_t h) {
369     return NULL;
370 }
371 #endif
372
373 /* Local Variables: */
374 /* c-file-style: "stroustrup" */
375 /* End: */