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