Stop resolver scripts from signalling "not found".
[libradsec.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 = resolvepassiveaddrinfo(protoopts ? protoopts->sourcearg : NULL, NULL, protodefs.socktype);
82 }
83
84 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
85     struct timeval now;
86     time_t elapsed;
87
88     debug(DBG_DBG, "tcpconnect: called from %s", text);
89     pthread_mutex_lock(&server->lock);
90     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
91         /* already reconnected, nothing to do */
92         debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
93         pthread_mutex_unlock(&server->lock);
94         return 1;
95     }
96
97     for (;;) {
98         gettimeofday(&now, NULL);
99         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
100         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
101             debug(DBG_DBG, "tcpconnect: timeout");
102             if (server->sock >= 0)
103                 close(server->sock);
104             pthread_mutex_unlock(&server->lock);
105             return 0;
106         }
107         if (server->connectionok) {
108             server->connectionok = 0;
109             sleep(2);
110         } else if (elapsed < 1)
111             sleep(2);
112         else if (elapsed < 60) {
113             debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
114             sleep(elapsed);
115         } else if (elapsed < 100000) {
116             debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
117             sleep(60);
118         } else
119             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
120
121         if (server->sock >= 0)
122             close(server->sock);
123         if ((server->sock = connecttcphostlist(server->conf->hostports, srcres)) >= 0)
124             break;
125     }
126     server->connectionok = 1;
127     gettimeofday(&server->lastconnecttry, NULL);
128     pthread_mutex_unlock(&server->lock);
129     return 1;
130 }
131
132 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
133 /* returns 0 on timeout, -1 on error and num if ok */
134 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
135     int ndesc, cnt, len;
136     fd_set readfds, writefds;
137     struct timeval timer;
138
139     if (s < 0)
140         return -1;
141     /* make socket non-blocking? */
142     for (len = 0; len < num; len += cnt) {
143         FD_ZERO(&readfds);
144         FD_SET(s, &readfds);
145         writefds = readfds;
146         if (timeout) {
147             timer.tv_sec = timeout;
148             timer.tv_usec = 0;
149         }
150         ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
151         if (ndesc < 1)
152             return ndesc;
153
154         cnt = read(s, buf + len, num - len);
155         if (cnt <= 0)
156             return -1;
157     }
158     return num;
159 }
160
161 /* timeout in seconds, 0 means no timeout (blocking) */
162 unsigned char *radtcpget(int s, int timeout) {
163     int cnt, len;
164     unsigned char buf[4], *rad;
165
166     for (;;) {
167         cnt = tcpreadtimeout(s, buf, 4, timeout);
168         if (cnt < 1) {
169             debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
170             return NULL;
171         }
172
173         len = RADLEN(buf);
174         rad = malloc(len);
175         if (!rad) {
176             debug(DBG_ERR, "radtcpget: malloc failed");
177             continue;
178         }
179         memcpy(rad, buf, 4);
180
181         cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
182         if (cnt < 1) {
183             debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
184             free(rad);
185             return NULL;
186         }
187
188         if (len >= 20)
189             break;
190
191         free(rad);
192         debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
193     }
194
195     debug(DBG_DBG, "radtcpget: got %d bytes", len);
196     return rad;
197 }
198
199 int clientradputtcp(struct server *server, unsigned char *rad) {
200     int cnt;
201     size_t len;
202     struct clsrvconf *conf = server->conf;
203
204     if (!server->connectionok)
205         return 0;
206     len = RADLEN(rad);
207     if ((cnt = write(server->sock, rad, len)) <= 0) {
208         debug(DBG_ERR, "clientradputtcp: write error");
209         return 0;
210     }
211     debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->name);
212     return 1;
213 }
214
215 void *tcpclientrd(void *arg) {
216     struct server *server = (struct server *)arg;
217     unsigned char *buf;
218     struct timeval lastconnecttry;
219
220     for (;;) {
221         /* yes, lastconnecttry is really necessary */
222         lastconnecttry = server->lastconnecttry;
223         buf = radtcpget(server->sock, 0);
224         if (!buf) {
225             tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
226             continue;
227         }
228
229         replyh(server, buf);
230     }
231     server->clientrdgone = 1;
232     return NULL;
233 }
234
235 void *tcpserverwr(void *arg) {
236     int cnt;
237     struct client *client = (struct client *)arg;
238     struct gqueue *replyq;
239     struct request *reply;
240
241     debug(DBG_DBG, "tcpserverwr: starting for %s", addr2string(client->addr));
242     replyq = client->replyq;
243     for (;;) {
244         pthread_mutex_lock(&replyq->mutex);
245         while (!list_first(replyq->entries)) {
246             if (client->sock >= 0) {
247                 debug(DBG_DBG, "tcpserverwr: waiting for signal");
248                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
249                 debug(DBG_DBG, "tcpserverwr: got signal");
250             }
251             if (client->sock < 0) {
252                 /* s might have changed while waiting */
253                 pthread_mutex_unlock(&replyq->mutex);
254                 debug(DBG_DBG, "tcpserverwr: exiting as requested");
255                 pthread_exit(NULL);
256             }
257         }
258         reply = (struct request *)list_shift(replyq->entries);
259         pthread_mutex_unlock(&replyq->mutex);
260         cnt = write(client->sock, reply->replybuf, RADLEN(reply->replybuf));
261         if (cnt > 0)
262             debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d to %s",
263                   cnt, RADLEN(reply->replybuf), addr2string(client->addr));
264         else
265             debug(DBG_ERR, "tcpserverwr: write error for %s", addr2string(client->addr));
266         freerq(reply);
267     }
268 }
269
270 void tcpserverrd(struct client *client) {
271     struct request *rq;
272     uint8_t *buf;
273     pthread_t tcpserverwrth;
274
275     debug(DBG_DBG, "tcpserverrd: starting for %s", addr2string(client->addr));
276
277     if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
278         debug(DBG_ERR, "tcpserverrd: pthread_create failed");
279         return;
280     }
281
282     for (;;) {
283         buf = radtcpget(client->sock, 0);
284         if (!buf) {
285             debug(DBG_ERR, "tcpserverrd: connection from %s lost", addr2string(client->addr));
286             break;
287         }
288         debug(DBG_DBG, "tcpserverrd: got Radius message from %s", addr2string(client->addr));
289         rq = newrequest();
290         if (!rq) {
291             free(buf);
292             continue;
293         }
294         rq->buf = buf;
295         rq->from = client;
296         if (!radsrv(rq)) {
297             debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
298             break;
299         }
300     }
301
302     /* stop writer by setting s to -1 and give signal in case waiting for data */
303     client->sock = -1;
304     pthread_mutex_lock(&client->replyq->mutex);
305     pthread_cond_signal(&client->replyq->cond);
306     pthread_mutex_unlock(&client->replyq->mutex);
307     debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
308     pthread_join(tcpserverwrth, NULL);
309     debug(DBG_DBG, "tcpserverrd: reader for %s exiting", addr2string(client->addr));
310 }
311 void *tcpservernew(void *arg) {
312     int s;
313     struct sockaddr_storage from;
314     socklen_t fromlen = sizeof(from);
315     struct clsrvconf *conf;
316     struct client *client;
317
318     s = *(int *)arg;
319     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
320         debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
321         goto exit;
322     }
323     debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from));
324
325     conf = find_clconf(handle, (struct sockaddr *)&from, NULL);
326     if (conf) {
327         client = addclient(conf, 1);
328         if (client) {
329             client->sock = s;
330             client->addr = addr_copy((struct sockaddr *)&from);
331             tcpserverrd(client);
332             removeclient(client);
333         } else
334             debug(DBG_WARN, "tcpservernew: failed to create new client instance");
335     } else
336         debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
337
338 exit:
339     shutdown(s, SHUT_RDWR);
340     close(s);
341     pthread_exit(NULL);
342 }
343
344 void *tcplistener(void *arg) {
345     pthread_t tcpserverth;
346     int s, *sp = (int *)arg;
347     struct sockaddr_storage from;
348     socklen_t fromlen = sizeof(from);
349
350     listen(*sp, 0);
351
352     for (;;) {
353         s = accept(*sp, (struct sockaddr *)&from, &fromlen);
354         if (s < 0) {
355             debug(DBG_WARN, "accept failed");
356             continue;
357         }
358         if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
359             debug(DBG_ERR, "tcplistener: pthread_create failed");
360             shutdown(s, SHUT_RDWR);
361             close(s);
362             continue;
363         }
364         pthread_detach(tcpserverth);
365     }
366     free(sp);
367     return NULL;
368 }
369 #else
370 const struct protodefs *tcpinit(uint8_t h) {
371     return NULL;
372 }
373 #endif
374
375 /* Local Variables: */
376 /* c-file-style: "stroustrup" */
377 /* End: */