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