* radsecproxy.c (pwdencrypt): Fix bug with User-Password's of a length
[libradsec.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006-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 /* Code contributions from:
10  *
11  * Arne Schwabe <schwabe at uni-paderborn.de>
12  * Maja Wolniewicz <mgw@umk.pl>
13  * Simon Leinen <simon.leinen@switch.ch>
14  * Stefan Winter <stefan.winter@restena.lu>
15  */
16
17 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
18  *              rd is responsible for init and launching wr
19  * For TLS there is a server instance that launches tlsserverrd for each TLS peer
20  *          each tlsserverrd launches tlsserverwr
21  * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
22  *          for init and launching rd
23  *
24  * serverrd will receive a request, processes it and puts it in the requestq of
25  *          the appropriate clientwr
26  * clientwr monitors its requestq and sends requests
27  * clientrd looks for responses, processes them and puts them in the replyq of
28  *          the peer the request came from
29  * serverwr monitors its reply and sends replies
30  *
31  * In addition to the main thread, we have:
32  * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
33  * If TLS peers are configured, there will initially be 2 * #peers TLS threads
34  * For each TLS peer connecting to us there will be 2 more TLS threads
35  *       This is only for connected peers
36  * Example: With 3 UDP peers and 30 TLS peers, there will be a max of
37  *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38  */
39
40 /* Bugs:
41  * May segfault when dtls connections go down? More testing needed
42  * Remove expired stuff from clients request list?
43  * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
44  * Useful for TCP accounting? Now we require separate server config for alt port
45  */
46
47 #include <signal.h>
48 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <netdb.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <limits.h>
54 #ifdef SYS_SOLARIS9
55 #include <fcntl.h>
56 #endif
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <ctype.h>
60 #include <sys/wait.h>
61 #include <arpa/inet.h>
62 #include <regex.h>
63 #include <libgen.h>
64 #include <pthread.h>
65 #include <openssl/ssl.h>
66 #include <openssl/rand.h>
67 #include <openssl/err.h>
68 #include <openssl/md5.h>
69 #include "debug.h"
70 #include "list.h"
71 #include "hash.h"
72 #include "util.h"
73 #include "hostport.h"
74 #include "radsecproxy.h"
75 #include "udp.h"
76 #include "tcp.h"
77 #include "tls.h"
78 #include "dtls.h"
79
80 static struct options options;
81 static struct list *clconfs, *srvconfs;
82 static struct list *realms;
83 static struct hash *rewriteconfs;
84
85 static pthread_mutex_t *ssl_locks = NULL;
86 static long *ssl_lock_count;
87 extern int optind;
88 extern char *optarg;
89 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
90
91 /* minimum required declarations to avoid reordering code */
92 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
93 int dynamicconfig(struct server *server);
94 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
95 void freerealm(struct realm *realm);
96 void freeclsrvconf(struct clsrvconf *conf);
97 void freerq(struct request *rq);
98 void freerqoutdata(struct rqout *rqout);
99 void rmclientrq(struct request *rq, uint8_t id);
100
101 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
102
103 uint8_t protoname2int(const char *name) {
104     uint8_t i;
105
106     for (i = 0; i < RAD_PROTOCOUNT; i++)
107         if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
108             return i;
109     return 255;
110 }
111
112 /* callbacks for making OpenSSL thread safe */
113 unsigned long ssl_thread_id() {
114     return (unsigned long)pthread_self();
115 }
116
117 void ssl_locking_callback(int mode, int type, const char *file, int line) {
118     if (mode & CRYPTO_LOCK) {
119         pthread_mutex_lock(&ssl_locks[type]);
120         ssl_lock_count[type]++;
121     } else
122         pthread_mutex_unlock(&ssl_locks[type]);
123 }
124
125 /* returns 1 if the len first bits are equal, else 0 */
126 int prefixmatch(void *a1, void *a2, uint8_t len) {
127     static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
128     uint8_t r, l = len / 8;
129     if (l && memcmp(a1, a2, l))
130         return 0;
131     r = len % 8;
132     if (!r)
133         return 1;
134     return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
135 }
136
137 /* returns next config with matching address, or NULL */
138 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
139     struct list_node *entry;
140     struct clsrvconf *conf;
141
142     for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
143         conf = (struct clsrvconf *)entry->data;
144         if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
145             if (cur)
146                 *cur = entry;
147             return conf;
148         }
149     }
150     return NULL;
151 }
152
153 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
154     return find_conf(type, addr, clconfs, cur, 0);
155 }
156
157 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
158     return find_conf(type, addr, srvconfs, cur, 1);
159 }
160
161 /* returns next config of given type, or NULL */
162 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
163     struct list_node *entry;
164     struct clsrvconf *conf;
165
166     for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
167         conf = (struct clsrvconf *)entry->data;
168         if (conf->type == type) {
169             if (cur)
170                 *cur = entry;
171             return conf;
172         }
173     }
174     return NULL;
175 }
176
177 struct gqueue *newqueue() {
178     struct gqueue *q;
179
180     q = malloc(sizeof(struct gqueue));
181     if (!q)
182         debugx(1, DBG_ERR, "malloc failed");
183     q->entries = list_create();
184     if (!q->entries)
185         debugx(1, DBG_ERR, "malloc failed");
186     pthread_mutex_init(&q->mutex, NULL);
187     pthread_cond_init(&q->cond, NULL);
188     return q;
189 }
190
191 void removequeue(struct gqueue *q) {
192     struct list_node *entry;
193
194     if (!q)
195         return;
196     pthread_mutex_lock(&q->mutex);
197     for (entry = list_first(q->entries); entry; entry = list_next(entry))
198         freerq((struct request *)entry);
199     list_destroy(q->entries);
200     pthread_cond_destroy(&q->cond);
201     pthread_mutex_unlock(&q->mutex);
202     pthread_mutex_destroy(&q->mutex);
203     free(q);
204 }
205
206 void freebios(struct gqueue *q) {
207     BIO *bio;
208
209     pthread_mutex_lock(&q->mutex);
210     while ((bio = (BIO *)list_shift(q->entries)))
211         BIO_free(bio);
212     pthread_mutex_unlock(&q->mutex);
213     removequeue(q);
214 }
215
216 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
217     struct client *new = malloc(sizeof(struct client));
218
219     if (!new) {
220         debug(DBG_ERR, "malloc failed");
221         return NULL;
222     }
223
224     if (lock)
225         pthread_mutex_lock(conf->lock);
226     if (!conf->clients) {
227         conf->clients = list_create();
228         if (!conf->clients) {
229             if (lock)
230                 pthread_mutex_unlock(conf->lock);
231             debug(DBG_ERR, "malloc failed");
232             return NULL;
233         }
234     }
235
236     memset(new, 0, sizeof(struct client));
237     new->conf = conf;
238     if (conf->pdef->addclient)
239         conf->pdef->addclient(new);
240     else
241         new->replyq = newqueue();
242     list_push(conf->clients, new);
243     if (lock)
244         pthread_mutex_unlock(conf->lock);
245     return new;
246 }
247
248 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
249     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
250
251     if (wantlock)
252         pthread_mutex_lock(&lock);
253     else
254         pthread_mutex_unlock(&lock);
255 }
256
257 void removeclientrqs(struct client *client) {
258     struct request *rq;
259     struct rqout *rqout;
260     int i;
261
262     removeclientrqs_sendrq_freeserver_lock(1);
263     for (i = 0; i < MAX_REQUESTS; i++) {
264         rq = client->rqs[i];
265         if (!rq)
266             continue;
267         if (rq->to) {
268             rqout = rq->to->requests + rq->newid;
269             pthread_mutex_lock(rqout->lock);
270             if (rqout->rq == rq) /* still pointing to our request */
271                 freerqoutdata(rqout);
272             pthread_mutex_unlock(rqout->lock);
273         }
274         freerq(rq);
275     }
276     removeclientrqs_sendrq_freeserver_lock(0);
277 }
278
279 void removelockedclient(struct client *client) {
280     struct clsrvconf *conf;
281
282     conf = client->conf;
283     if (conf->clients) {
284         removeclientrqs(client);
285         removequeue(client->replyq);
286         list_removedata(conf->clients, client);
287         free(client->addr);
288         free(client);
289     }
290 }
291
292 void removeclient(struct client *client) {
293     struct clsrvconf *conf;
294
295     if (!client)
296         return;
297
298     conf = client->conf;
299     pthread_mutex_lock(conf->lock);
300     removelockedclient(client);
301     pthread_mutex_unlock(conf->lock);
302 }
303
304 void freeserver(struct server *server, uint8_t destroymutex) {
305     struct rqout *rqout, *end;
306
307     if (!server)
308         return;
309
310     removeclientrqs_sendrq_freeserver_lock(1);
311     if (server->requests) {
312         rqout = server->requests;
313         for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
314             if (rqout->rq)
315                 rqout->rq->to = NULL;
316             freerqoutdata(rqout);
317             pthread_mutex_destroy(rqout->lock);
318             free(rqout->lock);
319         }
320         free(server->requests);
321     }
322     if (server->rbios)
323         freebios(server->rbios);
324     free(server->dynamiclookuparg);
325     if (server->ssl)
326         SSL_free(server->ssl);
327     if (destroymutex) {
328         pthread_mutex_destroy(&server->lock);
329         pthread_cond_destroy(&server->newrq_cond);
330         pthread_mutex_destroy(&server->newrq_mutex);
331     }
332     removeclientrqs_sendrq_freeserver_lock(0);
333     free(server);
334 }
335
336 int addserver(struct clsrvconf *conf) {
337     int i;
338
339     if (conf->servers) {
340         debug(DBG_ERR, "addserver: currently works with just one server per conf");
341         return 0;
342     }
343     conf->servers = malloc(sizeof(struct server));
344     if (!conf->servers) {
345         debug(DBG_ERR, "malloc failed");
346         return 0;
347     }
348     memset(conf->servers, 0, sizeof(struct server));
349     conf->servers->conf = conf;
350
351 #ifdef RADPROT_DTLS
352     if (conf->type == RAD_DTLS)
353         conf->servers->rbios = newqueue();
354 #endif
355     conf->pdef->setsrcres();
356
357     conf->servers->sock = -1;
358     if (conf->pdef->addserverextra)
359         conf->pdef->addserverextra(conf);
360
361     conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
362     if (!conf->servers->requests) {
363         debug(DBG_ERR, "malloc failed");
364         goto errexit;
365     }
366     for (i = 0; i < MAX_REQUESTS; i++) {
367         conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
368         if (!conf->servers->requests[i].lock) {
369             debug(DBG_ERR, "malloc failed");
370             goto errexit;
371         }
372         if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
373             debug(DBG_ERR, "mutex init failed");
374             free(conf->servers->requests[i].lock);
375             conf->servers->requests[i].lock = NULL;
376             goto errexit;
377         }
378     }
379     if (pthread_mutex_init(&conf->servers->lock, NULL)) {
380         debug(DBG_ERR, "mutex init failed");
381         goto errexit;
382     }
383     conf->servers->newrq = 0;
384     if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
385         debug(DBG_ERR, "mutex init failed");
386         pthread_mutex_destroy(&conf->servers->lock);
387         goto errexit;
388     }
389     if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
390         debug(DBG_ERR, "mutex init failed");
391         pthread_mutex_destroy(&conf->servers->newrq_mutex);
392         pthread_mutex_destroy(&conf->servers->lock);
393         goto errexit;
394     }
395
396     return 1;
397
398 errexit:
399     freeserver(conf->servers, 0);
400     conf->servers = NULL;
401     return 0;
402 }
403
404 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
405     while (length > 1) {
406         if (ATTRTYPE(attrs) == type)
407             return attrs;
408         length -= ATTRLEN(attrs);
409         attrs += ATTRLEN(attrs);
410     }
411     return NULL;
412 }
413
414 struct request *newrqref(struct request *rq) {
415     if (rq)
416         rq->refcount++;
417     return rq;
418 }
419
420 void freerq(struct request *rq) {
421     if (!rq)
422         return;
423     debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
424     if (--rq->refcount)
425         return;
426     if (rq->origusername)
427         free(rq->origusername);
428     if (rq->buf)
429         free(rq->buf);
430     if (rq->replybuf)
431         free(rq->replybuf);
432     if (rq->msg)
433         radmsg_free(rq->msg);
434     free(rq);
435 }
436
437 void freerqoutdata(struct rqout *rqout) {
438     if (!rqout)
439         return;
440     if (rqout->rq) {
441         if (rqout->rq->buf) {
442             free(rqout->rq->buf);
443             rqout->rq->buf = NULL;
444         }
445         freerq(rqout->rq);
446         rqout->rq = NULL;
447     }
448     rqout->tries = 0;
449     memset(&rqout->expiry, 0, sizeof(struct timeval));
450 }
451
452 void sendrq(struct request *rq) {
453     int i, start;
454     struct server *to;
455
456     removeclientrqs_sendrq_freeserver_lock(1);
457     to = rq->to;
458     if (!to)
459         goto errexit;
460
461     start = to->conf->statusserver ? 1 : 0;
462     pthread_mutex_lock(&to->newrq_mutex);
463     if (start && rq->msg->code == RAD_Status_Server) {
464         pthread_mutex_lock(to->requests[0].lock);
465         if (to->requests[0].rq) {
466             pthread_mutex_unlock(to->requests[0].lock);
467             debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
468             goto errexit;
469         }
470         i = 0;
471     } else {
472         if (!to->nextid)
473             to->nextid = start;
474         /* might simplify if only try nextid, might be ok */
475         for (i = to->nextid; i < MAX_REQUESTS; i++) {
476             if (!to->requests[i].rq) {
477                 pthread_mutex_lock(to->requests[i].lock);
478                 if (!to->requests[i].rq)
479                     break;
480                 pthread_mutex_unlock(to->requests[i].lock);
481             }
482         }
483         if (i == MAX_REQUESTS) {
484             for (i = start; i < to->nextid; i++) {
485                 if (!to->requests[i].rq) {
486                     pthread_mutex_lock(to->requests[i].lock);
487                     if (!to->requests[i].rq)
488                         break;
489                     pthread_mutex_unlock(to->requests[i].lock);
490                 }
491             }
492             if (i == to->nextid) {
493                 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
494                 goto errexit;
495             }
496         }
497     }
498     rq->newid = (uint8_t)i;
499     rq->msg->id = (uint8_t)i;
500     rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
501     if (!rq->buf) {
502         pthread_mutex_unlock(to->requests[i].lock);
503         debug(DBG_ERR, "sendrq: radmsg2buf failed");
504         goto errexit;
505     }
506
507     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
508     to->requests[i].rq = rq;
509     pthread_mutex_unlock(to->requests[i].lock);
510     if (i >= start) /* i is not reserved for statusserver */
511         to->nextid = i + 1;
512
513     if (!to->newrq) {
514         to->newrq = 1;
515         debug(DBG_DBG, "sendrq: signalling client writer");
516         pthread_cond_signal(&to->newrq_cond);
517     }
518
519     pthread_mutex_unlock(&to->newrq_mutex);
520     removeclientrqs_sendrq_freeserver_lock(0);
521     return;
522
523 errexit:
524     if (rq->from)
525         rmclientrq(rq, rq->msg->id);
526     freerq(rq);
527     pthread_mutex_unlock(&to->newrq_mutex);
528     removeclientrqs_sendrq_freeserver_lock(0);
529 }
530
531 void sendreply(struct request *rq) {
532     uint8_t first;
533     struct client *to = rq->from;
534
535     if (!rq->replybuf)
536         rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
537     radmsg_free(rq->msg);
538     rq->msg = NULL;
539     if (!rq->replybuf) {
540         freerq(rq);
541         debug(DBG_ERR, "sendreply: radmsg2buf failed");
542         return;
543     }
544
545     pthread_mutex_lock(&to->replyq->mutex);
546     first = list_first(to->replyq->entries) == NULL;
547
548     if (!list_push(to->replyq->entries, rq)) {
549         pthread_mutex_unlock(&to->replyq->mutex);
550         freerq(rq);
551         debug(DBG_ERR, "sendreply: malloc failed");
552         return;
553     }
554
555     if (first) {
556         debug(DBG_DBG, "signalling server writer");
557         pthread_cond_signal(&to->replyq->cond);
558     }
559     pthread_mutex_unlock(&to->replyq->mutex);
560 }
561
562 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
563     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
564     static unsigned char first = 1;
565     static EVP_MD_CTX mdctx;
566     unsigned char hash[EVP_MAX_MD_SIZE], *input;
567     unsigned int md_len;
568     uint8_t i, offset = 0, out[128];
569
570     pthread_mutex_lock(&lock);
571     if (first) {
572         EVP_MD_CTX_init(&mdctx);
573         first = 0;
574     }
575
576     input = auth;
577     for (;;) {
578         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
579             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
580             !EVP_DigestUpdate(&mdctx, input, 16) ||
581             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
582             md_len != 16) {
583             pthread_mutex_unlock(&lock);
584             return 0;
585         }
586         for (i = 0; i < 16; i++)
587             out[offset + i] = hash[i] ^ in[offset + i];
588         if (encrypt_flag)
589             input = out + offset;
590         else
591             input = in + offset;
592         offset += 16;
593         if (offset == len)
594             break;
595     }
596     memcpy(in, out, len);
597     pthread_mutex_unlock(&lock);
598     return 1;
599 }
600
601 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
602     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
603     static unsigned char first = 1;
604     static EVP_MD_CTX mdctx;
605     unsigned char hash[EVP_MAX_MD_SIZE];
606     unsigned int md_len;
607     uint8_t i, offset;
608
609     pthread_mutex_lock(&lock);
610     if (first) {
611         EVP_MD_CTX_init(&mdctx);
612         first = 0;
613     }
614
615 #if 0
616     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
617     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
618     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
619 #endif
620
621     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
622         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
623         !EVP_DigestUpdate(&mdctx, auth, 16) ||
624         !EVP_DigestUpdate(&mdctx, salt, 2) ||
625         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
626         pthread_mutex_unlock(&lock);
627         return 0;
628     }
629
630 #if 0
631     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
632 #endif
633
634     for (i = 0; i < 16; i++)
635         text[i] ^= hash[i];
636
637     for (offset = 16; offset < len; offset += 16) {
638 #if 0
639         printf("text + offset - 16 c(%d): ", offset / 16);
640         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
641 #endif
642         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
643             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
644             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
645             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
646             md_len != 16) {
647             pthread_mutex_unlock(&lock);
648             return 0;
649         }
650 #if 0
651         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
652 #endif
653
654         for (i = 0; i < 16; i++)
655             text[offset + i] ^= hash[i];
656     }
657
658 #if 0
659     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
660 #endif
661
662     pthread_mutex_unlock(&lock);
663     return 1;
664 }
665
666 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
667     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
668     static unsigned char first = 1;
669     static EVP_MD_CTX mdctx;
670     unsigned char hash[EVP_MAX_MD_SIZE];
671     unsigned int md_len;
672     uint8_t i, offset;
673     char plain[255];
674
675     pthread_mutex_lock(&lock);
676     if (first) {
677         EVP_MD_CTX_init(&mdctx);
678         first = 0;
679     }
680
681 #if 0
682     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
683     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
684     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
685 #endif
686
687     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
688         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
689         !EVP_DigestUpdate(&mdctx, auth, 16) ||
690         !EVP_DigestUpdate(&mdctx, salt, 2) ||
691         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
692         pthread_mutex_unlock(&lock);
693         return 0;
694     }
695
696 #if 0
697     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
698 #endif
699
700     for (i = 0; i < 16; i++)
701         plain[i] = text[i] ^ hash[i];
702
703     for (offset = 16; offset < len; offset += 16) {
704 #if 0
705         printf("text + offset - 16 c(%d): ", offset / 16);
706         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
707 #endif
708         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
709             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
710             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
711             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
712             md_len != 16) {
713             pthread_mutex_unlock(&lock);
714             return 0;
715         }
716 #if 0
717         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
718 #endif
719
720         for (i = 0; i < 16; i++)
721             plain[offset + i] = text[offset + i] ^ hash[i];
722     }
723
724     memcpy(text, plain, len);
725 #if 0
726     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
727 #endif
728
729     pthread_mutex_unlock(&lock);
730     return 1;
731 }
732
733 struct realm *newrealmref(struct realm *r) {
734     if (r)
735         r->refcount++;
736     return r;
737 }
738
739 /* returns with lock on realm */
740 struct realm *id2realm(struct list *realmlist, char *id) {
741     struct list_node *entry;
742     struct realm *realm, *subrealm;
743
744     /* need to do locking for subrealms and check subrealm timers */
745     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
746         realm = (struct realm *)entry->data;
747         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
748             pthread_mutex_lock(&realm->mutex);
749             if (realm->subrealms) {
750                 subrealm = id2realm(realm->subrealms, id);
751                 if (subrealm) {
752                     pthread_mutex_unlock(&realm->mutex);
753                     return subrealm;
754                 }
755             }
756             return newrealmref(realm);
757         }
758     }
759     return NULL;
760 }
761
762 int hasdynamicserver(struct list *srvconfs) {
763     struct list_node *entry;
764
765     for (entry = list_first(srvconfs); entry; entry = list_next(entry))
766         if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
767             return 1;
768     return 0;
769 }
770
771 /* helper function, only used by removeserversubrealms() */
772 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
773     struct list_node *entry, *entry2;
774     struct realm *realm;
775
776     for (entry = list_first(realmlist); entry;) {
777         realm = newrealmref((struct realm *)entry->data);
778         pthread_mutex_lock(&realm->mutex);
779         entry = list_next(entry);
780
781         if (realm->srvconfs) {
782             for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
783                 if (entry2->data == srv)
784                     freerealm(realm);
785             list_removedata(realm->srvconfs, srv);
786         }
787         if (realm->accsrvconfs) {
788             for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
789                 if (entry2->data == srv)
790                     freerealm(realm);
791             list_removedata(realm->accsrvconfs, srv);
792         }
793
794         /* remove subrealm if no dynamic servers left */
795         if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
796             while (list_shift(realm->srvconfs))
797                 freerealm(realm);
798             list_destroy(realm->srvconfs);
799             realm->srvconfs = NULL;
800             while (list_shift(realm->accsrvconfs))
801                 freerealm(realm);
802             list_destroy(realm->accsrvconfs);
803             realm->accsrvconfs = NULL;
804             list_removedata(realmlist, realm);
805         }
806         pthread_mutex_unlock(&realm->mutex);
807         freerealm(realm);
808     }
809 }
810
811 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
812     struct list_node *entry;
813     struct realm *realm;
814
815     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
816         realm = (struct realm *)entry->data;
817         pthread_mutex_lock(&realm->mutex);
818         if (realm->subrealms) {
819             _internal_removeserversubrealms(realm->subrealms, srv);
820             if (!list_first(realm->subrealms)) {
821                 list_destroy(realm->subrealms);
822                 realm->subrealms = NULL;
823             }
824         }
825         pthread_mutex_unlock(&realm->mutex);
826     }
827 }
828
829 int attrvalidate(unsigned char *attrs, int length) {
830     while (length > 1) {
831         if (ATTRLEN(attrs) < 2) {
832             debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
833             return 0;
834         }
835         length -= ATTRLEN(attrs);
836         if (length < 0) {
837             debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
838             return 0;
839         }
840         attrs += ATTRLEN(attrs);
841     }
842     if (length)
843         debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
844     return 1;
845 }
846
847 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
848     if (len < 16 || len > 128 || len % 16) {
849         debug(DBG_WARN, "pwdrecrypt: invalid password length");
850         return 0;
851     }
852
853     if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
854         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
855         return 0;
856     }
857 #ifdef DEBUG
858     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
859 #endif
860     if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
861         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
862         return 0;
863     }
864     return 1;
865 }
866
867 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
868     if (len < 18)
869         return 0;
870     if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
871         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
872         return 0;
873     }
874     if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
875         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
876         return 0;
877     }
878     return 1;
879 }
880
881 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
882            char *oldsecret, char *newsecret) {
883     unsigned char *attr;
884
885     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
886         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
887         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
888             return 0;
889     }
890     return 1;
891 }
892
893 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
894     if (!attrs)
895         return 0;
896
897     for (; attrs[0]; attrs += 2)
898         if (attrs[0] == vendor && attrs[1] == subattr)
899             return 1;
900     return 0;
901 }
902
903 /* returns 1 if entire element is to be removed, else 0 */
904 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
905     uint8_t alen, sublen;
906     uint32_t vendor;
907     uint8_t *subattrs;
908
909     if (!removevendorattrs)
910         return 0;
911
912     memcpy(&vendor, attr->v, 4);
913     vendor = ntohl(vendor);
914     while (*removevendorattrs && *removevendorattrs != vendor)
915         removevendorattrs += 2;
916     if (!*removevendorattrs)
917         return 0;
918
919     if (findvendorsubattr(removevendorattrs, vendor, 256))
920         return 1; /* remove entire vendor attribute */
921
922     sublen = attr->l - 4;
923     subattrs = attr->v + 4;
924
925     if (!attrvalidate(subattrs, sublen)) {
926         debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
927         return 0;
928     }
929
930     while (sublen > 1) {
931         alen = ATTRLEN(subattrs);
932         sublen -= alen;
933         if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
934             memmove(subattrs, subattrs + alen, sublen);
935             attr->l -= alen;
936         } else
937             subattrs += alen;
938     }
939     return 0;
940 }
941
942 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
943     struct list_node *n, *p;
944     struct tlv *attr;
945
946     p = NULL;
947     n = list_first(msg->attrs);
948     while (n) {
949         attr = (struct tlv *)n->data;
950         if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
951             (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
952             list_removedata(msg->attrs, attr);
953             freetlv(attr);
954             n = p ? list_next(p) : list_first(msg->attrs);
955         } else {
956             p = n;
957             n = list_next(n);
958         }
959     }
960 }
961
962 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
963     struct list_node *n;
964     struct tlv *a;
965
966     for (n = list_first(addattrs); n; n = list_next(n)) {
967         a = copytlv((struct tlv *)n->data);
968         if (!a)
969             return 0;
970         if (!radmsg_add(msg, a)) {
971             freetlv(a);
972             return 0;
973         }
974     }
975     return 1;
976 }
977
978 int resizeattr(struct tlv *attr, uint8_t newlen) {
979     uint8_t *newv;
980
981     if (newlen != attr->l) {
982         newv = realloc(attr->v, newlen);
983         if (!newv)
984             return 0;
985         attr->v = newv;
986         attr->l = newlen;
987     }
988     return 1;
989 }
990
991 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
992     size_t nmatch = 10, reslen = 0, start = 0;
993     regmatch_t pmatch[10], *pfield;
994     int i;
995     char *in, *out;
996
997     in = stringcopy((char *)attr->v, attr->l);
998     if (!in)
999         return 0;
1000
1001     if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1002         free(in);
1003         return 1;
1004     }
1005
1006     out = modattr->replacement;
1007
1008     for (i = start; out[i]; i++) {
1009         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1010             pfield = &pmatch[out[i + 1] - '0'];
1011             if (pfield->rm_so >= 0) {
1012                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1013                 start = i + 2;
1014             }
1015             i++;
1016         }
1017     }
1018     reslen += i - start;
1019     if (reslen > 253) {
1020         debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1021         free(in);
1022         return 0;
1023     }
1024
1025     if (!resizeattr(attr, reslen)) {
1026         free(in);
1027         return 0;
1028     }
1029
1030     start = 0;
1031     reslen = 0;
1032     for (i = start; out[i]; i++) {
1033         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1034             pfield = &pmatch[out[i + 1] - '0'];
1035             if (pfield->rm_so >= 0) {
1036                 memcpy(attr->v + reslen, out + start, i - start);
1037                 reslen += i - start;
1038                 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1039                 reslen += pfield->rm_eo - pfield->rm_so;
1040                 start = i + 2;
1041             }
1042             i++;
1043         }
1044     }
1045
1046     memcpy(attr->v + reslen, out + start, i - start);
1047     return 1;
1048 }
1049
1050 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1051     struct list_node *n, *m;
1052
1053     for (n = list_first(msg->attrs); n; n = list_next(n))
1054         for (m = list_first(modattrs); m; m = list_next(m))
1055             if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1056                 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1057                 return 0;
1058     return 1;
1059 }
1060
1061 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1062     int rv = 1;                 /* Success.  */
1063
1064     if (rewrite) {
1065         if (rewrite->removeattrs || rewrite->removevendorattrs)
1066             dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1067         if (rewrite->modattrs)
1068             if (!dorewritemod(msg, rewrite->modattrs))
1069                 rv = 0;
1070         if (rewrite->addattrs)
1071             if (!dorewriteadd(msg, rewrite->addattrs))
1072                 rv = 0;
1073     }
1074     return rv;
1075 }
1076
1077 int rewriteusername(struct request *rq, struct tlv *attr) {
1078     char *orig = (char *)tlv2str(attr);
1079     if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1080         free(orig);
1081         return 0;
1082     }
1083     if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1084         rq->origusername = (char *)orig;
1085     else
1086         free(orig);
1087     return 1;
1088 }
1089
1090 /** Create vendor specific tlv with ATTR.  ATTR is consumed (freed) if
1091  * all is well with the new tlv, i.e. if the function returns
1092  * !NULL.  */
1093 static struct tlv *
1094 makevendortlv(uint32_t vendor, struct tlv *attr)
1095 {
1096     struct tlv *newtlv = NULL;
1097     uint8_t l, *v;
1098
1099     if (!attr)
1100         return NULL;
1101     l = attr->l + 6;
1102     v = malloc(l);
1103     if (v) {
1104         vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1105         memcpy(v, &vendor, 4);
1106         tlv2buf(v + 4, attr);
1107         v[5] += 2; /* Vendor length increased for type and length fields. */
1108         newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1109         if (newtlv == NULL)
1110             free(v);
1111         else
1112             freetlv(attr);
1113     }
1114     return newtlv;
1115 }
1116
1117 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG.  ATTR
1118  * is consumed.  */
1119 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1120     struct tlv *vattr;
1121
1122     vattr = makevendortlv(vendor, attr);
1123     if (!vattr) {
1124         freetlv(attr);
1125         return 0;
1126     }
1127     if (!radmsg_add(msg, vattr)) {
1128         freetlv(vattr);
1129         return 0;
1130     }
1131     return 1;
1132 }
1133
1134 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1135     uint8_t ttl[4];
1136     struct tlv *attr;
1137
1138     memset(ttl, 0, 4);
1139     ttl[3] = addttl;
1140
1141     if (attrtype[1] == 256) { /* not vendor */
1142         attr = maketlv(attrtype[0], 4, ttl);
1143         if (attr && !radmsg_add(msg, attr))
1144             freetlv(attr);
1145     } else {
1146         attr = maketlv(attrtype[1], 4, ttl);
1147         if (attr)
1148             addvendorattr(msg, attrtype[0], attr);
1149     }
1150 }
1151
1152 int decttl(uint8_t l, uint8_t *v) {
1153     int i;
1154
1155     i = l - 1;
1156     if (v[i]) {
1157         if (--v[i--])
1158             return 1;
1159         while (i >= 0 && !v[i])
1160             i--;
1161         return i >= 0;
1162     }
1163     for (i--; i >= 0 && !v[i]; i--);
1164     if (i < 0)
1165         return 0;
1166     v[i]--;
1167     while (++i < l)
1168         v[i] = 255;
1169     return 1;
1170 }
1171
1172 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1173 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1174     uint8_t alen, *subattrs;
1175     struct tlv *attr;
1176     struct list_node *node;
1177     uint32_t vendor;
1178     int sublen;
1179
1180     if (attrtype[1] == 256) { /* not vendor */
1181         attr = radmsg_gettype(msg, attrtype[0]);
1182         if (attr)
1183             return decttl(attr->l, attr->v);
1184     } else
1185         for (node = list_first(msg->attrs); node; node = list_next(node)) {
1186             attr = (struct tlv *)node->data;
1187             if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1188                 continue;
1189             memcpy(&vendor, attr->v, 4);
1190             if (ntohl(vendor) != attrtype[0])
1191                 continue;
1192             sublen = attr->l - 4;
1193             subattrs = attr->v + 4;
1194             if (!attrvalidate(subattrs, sublen))
1195                 continue;
1196             while (sublen > 1) {
1197                 if (ATTRTYPE(subattrs) == attrtype[1])
1198                     return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1199                 alen = ATTRLEN(subattrs);
1200                 sublen -= alen;
1201                 subattrs += alen;
1202             }
1203         }
1204     return -1;
1205 }
1206
1207 const char *radmsgtype2string(uint8_t code) {
1208     static const char *rad_msg_names[] = {
1209         "", "Access-Request", "Access-Accept", "Access-Reject",
1210         "Accounting-Request", "Accounting-Response", "", "",
1211         "", "", "", "Access-Challenge",
1212         "Status-Server", "Status-Client"
1213     };
1214     return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1215 }
1216
1217 void char2hex(char *h, unsigned char c) {
1218     static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1219                                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1220     h[0] = hexdigits[c / 16];
1221     h[1] = hexdigits[c % 16];
1222     return;
1223 }
1224
1225 uint8_t *radattr2ascii(struct tlv *attr) {
1226     int i, l;
1227     uint8_t *a, *d;
1228
1229     if (!attr)
1230         return NULL;
1231
1232     l = attr->l;
1233     for (i = 0; i < attr->l; i++)
1234         if (attr->v[i] < 32 || attr->v[i] > 126)
1235             l += 2;
1236     if (l == attr->l)
1237         return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1238
1239     a = malloc(l + 1);
1240     if (!a)
1241         return NULL;
1242
1243     d = a;
1244     for (i = 0; i < attr->l; i++)
1245         if (attr->v[i] < 32 || attr->v[i] > 126) {
1246             *d++ = '%';
1247             char2hex((char *)d, attr->v[i]);
1248             d += 2;
1249         } else
1250             *d++ = attr->v[i];
1251     *d = '\0';
1252     return a;
1253 }
1254
1255 void acclog(struct radmsg *msg, struct client *from) {
1256     struct tlv *attr;
1257     uint8_t *username;
1258
1259     attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1260     if (!attr) {
1261         debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1262         return;
1263     }
1264     username = radattr2ascii(attr);
1265     if (username) {
1266         debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1267
1268         free(username);
1269     }
1270 }
1271
1272 void respond(struct request *rq, uint8_t code, char *message) {
1273     struct radmsg *msg;
1274     struct tlv *attr;
1275
1276     msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1277     if (!msg) {
1278         debug(DBG_ERR, "respond: malloc failed");
1279         return;
1280     }
1281     if (message && *message) {
1282         attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1283         if (!attr || !radmsg_add(msg, attr)) {
1284             freetlv(attr);
1285             radmsg_free(msg);
1286             debug(DBG_ERR, "respond: malloc failed");
1287             return;
1288         }
1289     }
1290
1291     radmsg_free(rq->msg);
1292     rq->msg = msg;
1293     debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1294     sendreply(newrqref(rq));
1295 }
1296
1297 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1298     struct list_node *entry;
1299     struct clsrvconf *server, *best = NULL, *first = NULL;
1300
1301     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1302         server = (struct clsrvconf *)entry->data;
1303         if (!server->servers)
1304             return server;
1305         if (!first)
1306             first = server;
1307         if (!server->servers->connectionok && !server->servers->dynstartup)
1308             continue;
1309         if (!server->servers->lostrqs)
1310             return server;
1311         if (!best) {
1312             best = server;
1313             continue;
1314         }
1315         if (server->servers->lostrqs < best->servers->lostrqs)
1316             best = server;
1317     }
1318     return best ? best : first;
1319 }
1320
1321 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1322 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1323     struct clsrvconf *srvconf;
1324     struct realm *subrealm;
1325     struct server *server = NULL;
1326     char *id = (char *)tlv2str(username);
1327
1328     if (!id)
1329         return NULL;
1330     /* returns with lock on realm */
1331     *realm = id2realm(realms, id);
1332     if (!*realm)
1333         goto exit;
1334     debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1335     srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1336     if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1337         subrealm = adddynamicrealmserver(*realm, id);
1338         if (subrealm) {
1339             pthread_mutex_lock(&subrealm->mutex);
1340             pthread_mutex_unlock(&(*realm)->mutex);
1341             freerealm(*realm);
1342             *realm = subrealm;
1343             srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1344         }
1345     }
1346     if (srvconf)
1347         server = srvconf->servers;
1348
1349 exit:
1350     free(id);
1351     return server;
1352 }
1353
1354
1355 struct request *newrequest() {
1356     struct request *rq;
1357
1358     rq = malloc(sizeof(struct request));
1359     if (!rq) {
1360         debug(DBG_ERR, "newrequest: malloc failed");
1361         return NULL;
1362     }
1363     memset(rq, 0, sizeof(struct request));
1364     rq->refcount = 1;
1365     gettimeofday(&rq->created, NULL);
1366     return rq;
1367 }
1368
1369 int addclientrq(struct request *rq) {
1370     struct request *r;
1371     struct timeval now;
1372
1373     r = rq->from->rqs[rq->rqid];
1374     if (r) {
1375         if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1376             gettimeofday(&now, NULL);
1377             if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1378                 if (r->replybuf) {
1379                     debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1380                     sendreply(newrqref(r));
1381                 } else
1382                     debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1383                 return 0;
1384             }
1385         }
1386         freerq(r);
1387     }
1388     rq->from->rqs[rq->rqid] = newrqref(rq);
1389     return 1;
1390 }
1391
1392 void rmclientrq(struct request *rq, uint8_t id) {
1393     struct request *r;
1394
1395     r = rq->from->rqs[id];
1396     if (r) {
1397         freerq(r);
1398         rq->from->rqs[id] = NULL;
1399     }
1400 }
1401
1402 /* returns 0 if validation/authentication fails, else 1 */
1403 int radsrv(struct request *rq) {
1404     struct radmsg *msg = NULL;
1405     struct tlv *attr;
1406     uint8_t *userascii = NULL;
1407     struct realm *realm = NULL;
1408     struct server *to = NULL;
1409     struct client *from = rq->from;
1410     int ttlres;
1411
1412     msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1413     free(rq->buf);
1414     rq->buf = NULL;
1415
1416     if (!msg) {
1417         debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1418         freerq(rq);
1419         return 0;
1420     }
1421
1422     rq->msg = msg;
1423     rq->rqid = msg->id;
1424     memcpy(rq->rqauth, msg->auth, 16);
1425
1426     debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1427     if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1428         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1429         goto exit;
1430     }
1431
1432     if (!addclientrq(rq))
1433         goto exit;
1434
1435     if (msg->code == RAD_Status_Server) {
1436         respond(rq, RAD_Access_Accept, NULL);
1437         goto exit;
1438     }
1439
1440     /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1441
1442     if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1443         goto rmclrqexit;
1444
1445     ttlres = checkttl(msg, options.ttlattrtype);
1446     if (!ttlres) {
1447         debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1448         goto exit;
1449     }
1450
1451     attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1452     if (!attr) {
1453         if (msg->code == RAD_Accounting_Request) {
1454             acclog(msg, from);
1455             respond(rq, RAD_Accounting_Response, NULL);
1456         } else
1457             debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1458         goto exit;
1459     }
1460
1461     if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1462         debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1463         goto rmclrqexit;
1464     }
1465
1466     userascii = radattr2ascii(attr);
1467     if (!userascii)
1468         goto rmclrqexit;
1469     debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1470
1471     /* will return with lock on the realm */
1472     to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1473     if (!realm) {
1474         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1475         goto exit;
1476     }
1477
1478     if (!to) {
1479         if (realm->message && msg->code == RAD_Access_Request) {
1480             debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1481             respond(rq, RAD_Access_Reject, realm->message);
1482         } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1483             acclog(msg, from);
1484             respond(rq, RAD_Accounting_Response, NULL);
1485         }
1486         goto exit;
1487     }
1488
1489     if ((to->conf->loopprevention == 1
1490          || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1491         && !strcmp(from->conf->name, to->conf->name)) {
1492         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1493               from->conf->name, addr2string(from->addr), to->conf->name);
1494         goto exit;
1495     }
1496
1497     if (msg->code == RAD_Accounting_Request)
1498         memset(msg->auth, 0, 16);
1499     else if (!RAND_bytes(msg->auth, 16)) {
1500         debug(DBG_WARN, "radsrv: failed to generate random auth");
1501         goto rmclrqexit;
1502     }
1503
1504 #ifdef DEBUG
1505     printfchars(NULL, "auth", "%02x ", auth, 16);
1506 #endif
1507
1508     attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1509     if (attr) {
1510         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1511         if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1512             goto rmclrqexit;
1513     }
1514
1515     attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1516     if (attr) {
1517         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1518         if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1519             goto rmclrqexit;
1520     }
1521
1522     if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1523         goto rmclrqexit;
1524
1525     if (ttlres == -1 && (options.addttl || to->conf->addttl))
1526         addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1527
1528     free(userascii);
1529     rq->to = to;
1530     sendrq(rq);
1531     pthread_mutex_unlock(&realm->mutex);
1532     freerealm(realm);
1533     return 1;
1534
1535 rmclrqexit:
1536     rmclientrq(rq, msg->id);
1537 exit:
1538     freerq(rq);
1539     free(userascii);
1540     if (realm) {
1541         pthread_mutex_unlock(&realm->mutex);
1542         freerealm(realm);
1543     }
1544     return 1;
1545 }
1546
1547 void replyh(struct server *server, unsigned char *buf) {
1548     struct client *from;
1549     struct rqout *rqout;
1550     int sublen, ttlres;
1551     unsigned char *subattrs;
1552     uint8_t *username, *stationid, *replymsg;
1553     struct radmsg *msg = NULL;
1554     struct tlv *attr;
1555     struct list_node *node;
1556
1557     server->connectionok = 1;
1558     server->lostrqs = 0;
1559
1560     rqout = server->requests + buf[1];
1561     pthread_mutex_lock(rqout->lock);
1562     if (!rqout->tries) {
1563         free(buf);
1564         buf = NULL;
1565         debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1566         goto errunlock;
1567     }
1568
1569     msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1570     free(buf);
1571     buf = NULL;
1572     if (!msg) {
1573         debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1574         goto errunlock;
1575     }
1576     if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1577         && msg->code != RAD_Accounting_Response) {
1578         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1579         goto errunlock;
1580     }
1581     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1582
1583     gettimeofday(&server->lastrcv, NULL);
1584
1585     if (rqout->rq->msg->code == RAD_Status_Server) {
1586         freerqoutdata(rqout);
1587         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1588         goto errunlock;
1589     }
1590
1591     gettimeofday(&server->lastreply, NULL);
1592     from = rqout->rq->from;
1593
1594     if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1595         debug(DBG_INFO, "replyh: rewritein failed");
1596         goto errunlock;
1597     }
1598
1599     ttlres = checkttl(msg, options.ttlattrtype);
1600     if (!ttlres) {
1601         debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1602         goto errunlock;
1603     }
1604
1605     /* MS MPPE */
1606     for (node = list_first(msg->attrs); node; node = list_next(node)) {
1607         attr = (struct tlv *)node->data;
1608         if (attr->t != RAD_Attr_Vendor_Specific)
1609             continue;
1610         if (attr->l <= 4)
1611             break;
1612         if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55)  /* 311 == MS */
1613             continue;
1614
1615         sublen = attr->l - 4;
1616         subattrs = attr->v + 4;
1617         if (!attrvalidate(subattrs, sublen) ||
1618             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1619                     rqout->rq, server->conf->secret, from->conf->secret) ||
1620             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1621                     rqout->rq, server->conf->secret, from->conf->secret))
1622             break;
1623     }
1624     if (node) {
1625         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1626         goto errunlock;
1627     }
1628
1629     if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1630         username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1631         if (username) {
1632             stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1633             replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1634             if (stationid) {
1635                 if (replymsg) {
1636                     debug(DBG_WARN, "%s for user %s stationid %s from %s (%s) to %s (%s)",
1637                           radmsgtype2string(msg->code), username, stationid, server->conf->name, replymsg, from->conf->name, addr2string(from->addr));
1638                     free(replymsg);
1639                 } else
1640                     debug(DBG_WARN, "%s for user %s stationid %s from %s to %s (%s)",
1641                           radmsgtype2string(msg->code), username, stationid, server->conf->name, from->conf->name, addr2string(from->addr));
1642                 free(stationid);
1643             } else {
1644                 if (replymsg) {
1645                     debug(DBG_WARN, "%s for user %s from %s (%s) to %s (%s)",
1646                           radmsgtype2string(msg->code), username, server->conf->name, replymsg, from->conf->name, addr2string(from->addr));
1647                     free(replymsg);
1648                 } else
1649                     debug(DBG_WARN, "%s for user %s from %s to %s (%s)",
1650                           radmsgtype2string(msg->code), username, server->conf->name, from->conf->name, addr2string(from->addr));
1651             }
1652             free(username);
1653         }
1654     }
1655
1656     msg->id = (char)rqout->rq->rqid;
1657     memcpy(msg->auth, rqout->rq->rqauth, 16);
1658
1659 #ifdef DEBUG
1660     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1661 #endif
1662
1663     if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1664         if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1665             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1666             goto errunlock;
1667         }
1668         memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1669     }
1670
1671     if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1672         debug(DBG_WARN, "replyh: rewriteout failed");
1673         goto errunlock;
1674     }
1675
1676     if (ttlres == -1 && (options.addttl || from->conf->addttl))
1677         addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1678
1679     debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1680           "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1681
1682     radmsg_free(rqout->rq->msg);
1683     rqout->rq->msg = msg;
1684     sendreply(newrqref(rqout->rq));
1685     freerqoutdata(rqout);
1686     pthread_mutex_unlock(rqout->lock);
1687     return;
1688
1689 errunlock:
1690     radmsg_free(msg);
1691     pthread_mutex_unlock(rqout->lock);
1692     return;
1693 }
1694
1695 struct request *createstatsrvrq() {
1696     struct request *rq;
1697     struct tlv *attr;
1698
1699     rq = newrequest();
1700     if (!rq)
1701         return NULL;
1702     rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1703     if (!rq->msg)
1704         goto exit;
1705     attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1706     if (!attr)
1707         goto exit;
1708     if (!radmsg_add(rq->msg, attr)) {
1709         freetlv(attr);
1710         goto exit;
1711     }
1712     return rq;
1713
1714 exit:
1715     freerq(rq);
1716     return NULL;
1717 }
1718
1719 /* code for removing state not finished */
1720 void *clientwr(void *arg) {
1721     struct server *server = (struct server *)arg;
1722     struct rqout *rqout = NULL;
1723     pthread_t clientrdth;
1724     int i, dynconffail = 0;
1725     time_t secs;
1726     uint8_t rnd;
1727     struct timeval now, laststatsrv;
1728     struct timespec timeout;
1729     struct request *statsrvrq;
1730     struct clsrvconf *conf;
1731
1732     conf = server->conf;
1733
1734     if (server->dynamiclookuparg && !dynamicconfig(server)) {
1735         dynconffail = 1;
1736         server->dynstartup = 0;
1737         sleep(900);
1738         goto errexit;
1739     }
1740
1741     if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1742         debug(DBG_WARN, "clientwr: resolve failed");
1743         server->dynstartup = 0;
1744         sleep(900);
1745         goto errexit;
1746     }
1747
1748     memset(&timeout, 0, sizeof(struct timespec));
1749
1750     if (conf->statusserver) {
1751         gettimeofday(&server->lastrcv, NULL);
1752         gettimeofday(&laststatsrv, NULL);
1753     }
1754
1755     if (conf->pdef->connecter) {
1756         if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1757             if (server->dynamiclookuparg) {
1758                 server->dynstartup = 0;
1759                 sleep(900);
1760             }
1761             goto errexit;
1762         }
1763         server->connectionok = 1;
1764         if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1765             debug(DBG_ERR, "clientwr: pthread_create failed");
1766             goto errexit;
1767         }
1768     } else
1769         server->connectionok = 1;
1770     server->dynstartup = 0;
1771
1772     for (;;) {
1773         pthread_mutex_lock(&server->newrq_mutex);
1774         if (!server->newrq) {
1775             gettimeofday(&now, NULL);
1776             /* random 0-7 seconds */
1777             RAND_bytes(&rnd, 1);
1778             rnd /= 32;
1779             if (conf->statusserver) {
1780                 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1781                 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1782                     secs = now.tv_sec;
1783                 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1784                     timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1785             } else {
1786                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1787                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1788             }
1789 #if 0
1790             if (timeout.tv_sec > now.tv_sec)
1791                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1792 #endif
1793             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1794             timeout.tv_sec = 0;
1795         }
1796         if (server->newrq) {
1797             debug(DBG_DBG, "clientwr: got new request");
1798             server->newrq = 0;
1799         }
1800 #if 0
1801         else
1802             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1803 #endif
1804         pthread_mutex_unlock(&server->newrq_mutex);
1805
1806         for (i = 0; i < MAX_REQUESTS; i++) {
1807             if (server->clientrdgone) {
1808                 pthread_join(clientrdth, NULL);
1809                 goto errexit;
1810             }
1811
1812             for (; i < MAX_REQUESTS; i++) {
1813                 rqout = server->requests + i;
1814                 if (rqout->rq) {
1815                     pthread_mutex_lock(rqout->lock);
1816                     if (rqout->rq)
1817                         break;
1818                     pthread_mutex_unlock(rqout->lock);
1819                 }
1820             }
1821
1822             if (i == MAX_REQUESTS)
1823                 break;
1824
1825             gettimeofday(&now, NULL);
1826             if (now.tv_sec < rqout->expiry.tv_sec) {
1827                 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1828                     timeout.tv_sec = rqout->expiry.tv_sec;
1829                 pthread_mutex_unlock(rqout->lock);
1830                 continue;
1831             }
1832
1833             if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1834                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1835                 if (conf->statusserver) {
1836                     if (*rqout->rq->buf == RAD_Status_Server) {
1837                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1838                         if (server->lostrqs < 255)
1839                             server->lostrqs++;
1840                     }
1841                 } else {
1842                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1843                     if (server->lostrqs < 255)
1844                         server->lostrqs++;
1845                 }
1846                 freerqoutdata(rqout);
1847                 pthread_mutex_unlock(rqout->lock);
1848                 continue;
1849             }
1850
1851             rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1852             if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1853                 timeout.tv_sec = rqout->expiry.tv_sec;
1854             rqout->tries++;
1855             conf->pdef->clientradput(server, rqout->rq->buf);
1856             pthread_mutex_unlock(rqout->lock);
1857         }
1858         if (conf->statusserver && server->connectionok) {
1859             secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1860             gettimeofday(&now, NULL);
1861             if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1862                 laststatsrv = now;
1863                 statsrvrq = createstatsrvrq();
1864                 if (statsrvrq) {
1865                     statsrvrq->to = server;
1866                     debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1867                     sendrq(statsrvrq);
1868                 }
1869             }
1870         }
1871     }
1872 errexit:
1873     conf->servers = NULL;
1874     if (server->dynamiclookuparg) {
1875         removeserversubrealms(realms, conf);
1876         if (dynconffail)
1877             free(conf);
1878         else
1879             freeclsrvconf(conf);
1880     }
1881     freeserver(server, 1);
1882     ERR_remove_state(0);
1883     return NULL;
1884 }
1885
1886 void createlistener(uint8_t type, char *arg) {
1887     pthread_t th;
1888     struct addrinfo *res;
1889     int s = -1, on = 1, *sp = NULL;
1890     struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1891
1892     if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1893         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1894
1895     for (res = hp->addrinfo; res; res = res->ai_next) {
1896         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1897         if (s < 0) {
1898             debug(DBG_WARN, "createlistener: socket failed");
1899             continue;
1900         }
1901         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1902
1903         disable_DF_bit(s, res);
1904
1905 #ifdef IPV6_V6ONLY
1906         if (res->ai_family == AF_INET6)
1907             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1908 #endif
1909         if (bind(s, res->ai_addr, res->ai_addrlen)) {
1910             debug(DBG_WARN, "createlistener: bind failed");
1911             close(s);
1912             s = -1;
1913             continue;
1914         }
1915
1916         sp = malloc(sizeof(int));
1917         if (!sp)
1918             debugx(1, DBG_ERR, "malloc failed");
1919         *sp = s;
1920         if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1921             debugx(1, DBG_ERR, "pthread_create failed");
1922         pthread_detach(th);
1923     }
1924     if (!sp)
1925         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1926
1927     debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1928     freehostport(hp);
1929 }
1930
1931 void createlisteners(uint8_t type) {
1932     int i;
1933     char **args;
1934
1935     args = protodefs[type]->getlistenerargs();
1936     if (args)
1937         for (i = 0; args[i]; i++)
1938             createlistener(type, args[i]);
1939     else
1940         createlistener(type, NULL);
1941 }
1942
1943 void sslinit() {
1944     int i;
1945     time_t t;
1946     pid_t pid;
1947
1948     ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1949     ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1950     for (i = 0; i < CRYPTO_num_locks(); i++) {
1951         ssl_lock_count[i] = 0;
1952         pthread_mutex_init(&ssl_locks[i], NULL);
1953     }
1954     CRYPTO_set_id_callback(ssl_thread_id);
1955     CRYPTO_set_locking_callback(ssl_locking_callback);
1956
1957     SSL_load_error_strings();
1958     SSL_library_init();
1959
1960     while (!RAND_status()) {
1961         t = time(NULL);
1962         pid = getpid();
1963         RAND_seed((unsigned char *)&t, sizeof(time_t));
1964         RAND_seed((unsigned char *)&pid, sizeof(pid));
1965     }
1966 }
1967
1968 struct list *addsrvconfs(char *value, char **names) {
1969     struct list *conflist;
1970     int n;
1971     struct list_node *entry;
1972     struct clsrvconf *conf = NULL;
1973
1974     if (!names || !*names)
1975         return NULL;
1976
1977     conflist = list_create();
1978     if (!conflist) {
1979         debug(DBG_ERR, "malloc failed");
1980         return NULL;
1981     }
1982
1983     for (n = 0; names[n]; n++) {
1984         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1985             conf = (struct clsrvconf *)entry->data;
1986             if (!strcasecmp(names[n], conf->name))
1987                 break;
1988         }
1989         if (!entry) {
1990             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
1991             list_destroy(conflist);
1992             return NULL;
1993         }
1994         if (!list_push(conflist, conf)) {
1995             debug(DBG_ERR, "malloc failed");
1996             list_destroy(conflist);
1997             return NULL;
1998         }
1999         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2000     }
2001     return conflist;
2002 }
2003
2004 void freerealm(struct realm *realm) {
2005     if (!realm)
2006         return;
2007     debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2008     if (--realm->refcount)
2009         return;
2010
2011     free(realm->name);
2012     free(realm->message);
2013     regfree(&realm->regex);
2014     pthread_mutex_destroy(&realm->mutex);
2015     /* if refcount == 0, all subrealms gone */
2016     list_destroy(realm->subrealms);
2017     /* if refcount == 0, all srvconfs gone */
2018     list_destroy(realm->srvconfs);
2019     /* if refcount == 0, all accsrvconfs gone */
2020     list_destroy(realm->accsrvconfs);
2021     freerealm(realm->parent);
2022     free(realm);
2023 }
2024
2025 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2026     int n;
2027     struct realm *realm;
2028     char *s, *regex = NULL;
2029
2030     if (*value == '/') {
2031         /* regexp, remove optional trailing / if present */
2032         if (value[strlen(value) - 1] == '/')
2033             value[strlen(value) - 1] = '\0';
2034     } else {
2035         /* not a regexp, let us make it one */
2036         if (*value == '*' && !value[1])
2037             regex = stringcopy(".*", 0);
2038         else {
2039             for (n = 0, s = value; *s;)
2040                 if (*s++ == '.')
2041                     n++;
2042             regex = malloc(strlen(value) + n + 3);
2043             if (regex) {
2044                 regex[0] = '@';
2045                 for (n = 1, s = value; *s; s++) {
2046                     if (*s == '.')
2047                         regex[n++] = '\\';
2048                     regex[n++] = *s;
2049                 }
2050                 regex[n++] = '$';
2051                 regex[n] = '\0';
2052             }
2053         }
2054         if (!regex) {
2055             debug(DBG_ERR, "malloc failed");
2056             realm = NULL;
2057             goto exit;
2058         }
2059         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2060     }
2061
2062     realm = malloc(sizeof(struct realm));
2063     if (!realm) {
2064         debug(DBG_ERR, "malloc failed");
2065         goto exit;
2066     }
2067     memset(realm, 0, sizeof(struct realm));
2068
2069     if (pthread_mutex_init(&realm->mutex, NULL)) {
2070         debug(DBG_ERR, "mutex init failed");
2071         free(realm);
2072         realm = NULL;
2073         goto exit;
2074     }
2075
2076     realm->name = stringcopy(value, 0);
2077     if (!realm->name) {
2078         debug(DBG_ERR, "malloc failed");
2079         goto errexit;
2080     }
2081     if (message && strlen(message) > 253) {
2082         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2083         goto errexit;
2084     }
2085     realm->message = message;
2086     realm->accresp = accresp;
2087
2088     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2089         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2090         goto errexit;
2091     }
2092
2093     if (servers && *servers) {
2094         realm->srvconfs = addsrvconfs(value, servers);
2095         if (!realm->srvconfs)
2096             goto errexit;
2097     }
2098
2099     if (accservers && *accservers) {
2100         realm->accsrvconfs = addsrvconfs(value, accservers);
2101         if (!realm->accsrvconfs)
2102             goto errexit;
2103     }
2104
2105     if (!list_push(realmlist, realm)) {
2106         debug(DBG_ERR, "malloc failed");
2107         pthread_mutex_destroy(&realm->mutex);
2108         goto errexit;
2109     }
2110
2111     debug(DBG_DBG, "addrealm: added realm %s", value);
2112     goto exit;
2113
2114 errexit:
2115     while (list_shift(realm->srvconfs));
2116     while (list_shift(realm->accsrvconfs));
2117     freerealm(realm);
2118     realm = NULL;
2119 exit:
2120     free(regex);
2121     if (servers) {
2122         if (realm)
2123             for (n = 0; servers[n]; n++)
2124                 newrealmref(realm);
2125         freegconfmstr(servers);
2126     }
2127     if (accservers) {
2128         if (realm)
2129             for (n = 0; accservers[n]; n++)
2130                 newrealmref(realm);
2131         freegconfmstr(accservers);
2132     }
2133     return newrealmref(realm);
2134 }
2135
2136 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2137     struct list_node *entry;
2138     struct clsrvconf *conf, *srvconf;
2139     struct list *subrealmservers = NULL;
2140     pthread_t clientth;
2141
2142     if (list_first(srvconfs)) {
2143         subrealmservers = list_create();
2144         if (!subrealmservers)
2145             return NULL;
2146     }
2147
2148     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2149         conf = (struct clsrvconf *)entry->data;
2150         if (!conf->servers && conf->dynamiclookupcommand) {
2151             srvconf = malloc(sizeof(struct clsrvconf));
2152             if (!srvconf) {
2153                 debug(DBG_ERR, "malloc failed");
2154                 continue;
2155             }
2156             *srvconf = *conf;
2157             if (addserver(srvconf)) {
2158                 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2159                 srvconf->servers->dynstartup = 1;
2160                 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2161                     debug(DBG_ERR, "pthread_create failed");
2162                     freeserver(srvconf->servers, 1);
2163                     srvconf->servers = NULL;
2164                 } else
2165                     pthread_detach(clientth);
2166             }
2167             conf = srvconf;
2168         }
2169         if (conf->servers) {
2170             if (list_push(subrealmservers, conf))
2171                 newrealmref(realm);
2172             else
2173                 debug(DBG_ERR, "malloc failed");
2174         }
2175     }
2176     return subrealmservers;
2177 }
2178
2179 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2180     struct realm *newrealm = NULL;
2181     char *realmname, *s;
2182
2183     /* create dynamic for the realm (string after last @, exit if nothing after @ */
2184     realmname = strrchr(id, '@');
2185     if (!realmname)
2186         return NULL;
2187     realmname++;
2188     if (!*realmname)
2189         return NULL;
2190     for (s = realmname; *s; s++)
2191         if (*s != '.' && *s != '-' && !isalnum((int)*s))
2192             return NULL;
2193
2194     if (!realm->subrealms)
2195         realm->subrealms = list_create();
2196     if (!realm->subrealms)
2197         return NULL;
2198
2199     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2200     if (!newrealm) {
2201         list_destroy(realm->subrealms);
2202         realm->subrealms = NULL;
2203         return NULL;
2204     }
2205
2206     newrealm->parent = newrealmref(realm);
2207     /* add server and accserver to newrealm */
2208     newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2209     newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2210     return newrealm;
2211 }
2212
2213 int dynamicconfig(struct server *server) {
2214     int ok, fd[2], status;
2215     pid_t pid;
2216     struct clsrvconf *conf = server->conf;
2217     struct gconffile *cf = NULL;
2218
2219     /* for now we only learn hostname/address */
2220     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2221
2222     if (pipe(fd) > 0) {
2223         debug(DBG_ERR, "dynamicconfig: pipe error");
2224         goto errexit;
2225     }
2226     pid = fork();
2227     if (pid < 0) {
2228         debug(DBG_ERR, "dynamicconfig: fork error");
2229         close(fd[0]);
2230         close(fd[1]);
2231         goto errexit;
2232     } else if (pid == 0) {
2233         /* child */
2234         close(fd[0]);
2235         if (fd[1] != STDOUT_FILENO) {
2236             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2237                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2238             close(fd[1]);
2239         }
2240         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2241             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2242     }
2243
2244     close(fd[1]);
2245     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2246     ok = getgenericconfig(&cf, NULL,
2247                           "Server", CONF_CBK, confserver_cb, (void *)conf,
2248                           NULL
2249         );
2250     freegconf(&cf);
2251
2252     if (waitpid(pid, &status, 0) < 0) {
2253         debug(DBG_ERR, "dynamicconfig: wait error");
2254         goto errexit;
2255     }
2256
2257     if (status) {
2258         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2259         goto errexit;
2260     }
2261
2262     if (ok)
2263         return 1;
2264
2265 errexit:
2266     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2267     return 0;
2268 }
2269
2270 /* should accept both names and numeric values, only numeric right now */
2271 uint8_t attrname2val(char *attrname) {
2272     int val = 0;
2273
2274     val = atoi(attrname);
2275     return val > 0 && val < 256 ? val : 0;
2276 }
2277
2278 /* ATTRNAME is on the form vendor[:type].
2279    If only vendor is found, TYPE is set to 256 and 1 is returned.
2280    If type is >= 256, 1 is returned.
2281    Otherwise, 0 is returned.
2282 */
2283 /* should accept both names and numeric values, only numeric right now */
2284 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2285     char *s;
2286
2287     *vendor = atoi(attrname);
2288     s = strchr(attrname, ':');
2289     if (!s) {                   /* Only vendor was found.  */
2290         *type = 256;
2291         return 1;
2292     }
2293     *type = atoi(s + 1);
2294     return *type < 256;
2295 }
2296
2297 /* should accept both names and numeric values, only numeric right now */
2298 struct tlv *extractattr(char *nameval) {
2299     int len, name = 0;
2300     int vendor = 0;         /* Vendor 0 is reserved, see RFC 1700.  */
2301     char *s, *s2;
2302     struct tlv *a;
2303
2304     s = strchr(nameval, ':');
2305     if (!s)
2306         return NULL;
2307     name = atoi(nameval);
2308
2309     /* Two ':' means that we have vendor:name:val.  */
2310     s2 = strchr(s + 1, ':');
2311     if (s2) {
2312         vendor = name;
2313         name = atoi(s + 1);
2314         s = s2;
2315     }
2316     len = strlen(s + 1);
2317     if (len > 253)
2318         return NULL;
2319
2320     if (name < 1 || name > 255)
2321         return NULL;
2322     a = malloc(sizeof(struct tlv));
2323     if (!a)
2324         return NULL;
2325
2326     a->v = (uint8_t *)stringcopy(s + 1, 0);
2327     if (!a->v) {
2328         free(a);
2329         return NULL;
2330     }
2331     a->t = name;
2332     a->l = len;
2333
2334     if (vendor)
2335         a = makevendortlv(vendor, a);
2336
2337     return a;
2338 }
2339
2340 /* should accept both names and numeric values, only numeric right now */
2341 struct modattr *extractmodattr(char *nameval) {
2342     int name = 0;
2343     char *s, *t;
2344     struct modattr *m;
2345
2346     if (!strncasecmp(nameval, "User-Name:/", 11)) {
2347         s = nameval + 11;
2348         name = 1;
2349     } else {
2350         s = strchr(nameval, ':');
2351         name = atoi(nameval);
2352         if (!s || name < 1 || name > 255 || s[1] != '/')
2353             return NULL;
2354         s += 2;
2355     }
2356     /* regexp, remove optional trailing / if present */
2357     if (s[strlen(s) - 1] == '/')
2358         s[strlen(s) - 1] = '\0';
2359
2360     t = strchr(s, '/');
2361     if (!t)
2362         return NULL;
2363     *t = '\0';
2364     t++;
2365
2366     m = malloc(sizeof(struct modattr));
2367     if (!m) {
2368         debug(DBG_ERR, "malloc failed");
2369         return NULL;
2370     }
2371     m->t = name;
2372
2373     m->replacement = stringcopy(t, 0);
2374     if (!m->replacement) {
2375         free(m);
2376         debug(DBG_ERR, "malloc failed");
2377         return NULL;
2378     }
2379
2380     m->regex = malloc(sizeof(regex_t));
2381     if (!m->regex) {
2382         free(m->replacement);
2383         free(m);
2384         debug(DBG_ERR, "malloc failed");
2385         return NULL;
2386     }
2387
2388     if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2389         free(m->regex);
2390         free(m->replacement);
2391         free(m);
2392         debug(DBG_ERR, "failed to compile regular expression %s", s);
2393         return NULL;
2394     }
2395
2396     return m;
2397 }
2398
2399 struct rewrite *getrewrite(char *alt1, char *alt2) {
2400     struct rewrite *r;
2401
2402     if ((r = hash_read(rewriteconfs,  alt1, strlen(alt1))))
2403         return r;
2404     if ((r = hash_read(rewriteconfs,  alt2, strlen(alt2))))
2405         return r;
2406     return NULL;
2407 }
2408
2409 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2410 {
2411     struct rewrite *rewrite = NULL;
2412     int i, n;
2413     uint8_t *rma = NULL;
2414     uint32_t *p, *rmva = NULL;
2415     struct list *adda = NULL, *moda = NULL;
2416     struct tlv *a;
2417     struct modattr *m;
2418
2419     if (rmattrs) {
2420         for (n = 0; rmattrs[n]; n++);
2421         rma = calloc(n + 1, sizeof(uint8_t));
2422         if (!rma)
2423             debugx(1, DBG_ERR, "malloc failed");
2424
2425         for (i = 0; i < n; i++)
2426             if (!(rma[i] = attrname2val(rmattrs[i])))
2427                 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2428         freegconfmstr(rmattrs);
2429         rma[i] = 0;
2430     }
2431
2432     if (rmvattrs) {
2433         for (n = 0; rmvattrs[n]; n++);
2434         rmva = calloc(2 * n + 1, sizeof(uint32_t));
2435         if (!rmva)
2436             debugx(1, DBG_ERR, "malloc failed");
2437
2438         for (p = rmva, i = 0; i < n; i++, p += 2)
2439             if (!vattrname2val(rmvattrs[i], p, p + 1))
2440                 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2441         freegconfmstr(rmvattrs);
2442         *p = 0;
2443     }
2444
2445     if (addattrs) {
2446         adda = list_create();
2447         if (!adda)
2448             debugx(1, DBG_ERR, "malloc failed");
2449         for (i = 0; addattrs[i]; i++) {
2450             a = extractattr(addattrs[i]);
2451             if (!a)
2452                 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2453             if (!list_push(adda, a))
2454                 debugx(1, DBG_ERR, "malloc failed");
2455         }
2456         freegconfmstr(addattrs);
2457     }
2458
2459     if (addvattrs) {
2460         if (!adda)
2461             adda = list_create();
2462         if (!adda)
2463             debugx(1, DBG_ERR, "malloc failed");
2464         for (i = 0; addvattrs[i]; i++) {
2465             a = extractattr(addvattrs[i]);
2466             if (!a)
2467                 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2468             if (!list_push(adda, a))
2469                 debugx(1, DBG_ERR, "malloc failed");
2470         }
2471         freegconfmstr(addvattrs);
2472     }
2473
2474     if (modattrs) {
2475         moda = list_create();
2476         if (!moda)
2477             debugx(1, DBG_ERR, "malloc failed");
2478         for (i = 0; modattrs[i]; i++) {
2479             m = extractmodattr(modattrs[i]);
2480             if (!m)
2481                 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2482             if (!list_push(moda, m))
2483                 debugx(1, DBG_ERR, "malloc failed");
2484         }
2485         freegconfmstr(modattrs);
2486     }
2487
2488     if (rma || rmva || adda || moda) {
2489         rewrite = malloc(sizeof(struct rewrite));
2490         if (!rewrite)
2491             debugx(1, DBG_ERR, "malloc failed");
2492         rewrite->removeattrs = rma;
2493         rewrite->removevendorattrs = rmva;
2494         rewrite->addattrs = adda;
2495         rewrite->modattrs = moda;
2496     }
2497
2498     if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2499         debugx(1, DBG_ERR, "malloc failed");
2500     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2501 }
2502
2503 int setttlattr(struct options *opts, char *defaultattr) {
2504     char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2505
2506     if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2507         (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2508         return 1;
2509     debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2510     return 0;
2511 }
2512
2513 void freeclsrvconf(struct clsrvconf *conf) {
2514     free(conf->name);
2515     if (conf->hostsrc)
2516         freegconfmstr(conf->hostsrc);
2517     free(conf->portsrc);
2518     free(conf->secret);
2519     free(conf->tls);
2520     free(conf->matchcertattr);
2521     if (conf->certcnregex)
2522         regfree(conf->certcnregex);
2523     if (conf->certuriregex)
2524         regfree(conf->certuriregex);
2525     free(conf->confrewritein);
2526     free(conf->confrewriteout);
2527     if (conf->rewriteusername) {
2528         if (conf->rewriteusername->regex)
2529             regfree(conf->rewriteusername->regex);
2530         free(conf->rewriteusername->replacement);
2531         free(conf->rewriteusername);
2532     }
2533     free(conf->dynamiclookupcommand);
2534     free(conf->rewritein);
2535     free(conf->rewriteout);
2536     if (conf->hostports)
2537         freehostports(conf->hostports);
2538     if (conf->lock) {
2539         pthread_mutex_destroy(conf->lock);
2540         free(conf->lock);
2541     }
2542     /* not touching ssl_ctx, clients and servers */
2543     free(conf);
2544 }
2545
2546 int mergeconfstring(char **dst, char **src) {
2547     char *t;
2548
2549     if (*src) {
2550         *dst = *src;
2551         *src = NULL;
2552         return 1;
2553     }
2554     if (*dst) {
2555         t = stringcopy(*dst, 0);
2556         if (!t) {
2557             debug(DBG_ERR, "malloc failed");
2558             return 0;
2559         }
2560         *dst = t;
2561     }
2562     return 1;
2563 }
2564
2565 char **mstringcopy(char **in) {
2566     char **out;
2567     int n;
2568
2569     if (!in)
2570         return NULL;
2571
2572     for (n = 0; in[n]; n++);
2573     out = malloc((n + 1) * sizeof(char *));
2574     if (!out)
2575         return NULL;
2576     for (n = 0; in[n]; n++) {
2577         out[n] = stringcopy(in[n], 0);
2578         if (!out[n]) {
2579             freegconfmstr(out);
2580             return NULL;
2581         }
2582     }
2583     out[n] = NULL;
2584     return out;
2585 }
2586
2587 int mergeconfmstring(char ***dst, char ***src) {
2588     char **t;
2589
2590     if (*src) {
2591         *dst = *src;
2592         *src = NULL;
2593         return 1;
2594     }
2595     if (*dst) {
2596         t = mstringcopy(*dst);
2597         if (!t) {
2598             debug(DBG_ERR, "malloc failed");
2599             return 0;
2600         }
2601         *dst = t;
2602     }
2603     return 1;
2604 }
2605
2606 /* assumes dst is a shallow copy */
2607 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2608     if (!mergeconfstring(&dst->name, &src->name) ||
2609         !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2610         !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2611         !mergeconfstring(&dst->secret, &src->secret) ||
2612         !mergeconfstring(&dst->tls, &src->tls) ||
2613         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2614         !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2615         !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2616         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2617         return 0;
2618     if (src->pdef)
2619         dst->pdef = src->pdef;
2620     dst->statusserver = src->statusserver;
2621     dst->certnamecheck = src->certnamecheck;
2622     if (src->retryinterval != 255)
2623         dst->retryinterval = src->retryinterval;
2624     if (src->retrycount != 255)
2625         dst->retrycount = src->retrycount;
2626     return 1;
2627 }
2628
2629 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2630     struct clsrvconf *conf;
2631     char *conftype = NULL, *rewriteinalias = NULL;
2632     long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2633
2634     debug(DBG_DBG, "confclient_cb called for %s", block);
2635
2636     conf = malloc(sizeof(struct clsrvconf));
2637     if (!conf)
2638         debugx(1, DBG_ERR, "malloc failed");
2639     memset(conf, 0, sizeof(struct clsrvconf));
2640     conf->certnamecheck = 1;
2641
2642     if (!getgenericconfig(cf, block,
2643                           "type", CONF_STR, &conftype,
2644                           "host", CONF_MSTR, &conf->hostsrc,
2645                           "secret", CONF_STR, &conf->secret,
2646 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2647                           "tls", CONF_STR, &conf->tls,
2648                           "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2649                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2650 #endif
2651                           "DuplicateInterval", CONF_LINT, &dupinterval,
2652                           "addTTL", CONF_LINT, &addttl,
2653                           "rewrite", CONF_STR, &rewriteinalias,
2654                           "rewriteIn", CONF_STR, &conf->confrewritein,
2655                           "rewriteOut", CONF_STR, &conf->confrewriteout,
2656                           "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2657                           NULL
2658             ))
2659         debugx(1, DBG_ERR, "configuration error");
2660
2661     conf->name = stringcopy(val, 0);
2662     if (conf->name && !conf->hostsrc) {
2663         conf->hostsrc = malloc(2 * sizeof(char *));
2664         if (conf->hostsrc) {
2665             conf->hostsrc[0] = stringcopy(val, 0);
2666             conf->hostsrc[1] = NULL;
2667         }
2668     }
2669     if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2670         debugx(1, DBG_ERR, "malloc failed");
2671
2672     if (!conftype)
2673         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2674     conf->type = protoname2int(conftype);
2675     if (conf->type == 255)
2676         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2677     free(conftype);
2678     conf->pdef = protodefs[conf->type];
2679
2680 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2681     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2682         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2683         if (!conf->tlsconf)
2684             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2685         if (conf->matchcertattr && !addmatchcertattr(conf))
2686             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2687     }
2688 #endif
2689
2690     if (dupinterval != LONG_MIN) {
2691         if (dupinterval < 0 || dupinterval > 255)
2692             debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2693         conf->dupinterval = (uint8_t)dupinterval;
2694     } else
2695         conf->dupinterval = conf->pdef->duplicateintervaldefault;
2696
2697     if (addttl != LONG_MIN) {
2698         if (addttl < 1 || addttl > 255)
2699             debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2700         conf->addttl = (uint8_t)addttl;
2701     }
2702
2703     if (!conf->confrewritein)
2704         conf->confrewritein = rewriteinalias;
2705     else
2706         free(rewriteinalias);
2707     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2708     if (conf->confrewriteout)
2709         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2710
2711     if (conf->confrewriteusername) {
2712         conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2713         if (!conf->rewriteusername)
2714             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2715     }
2716
2717     if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2718         !resolvehostports(conf->hostports, conf->pdef->socktype))
2719         debugx(1, DBG_ERR, "resolve failed, exiting");
2720
2721     if (!conf->secret) {
2722         if (!conf->pdef->secretdefault)
2723             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2724         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2725         if (!conf->secret)
2726             debugx(1, DBG_ERR, "malloc failed");
2727     }
2728
2729     conf->lock = malloc(sizeof(pthread_mutex_t));
2730     if (!conf->lock)
2731         debugx(1, DBG_ERR, "malloc failed");
2732
2733     pthread_mutex_init(conf->lock, NULL);
2734     if (!list_push(clconfs, conf))
2735         debugx(1, DBG_ERR, "malloc failed");
2736     return 1;
2737 }
2738
2739 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2740 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2741     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2742         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2743         if (!conf->tlsconf) {
2744             debug(DBG_ERR, "error in block %s, no tls context defined", block);
2745             return 0;
2746         }
2747         if (conf->matchcertattr && !addmatchcertattr(conf)) {
2748             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2749             return 0;
2750         }
2751     }
2752 #endif
2753
2754     if (!conf->portsrc) {
2755         conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2756         if (!conf->portsrc) {
2757             debug(DBG_ERR, "malloc failed");
2758             return 0;
2759         }
2760     }
2761
2762     if (conf->retryinterval == 255)
2763         conf->retryinterval = conf->pdef->retryintervaldefault;
2764     if (conf->retrycount == 255)
2765         conf->retrycount = conf->pdef->retrycountdefault;
2766
2767     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2768     if (conf->confrewriteout)
2769         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2770
2771     if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2772         debug(DBG_ERR, "error in block %s, failed to parse %s", block, conf->hostsrc);
2773         return 0;
2774     }
2775
2776     if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2777         debug(DBG_ERR, "resolve failed, exiting");
2778         return 0;
2779     }
2780     return 1;
2781 }
2782
2783 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2784     struct clsrvconf *conf, *resconf;
2785     char *conftype = NULL, *rewriteinalias = NULL;
2786     long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2787
2788     debug(DBG_DBG, "confserver_cb called for %s", block);
2789
2790     conf = malloc(sizeof(struct clsrvconf));
2791     if (!conf) {
2792         debug(DBG_ERR, "malloc failed");
2793         return 0;
2794     }
2795     memset(conf, 0, sizeof(struct clsrvconf));
2796     conf->loopprevention = UCHAR_MAX; /* Uninitialized.  */
2797     resconf = (struct clsrvconf *)arg;
2798     if (resconf) {
2799         conf->statusserver = resconf->statusserver;
2800         conf->certnamecheck = resconf->certnamecheck;
2801     } else
2802         conf->certnamecheck = 1;
2803
2804     if (!getgenericconfig(cf, block,
2805                           "type", CONF_STR, &conftype,
2806                           "host", CONF_MSTR, &conf->hostsrc,
2807                           "port", CONF_STR, &conf->portsrc,
2808                           "secret", CONF_STR, &conf->secret,
2809 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2810                           "tls", CONF_STR, &conf->tls,
2811                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2812                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2813 #endif
2814                           "addTTL", CONF_LINT, &addttl,
2815                           "rewrite", CONF_STR, &rewriteinalias,
2816                           "rewriteIn", CONF_STR, &conf->confrewritein,
2817                           "rewriteOut", CONF_STR, &conf->confrewriteout,
2818                           "StatusServer", CONF_BLN, &conf->statusserver,
2819                           "RetryInterval", CONF_LINT, &retryinterval,
2820                           "RetryCount", CONF_LINT, &retrycount,
2821                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2822                           "LoopPrevention", CONF_BLN, &conf->loopprevention,
2823                           NULL
2824             )) {
2825         debug(DBG_ERR, "configuration error");
2826         goto errexit;
2827     }
2828
2829     conf->name = stringcopy(val, 0);
2830     if (conf->name && !conf->hostsrc) {
2831         conf->hostsrc = malloc(2 * sizeof(char *));
2832         if (conf->hostsrc) {
2833             conf->hostsrc[0] = stringcopy(val, 0);
2834             conf->hostsrc[1] = NULL;
2835         }
2836     }
2837     if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2838         debug(DBG_ERR, "malloc failed");
2839         goto errexit;
2840     }
2841
2842     if (!conftype) {
2843         debug(DBG_ERR, "error in block %s, option type missing", block);
2844         goto errexit;
2845     }
2846     conf->type = protoname2int(conftype);
2847     if (conf->type == 255) {
2848         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2849         goto errexit;
2850     }
2851     free(conftype);
2852     conftype = NULL;
2853
2854     conf->pdef = protodefs[conf->type];
2855
2856     if (!conf->confrewritein)
2857         conf->confrewritein = rewriteinalias;
2858     else
2859         free(rewriteinalias);
2860     rewriteinalias = NULL;
2861
2862     if (retryinterval != LONG_MIN) {
2863         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2864             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2865             goto errexit;
2866         }
2867         conf->retryinterval = (uint8_t)retryinterval;
2868     } else
2869         conf->retryinterval = 255;
2870
2871     if (retrycount != LONG_MIN) {
2872         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2873             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2874             goto errexit;
2875         }
2876         conf->retrycount = (uint8_t)retrycount;
2877     } else
2878         conf->retrycount = 255;
2879
2880     if (addttl != LONG_MIN) {
2881         if (addttl < 1 || addttl > 255) {
2882             debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2883             goto errexit;
2884         }
2885         conf->addttl = (uint8_t)addttl;
2886     }
2887
2888     if (resconf) {
2889         if (!mergesrvconf(resconf, conf))
2890             goto errexit;
2891         free(conf);
2892         conf = resconf;
2893         if (conf->dynamiclookupcommand) {
2894             free(conf->dynamiclookupcommand);
2895             conf->dynamiclookupcommand = NULL;
2896         }
2897     }
2898
2899     if (resconf || !conf->dynamiclookupcommand) {
2900         if (!compileserverconfig(conf, block))
2901             goto errexit;
2902     }
2903
2904     if (!conf->secret) {
2905         if (!conf->pdef->secretdefault) {
2906             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2907             return 0;
2908         }
2909         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2910         if (!conf->secret) {
2911             debug(DBG_ERR, "malloc failed");
2912             return 0;
2913         }
2914     }
2915
2916     if (resconf)
2917         return 1;
2918
2919     if (!list_push(srvconfs, conf)) {
2920         debug(DBG_ERR, "malloc failed");
2921         goto errexit;
2922     }
2923     return 1;
2924
2925 errexit:
2926     free(conftype);
2927     free(rewriteinalias);
2928     freeclsrvconf(conf);
2929     return 0;
2930 }
2931
2932 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2933     char **servers = NULL, **accservers = NULL, *msg = NULL;
2934     uint8_t accresp = 0;
2935
2936     debug(DBG_DBG, "confrealm_cb called for %s", block);
2937
2938     if (!getgenericconfig(cf, block,
2939                           "server", CONF_MSTR, &servers,
2940                           "accountingServer", CONF_MSTR, &accservers,
2941                           "ReplyMessage", CONF_STR, &msg,
2942                           "AccountingResponse", CONF_BLN, &accresp,
2943                           NULL
2944             ))
2945         debugx(1, DBG_ERR, "configuration error");
2946
2947     addrealm(realms, val, servers, accservers, msg, accresp);
2948     return 1;
2949 }
2950
2951 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2952     char **rmattrs = NULL, **rmvattrs = NULL;
2953     char **addattrs = NULL, **addvattrs = NULL;
2954     char **modattrs = NULL;
2955
2956     debug(DBG_DBG, "confrewrite_cb called for %s", block);
2957
2958     if (!getgenericconfig(cf, block,
2959                           "removeAttribute", CONF_MSTR, &rmattrs,
2960                           "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2961                           "addAttribute", CONF_MSTR, &addattrs,
2962                           "addVendorAttribute", CONF_MSTR, &addvattrs,
2963                           "modifyAttribute", CONF_MSTR, &modattrs,
2964                           NULL
2965             ))
2966         debugx(1, DBG_ERR, "configuration error");
2967     addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
2968     return 1;
2969 }
2970
2971 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2972     struct commonprotoopts *protoopts;
2973
2974     protoopts = malloc(sizeof(struct commonprotoopts));
2975     if (!protoopts)
2976         return 0;
2977     memset(protoopts, 0, sizeof(struct commonprotoopts));
2978     protoopts->listenargs = listenargs;
2979     protoopts->sourcearg = sourcearg;
2980     protodefs[type]->setprotoopts(protoopts);
2981     return 1;
2982 }
2983
2984 void getmainconfig(const char *configfile) {
2985     long int addttl = LONG_MIN, loglevel = LONG_MIN;
2986     struct gconffile *cfs;
2987     char **listenargs[RAD_PROTOCOUNT];
2988     char *sourcearg[RAD_PROTOCOUNT];
2989     int i;
2990
2991     cfs = openconfigfile(configfile);
2992     memset(&options, 0, sizeof(options));
2993     memset(&listenargs, 0, sizeof(listenargs));
2994     memset(&sourcearg, 0, sizeof(sourcearg));
2995
2996     clconfs = list_create();
2997     if (!clconfs)
2998         debugx(1, DBG_ERR, "malloc failed");
2999
3000     srvconfs = list_create();
3001     if (!srvconfs)
3002         debugx(1, DBG_ERR, "malloc failed");
3003
3004     realms = list_create();
3005     if (!realms)
3006         debugx(1, DBG_ERR, "malloc failed");
3007
3008     rewriteconfs = hash_create();
3009     if (!rewriteconfs)
3010         debugx(1, DBG_ERR, "malloc failed");
3011
3012     if (!getgenericconfig(&cfs, NULL,
3013 #ifdef RADPROT_UDP
3014                           "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3015                           "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3016 #endif
3017 #ifdef RADPROT_TCP
3018                           "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3019                           "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3020 #endif
3021 #ifdef RADPROT_TLS
3022                           "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3023                           "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3024 #endif
3025 #ifdef RADPROT_DTLS
3026                           "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3027                           "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3028 #endif
3029                           "TTLAttribute", CONF_STR, &options.ttlattr,
3030                           "addTTL", CONF_LINT, &addttl,
3031                           "LogLevel", CONF_LINT, &loglevel,
3032                           "LogDestination", CONF_STR, &options.logdestination,
3033                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3034                           "Client", CONF_CBK, confclient_cb, NULL,
3035                           "Server", CONF_CBK, confserver_cb, NULL,
3036                           "Realm", CONF_CBK, confrealm_cb, NULL,
3037 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3038                           "TLS", CONF_CBK, conftls_cb, NULL,
3039 #endif
3040                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3041                           NULL
3042             ))
3043         debugx(1, DBG_ERR, "configuration error");
3044
3045     if (loglevel != LONG_MIN) {
3046         if (loglevel < 1 || loglevel > 4)
3047             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3048         options.loglevel = (uint8_t)loglevel;
3049     }
3050     if (addttl != LONG_MIN) {
3051         if (addttl < 1 || addttl > 255)
3052             debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3053         options.addttl = (uint8_t)addttl;
3054     }
3055     if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3056         debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3057
3058     for (i = 0; i < RAD_PROTOCOUNT; i++)
3059         if (listenargs[i] || sourcearg[i])
3060             setprotoopts(i, listenargs[i], sourcearg[i]);
3061 }
3062
3063 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3064     int c;
3065
3066     while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3067         switch (c) {
3068         case 'c':
3069             *configfile = optarg;
3070             break;
3071         case 'd':
3072             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3073                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3074             *loglevel = *optarg - '0';
3075             break;
3076         case 'f':
3077             *foreground = 1;
3078             break;
3079         case 'i':
3080             *pidfile = optarg;
3081             break;
3082         case 'p':
3083             *pretend = 1;
3084             break;
3085         case 'v':
3086             debug(DBG_ERR, "radsecproxy revision $Rev$");
3087             debug(DBG_ERR, "This binary was built with support for the following transports:");
3088 #ifdef RADPROT_UDP
3089             debug(DBG_ERR, "  UDP");
3090 #endif
3091 #ifdef RADPROT_TCP
3092             debug(DBG_ERR, "  TCP");
3093 #endif
3094 #ifdef RADPROT_TLS
3095             debug(DBG_ERR, "  TLS");
3096 #endif
3097 #ifdef RADPROT_DTLS
3098             debug(DBG_ERR, "  DTLS");
3099 #endif
3100             exit(0);
3101         default:
3102             goto usage;
3103         }
3104     }
3105     if (!(argc - optind))
3106         return;
3107
3108 usage:
3109     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3110 }
3111
3112 #ifdef SYS_SOLARIS9
3113 int daemon(int a, int b) {
3114     int i;
3115
3116     if (fork())
3117         exit(0);
3118
3119     setsid();
3120
3121     for (i = 0; i < 3; i++) {
3122         close(i);
3123         open("/dev/null", O_RDWR);
3124     }
3125     return 1;
3126 }
3127 #endif
3128
3129 void *sighandler(void *arg) {
3130     sigset_t sigset;
3131     int sig;
3132
3133     for(;;) {
3134         sigemptyset(&sigset);
3135         sigaddset(&sigset, SIGHUP);
3136         sigaddset(&sigset, SIGPIPE);
3137         sigwait(&sigset, &sig);
3138         switch (sig) {
3139         case 0:
3140             /* completely ignoring this */
3141             break;
3142         case SIGHUP:
3143             debug(DBG_INFO, "sighandler: got SIGHUP");
3144             debug_reopen_log();
3145             break;
3146         case SIGPIPE:
3147             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3148             break;
3149         default:
3150             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3151         }
3152     }
3153 }
3154
3155 int createpidfile(const char *pidfile) {
3156     int r;
3157     FILE *f = fopen(pidfile, "w");
3158     if (f)
3159         r = fprintf(f, "%d\n", getpid());
3160     return f && !fclose(f) && r >= 0;
3161 }
3162
3163 int main(int argc, char **argv) {
3164     pthread_t sigth;
3165     sigset_t sigset;
3166     struct list_node *entry;
3167     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3168     char *configfile = NULL, *pidfile = NULL;
3169     struct clsrvconf *srvconf;
3170     int i;
3171
3172     debug_init("radsecproxy");
3173     debug_set_level(DEBUG_LEVEL);
3174
3175     for (i = 0; i < RAD_PROTOCOUNT; i++)
3176         protodefs[i] = protoinits[i](i);
3177
3178     /* needed even if no TLS/DTLS transport */
3179     sslinit();
3180
3181     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3182     if (loglevel)
3183         debug_set_level(loglevel);
3184     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3185     if (loglevel)
3186         options.loglevel = loglevel;
3187     else if (options.loglevel)
3188         debug_set_level(options.loglevel);
3189     if (!foreground)
3190         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3191     free(options.logdestination);
3192
3193     if (!list_first(clconfs))
3194         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3195     if (!list_first(realms))
3196         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3197
3198     if (pretend)
3199         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3200
3201     if (!foreground && (daemon(0, 0) < 0))
3202         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3203
3204     debug_timestamp_on();
3205     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3206     if (pidfile && !createpidfile(pidfile))
3207         debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3208
3209     sigemptyset(&sigset);
3210     /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3211     sigaddset(&sigset, SIGHUP);
3212     sigaddset(&sigset, SIGPIPE);
3213     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3214     pthread_create(&sigth, NULL, sighandler, NULL);
3215
3216     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3217         srvconf = (struct clsrvconf *)entry->data;
3218         if (srvconf->dynamiclookupcommand)
3219             continue;
3220         if (!addserver(srvconf))
3221             debugx(1, DBG_ERR, "failed to add server");
3222         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3223                            (void *)(srvconf->servers)))
3224             debugx(1, DBG_ERR, "pthread_create failed");
3225     }
3226
3227     for (i = 0; i < RAD_PROTOCOUNT; i++) {
3228         if (!protodefs[i])
3229             continue;
3230         if (protodefs[i]->initextra)
3231             protodefs[i]->initextra();
3232         if (find_clconf_type(i, NULL))
3233             createlisteners(i);
3234     }
3235
3236     /* just hang around doing nothing, anything to do here? */
3237     for (;;)
3238         sleep(1000);
3239 }
3240
3241 /* Local Variables: */
3242 /* c-file-style: "stroustrup" */
3243 /* End: */