separated udp
[radsecproxy.git] / tcp.c
1 /*
2  * Copyright (C) 2008 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 <openssl/ssl.h>
28 #include "debug.h"
29 #include "list.h"
30 #include "util.h"
31 #include "radsecproxy.h"
32 #include "tcp.h"
33
34 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
35     struct timeval now;
36     time_t elapsed;
37     
38     debug(DBG_DBG, "tcpconnect: called from %s", text);
39     pthread_mutex_lock(&server->lock);
40     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
41         /* already reconnected, nothing to do */
42         debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
43         pthread_mutex_unlock(&server->lock);
44         return 1;
45     }
46
47     for (;;) {
48         gettimeofday(&now, NULL);
49         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
50         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
51             debug(DBG_DBG, "tcpconnect: timeout");
52             if (server->sock >= 0)
53                 close(server->sock);
54             pthread_mutex_unlock(&server->lock);
55             return 0;
56         }
57         if (server->connectionok) {
58             server->connectionok = 0;
59             sleep(2);
60         } else if (elapsed < 1)
61             sleep(2);
62         else if (elapsed < 60) {
63             debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
64             sleep(elapsed);
65         } else if (elapsed < 100000) {
66             debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
67             sleep(60);
68         } else
69             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
70         debug(DBG_WARN, "tcpconnect: trying to open TCP connection to %s port %s", server->conf->host, server->conf->port);
71         if (server->sock >= 0)
72             close(server->sock);
73         if ((server->sock = connecttcp(server->conf->addrinfo, getsrcprotores(RAD_TCP))) >= 0)
74             break;
75         debug(DBG_ERR, "tcpconnect: connecttcp failed");
76     }
77     debug(DBG_WARN, "tcpconnect: TCP connection to %s port %s up", server->conf->host, server->conf->port);
78     gettimeofday(&server->lastconnecttry, NULL);
79     pthread_mutex_unlock(&server->lock);
80     return 1;
81 }
82
83 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
84 /* returns 0 on timeout, -1 on error and num if ok */
85 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
86     int ndesc, cnt, len;
87     fd_set readfds, writefds;
88     struct timeval timer;
89     
90     if (s < 0)
91         return -1;
92     /* make socket non-blocking? */
93     for (len = 0; len < num; len += cnt) {
94         FD_ZERO(&readfds);
95         FD_SET(s, &readfds);
96         writefds = readfds;
97         if (timeout) {
98             timer.tv_sec = timeout;
99             timer.tv_usec = 0;
100         }
101         ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
102         if (ndesc < 1)
103             return ndesc;
104
105         cnt = read(s, buf + len, num - len);
106         if (cnt <= 0)
107             return -1;
108     }
109     return num;
110 }
111
112 /* timeout in seconds, 0 means no timeout (blocking) */
113 unsigned char *radtcpget(int s, int timeout) {
114     int cnt, len;
115     unsigned char buf[4], *rad;
116
117     for (;;) {
118         cnt = tcpreadtimeout(s, buf, 4, timeout);
119         if (cnt < 1) {
120             debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
121             return NULL;
122         }
123
124         len = RADLEN(buf);
125         rad = malloc(len);
126         if (!rad) {
127             debug(DBG_ERR, "radtcpget: malloc failed");
128             continue;
129         }
130         memcpy(rad, buf, 4);
131         
132         cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
133         if (cnt < 1) {
134             debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
135             free(rad);
136             return NULL;
137         }
138         
139         if (len >= 20)
140             break;
141         
142         free(rad);
143         debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
144     }
145     
146     debug(DBG_DBG, "radtcpget: got %d bytes", len);
147     return rad;
148 }
149
150 int clientradputtcp(struct server *server, unsigned char *rad) {
151     int cnt;
152     size_t len;
153     struct timeval lastconnecttry;
154     struct clsrvconf *conf = server->conf;
155     
156     len = RADLEN(rad);
157     lastconnecttry = server->lastconnecttry;
158     while ((cnt = write(server->sock, rad, len)) <= 0) {
159         debug(DBG_ERR, "clientradputtcp: write error");
160         tcpconnect(server, &lastconnecttry, 0, "clientradputtcp");
161         lastconnecttry = server->lastconnecttry;
162     }
163
164     server->connectionok = 1;
165     debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->host);
166     return 1;
167 }
168
169 void *tcpclientrd(void *arg) {
170     struct server *server = (struct server *)arg;
171     unsigned char *buf;
172     struct timeval lastconnecttry;
173     
174     for (;;) {
175         /* yes, lastconnecttry is really necessary */
176         lastconnecttry = server->lastconnecttry;
177         buf = radtcpget(server->sock, 0);
178         if (!buf) {
179             tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
180             continue;
181         }
182
183         if (!replyh(server, buf))
184             free(buf);
185     }
186     server->clientrdgone = 1;
187     return NULL;
188 }
189
190 void *tcpserverwr(void *arg) {
191     int cnt;
192     struct client *client = (struct client *)arg;
193     struct queue *replyq;
194     struct reply *reply;
195     
196     debug(DBG_DBG, "tcpserverwr: starting for %s", client->conf->host);
197     replyq = client->replyq;
198     for (;;) {
199         pthread_mutex_lock(&replyq->mutex);
200         while (!list_first(replyq->entries)) {
201             if (client->sock >= 0) {        
202                 debug(DBG_DBG, "tcpserverwr: waiting for signal");
203                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
204                 debug(DBG_DBG, "tcpserverwr: got signal");
205             }
206             if (client->sock < 0) {
207                 /* s might have changed while waiting */
208                 pthread_mutex_unlock(&replyq->mutex);
209                 debug(DBG_DBG, "tcpserverwr: exiting as requested");
210                 pthread_exit(NULL);
211             }
212         }
213         reply = (struct reply *)list_shift(replyq->entries);
214         pthread_mutex_unlock(&replyq->mutex);
215         cnt = write(client->sock, reply->buf, RADLEN(reply->buf));
216         if (cnt > 0)
217             debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d",
218                   cnt, RADLEN(reply->buf));
219         else
220             debug(DBG_ERR, "tcpserverwr: write error for %s", client->conf->host);
221         free(reply->buf);
222         free(reply);
223     }
224 }
225
226 void tcpserverrd(struct client *client) {
227     struct request rq;
228     pthread_t tcpserverwrth;
229     
230     debug(DBG_DBG, "tcpserverrd: starting for %s", client->conf->host);
231     
232     if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
233         debug(DBG_ERR, "tcpserverrd: pthread_create failed");
234         return;
235     }
236
237     for (;;) {
238         memset(&rq, 0, sizeof(struct request));
239         rq.buf = radtcpget(client->sock, 0);
240         if (!rq.buf) {
241             debug(DBG_ERR, "tcpserverrd: connection from %s lost", client->conf->host);
242             break;
243         }
244         debug(DBG_DBG, "tcpserverrd: got Radius message from %s", client->conf->host);
245         rq.from = client;
246         if (!radsrv(&rq)) {
247             debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
248             break;
249         }
250     }
251
252     /* stop writer by setting s to -1 and give signal in case waiting for data */
253     client->sock = -1;
254     pthread_mutex_lock(&client->replyq->mutex);
255     pthread_cond_signal(&client->replyq->cond);
256     pthread_mutex_unlock(&client->replyq->mutex);
257     debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
258     pthread_join(tcpserverwrth, NULL);
259     removeclientrqs(client);
260     debug(DBG_DBG, "tcpserverrd: reader for %s exiting", client->conf->host);
261 }
262
263 void *tcpservernew(void *arg) {
264     int s;
265     struct sockaddr_storage from;
266     size_t fromlen = sizeof(from);
267     struct clsrvconf *conf;
268     struct client *client;
269
270     s = *(int *)arg;
271     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
272         debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
273         goto exit;
274     }
275     debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from, fromlen));
276
277     conf = find_clconf(RAD_TCP, (struct sockaddr *)&from, NULL);
278     if (conf) {
279         client = addclient(conf);
280         if (client) {
281             client->sock = s;
282             tcpserverrd(client);
283             removeclient(client);
284         } else
285             debug(DBG_WARN, "tcpservernew: failed to create new client instance");
286     } else
287         debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
288
289  exit:
290     shutdown(s, SHUT_RDWR);
291     close(s);
292     pthread_exit(NULL);
293 }
294
295 void *tcplistener(void *arg) {
296     pthread_t tcpserverth;
297     int s, *sp = (int *)arg;
298     struct sockaddr_storage from;
299     size_t fromlen = sizeof(from);
300
301     listen(*sp, 0);
302
303     for (;;) {
304         s = accept(*sp, (struct sockaddr *)&from, &fromlen);
305         if (s < 0) {
306             debug(DBG_WARN, "accept failed");
307             continue;
308         }
309         if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
310             debug(DBG_ERR, "tcplistener: pthread_create failed");
311             shutdown(s, SHUT_RDWR);
312             close(s);
313             continue;
314         }
315         pthread_detach(tcpserverth);
316     }
317     free(sp);
318     return NULL;
319 }