various code improvements
[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     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         replyh(server, buf);
184     }
185     server->clientrdgone = 1;
186     return NULL;
187 }
188
189 void *tcpserverwr(void *arg) {
190     int cnt;
191     struct client *client = (struct client *)arg;
192     struct queue *replyq;
193     struct reply *reply;
194     
195     debug(DBG_DBG, "tcpserverwr: starting for %s", client->conf->host);
196     replyq = client->replyq;
197     for (;;) {
198         pthread_mutex_lock(&replyq->mutex);
199         while (!list_first(replyq->entries)) {
200             if (client->sock >= 0) {        
201                 debug(DBG_DBG, "tcpserverwr: waiting for signal");
202                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
203                 debug(DBG_DBG, "tcpserverwr: got signal");
204             }
205             if (client->sock < 0) {
206                 /* s might have changed while waiting */
207                 pthread_mutex_unlock(&replyq->mutex);
208                 debug(DBG_DBG, "tcpserverwr: exiting as requested");
209                 pthread_exit(NULL);
210             }
211         }
212         reply = (struct reply *)list_shift(replyq->entries);
213         pthread_mutex_unlock(&replyq->mutex);
214         cnt = write(client->sock, reply->buf, RADLEN(reply->buf));
215         if (cnt > 0)
216             debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d",
217                   cnt, RADLEN(reply->buf));
218         else
219             debug(DBG_ERR, "tcpserverwr: write error for %s", client->conf->host);
220         free(reply->buf);
221         free(reply);
222     }
223 }
224
225 void tcpserverrd(struct client *client) {
226     struct request rq;
227     pthread_t tcpserverwrth;
228     
229     debug(DBG_DBG, "tcpserverrd: starting for %s", client->conf->host);
230     
231     if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
232         debug(DBG_ERR, "tcpserverrd: pthread_create failed");
233         return;
234     }
235
236     for (;;) {
237         memset(&rq, 0, sizeof(struct request));
238         rq.buf = radtcpget(client->sock, 0);
239         if (!rq.buf) {
240             debug(DBG_ERR, "tcpserverrd: connection from %s lost", client->conf->host);
241             break;
242         }
243         debug(DBG_DBG, "tcpserverrd: got Radius message from %s", client->conf->host);
244         rq.from = client;
245         if (!radsrv(&rq)) {
246             debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
247             break;
248         }
249     }
250
251     /* stop writer by setting s to -1 and give signal in case waiting for data */
252     client->sock = -1;
253     pthread_mutex_lock(&client->replyq->mutex);
254     pthread_cond_signal(&client->replyq->cond);
255     pthread_mutex_unlock(&client->replyq->mutex);
256     debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
257     pthread_join(tcpserverwrth, NULL);
258     removeclientrqs(client);
259     debug(DBG_DBG, "tcpserverrd: reader for %s exiting", client->conf->host);
260 }
261
262 void *tcpservernew(void *arg) {
263     int s;
264     struct sockaddr_storage from;
265     size_t fromlen = sizeof(from);
266     struct clsrvconf *conf;
267     struct client *client;
268
269     s = *(int *)arg;
270     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
271         debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
272         goto exit;
273     }
274     debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from, fromlen));
275
276     conf = find_clconf(RAD_TCP, (struct sockaddr *)&from, NULL);
277     if (conf) {
278         client = addclient(conf);
279         if (client) {
280             client->sock = s;
281             tcpserverrd(client);
282             removeclient(client);
283         } else
284             debug(DBG_WARN, "tcpservernew: failed to create new client instance");
285     } else
286         debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
287
288  exit:
289     shutdown(s, SHUT_RDWR);
290     close(s);
291     pthread_exit(NULL);
292 }
293
294 void *tcplistener(void *arg) {
295     pthread_t tcpserverth;
296     int s, *sp = (int *)arg;
297     struct sockaddr_storage from;
298     size_t fromlen = sizeof(from);
299
300     listen(*sp, 0);
301
302     for (;;) {
303         s = accept(*sp, (struct sockaddr *)&from, &fromlen);
304         if (s < 0) {
305             debug(DBG_WARN, "accept failed");
306             continue;
307         }
308         if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
309             debug(DBG_ERR, "tcplistener: pthread_create failed");
310             shutdown(s, SHUT_RDWR);
311             close(s);
312             continue;
313         }
314         pthread_detach(tcpserverth);
315     }
316     free(sp);
317     return NULL;
318 }