some code improvemetns, more efficiently removing outstanding requests when removing...
[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 "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     server->connectionok = 1;
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 clsrvconf *conf = server->conf;
155
156     if (!server->connectionok)
157         return 0;
158     len = RADLEN(rad);
159     if ((cnt = write(server->sock, rad, len)) <= 0) {
160         debug(DBG_ERR, "clientradputtcp: write error");
161         return 0;
162     }
163     debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->host);
164     return 1;
165 }
166
167 void *tcpclientrd(void *arg) {
168     struct server *server = (struct server *)arg;
169     unsigned char *buf;
170     struct timeval lastconnecttry;
171     
172     for (;;) {
173         /* yes, lastconnecttry is really necessary */
174         lastconnecttry = server->lastconnecttry;
175         buf = radtcpget(server->sock, 0);
176         if (!buf) {
177             tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
178             continue;
179         }
180
181         replyh(server, buf);
182     }
183     server->clientrdgone = 1;
184     return NULL;
185 }
186
187 void *tcpserverwr(void *arg) {
188     int cnt;
189     struct client *client = (struct client *)arg;
190     struct queue *replyq;
191     struct request *reply;
192     
193     debug(DBG_DBG, "tcpserverwr: starting for %s", addr2string(client->addr));
194     replyq = client->replyq;
195     for (;;) {
196         pthread_mutex_lock(&replyq->mutex);
197         while (!list_first(replyq->entries)) {
198             if (client->sock >= 0) {        
199                 debug(DBG_DBG, "tcpserverwr: waiting for signal");
200                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
201                 debug(DBG_DBG, "tcpserverwr: got signal");
202             }
203             if (client->sock < 0) {
204                 /* s might have changed while waiting */
205                 pthread_mutex_unlock(&replyq->mutex);
206                 debug(DBG_DBG, "tcpserverwr: exiting as requested");
207                 pthread_exit(NULL);
208             }
209         }
210         reply = (struct request *)list_shift(replyq->entries);
211         pthread_mutex_unlock(&replyq->mutex);
212         cnt = write(client->sock, reply->replybuf, RADLEN(reply->replybuf));
213         if (cnt > 0)
214             debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d to %s",
215                   cnt, RADLEN(reply->replybuf), addr2string(client->addr));
216         else
217             debug(DBG_ERR, "tcpserverwr: write error for %s", addr2string(client->addr));
218         freerq(reply);
219     }
220 }
221
222 void tcpserverrd(struct client *client) {
223     struct request *rq;
224     uint8_t *buf;
225     pthread_t tcpserverwrth;
226     
227     debug(DBG_DBG, "tcpserverrd: starting for %s", addr2string(client->addr));
228     
229     if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
230         debug(DBG_ERR, "tcpserverrd: pthread_create failed");
231         return;
232     }
233
234     for (;;) {
235         buf = radtcpget(client->sock, 0);
236         if (!buf) {
237             debug(DBG_ERR, "tcpserverrd: connection from %s lost", addr2string(client->addr));
238             break;
239         }
240         debug(DBG_DBG, "tcpserverrd: got Radius message from %s", addr2string(client->addr));
241         rq = newrequest();
242         if (!rq) {
243             free(buf);
244             continue;
245         }
246         rq->buf = buf;
247         rq->from = client;
248         if (!radsrv(rq)) {
249             debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
250             break;
251         }
252     }
253
254     /* stop writer by setting s to -1 and give signal in case waiting for data */
255     client->sock = -1;
256     pthread_mutex_lock(&client->replyq->mutex);
257     pthread_cond_signal(&client->replyq->cond);
258     pthread_mutex_unlock(&client->replyq->mutex);
259     debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
260     pthread_join(tcpserverwrth, NULL);
261     debug(DBG_DBG, "tcpserverrd: reader for %s exiting", addr2string(client->addr));
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));
276
277     conf = find_clconf(RAD_TCP, (struct sockaddr *)&from, NULL);
278     if (conf) {
279         client = addclient(conf, 1);
280         if (client) {
281             client->sock = s;
282             client->addr = addr_copy((struct sockaddr *)&from);
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 }