summaryrefslogtreecommitdiff
path: root/apache1x/mod_httpauth.c
blob: bb71ea71872c12125242acb9275f237dd4668a74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
/*
 * Copyright (c) 2004, Stefan Walter
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above
 *       copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the
 *       above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or
 *       other materials provided with the distribution.
 *     * The names of contributors to this software may not be
 *       used to endorse or promote products derived from this
 *       software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 *
 * CONTRIBUTORS
 *  Stef Walter <stef@memberwebs.com>
 *
 */

#include <httpd.h>
#include <http_core.h>
#include <http_config.h>
#include <http_log.h>
#include <http_protocol.h>
#include <ap_config.h>
#include <ap_alloc.h>

#include "sock-any.h"
#include "stringx.h"

#define DEFAULT_PORT 8020

module MODULE_VAR_EXPORT httpauth_module;

/* Keep track of a unique identifier */
static void* conn_current = NULL;

/* And increment this when it goes out of scope */
static unsigned int conn_seen = 0;

typedef struct httpauth_context
{
    const char* socketname;
    int socket;
    int types;
    const char* handler;
    const char* domain;
    pool* child_pool;
}
httpauth_context_t;

/* TODO: Support proxy authentication properly */

#define AUTH_PREFIX_BASIC   "Basic"
#define AUTH_PREFIX_DIGEST  "Digest"
#define AUTH_PREFIX_NTLM    "NTLM"

#define AUTH_TYPE_BASIC     1 << 1
#define AUTH_TYPE_DIGEST    1 << 2
#define AUTH_TYPE_NTLM      1 << 3
#define AUTH_TYPE_ANY       0x0000FFFF

#define HTTPAUTH_AUTHTYPE   "HTTPAUTH"

/* -------------------------------------------------------------------------------
 * Configuration code
 */

static void* httpauth_dir_config(pool* p, char* dir)
{
    httpauth_context_t* ctx;

    ctx = (httpauth_context_t*)ap_pcalloc(p, sizeof(*ctx));
    memset(ctx, 0, sizeof(*ctx));

    ctx->socket = -1;
    ctx->types = 0xFFFFFFFF;
    ctx->child_pool = p;
    return ctx;
}

static const char* set_socket(cmd_parms* cmd, void* config, const char* val)
{
    struct sockaddr_any sany;

    if(sock_any_pton(val, &sany, DEFAULT_PORT) == -1)
        return "Invalid socket name or ip in HttpAuthSocket";

    ((httpauth_context_t*)config)->socketname = val;
    return NULL;
}

static const char* set_handler(cmd_parms* cmd, void* config, const char* val)
{
    httpauth_context_t* conf = (httpauth_context_t*)config;
    conf->handler = val;
    return NULL;
}

static const char* set_types(cmd_parms* cmd, void* config, const char* val)
{
    httpauth_context_t* conf = (httpauth_context_t*)config;
    int type = 0;

    if(strcasecmp(val, AUTH_PREFIX_BASIC) == 0)
        type = AUTH_TYPE_BASIC;
    else if(strcasecmp(val, AUTH_PREFIX_DIGEST) == 0)
        type = AUTH_TYPE_DIGEST;
    else if(strcasecmp(val, AUTH_PREFIX_NTLM) == 0)
        type = AUTH_TYPE_NTLM;
    else if(strcasecmp(val, "any"))
        type = AUTH_TYPE_ANY;
    else
        return "Invalid type in HttpAuthTypes";

    if(conf->types == 0xFFFFFFFF)
        conf->types = type;
    else
        conf->types |= type;

    return NULL;
}

static const char* set_domain(cmd_parms* cmd, void* config, const char* val)
{
    httpauth_context_t* conf = (httpauth_context_t*)config;
    conf->domain = trim_space(ap_pstrdup(cmd->pool, val));
    return NULL;
}

static const command_rec httpauth_cmds[] =
{
    { "HttpAuthSocket", set_socket, NULL, OR_AUTHCFG, TAKE1,
      "The socket that httpauthd is listening on" },
    { "HttpAuthHandler", set_handler, NULL, OR_AUTHCFG, TAKE1,
      "The handler that httpauthd should use to authenticate" },
    { "HttpAuthTypes", set_types, NULL, OR_AUTHCFG, ITERATE,
      "The types of authentiction allowed (Basic, Digest, NTLM ...)" },
    { "HttpAuthDigestDomain", set_domain, NULL, OR_AUTHCFG, RAW_ARGS,
      "The domain for which digest authentication is relevant" },
    { NULL, NULL, NULL, 0, 0, NULL }
};

/* -------------------------------------------------------------------------------
 * Socket handling code
 */

void disconnect_socket(httpauth_context_t* ctx, server_rec* s)
{
    if(ctx->socket != -1)
    {
        ap_log_error(APLOG_MARK, APLOG_DEBUG, s,
                     "httpauth: disconnecting from daemon");

        ap_pclosesocket(ctx->child_pool, ctx->socket);
        ctx->socket = -1;
        errno = 0;
    }
}

void read_junk(httpauth_context_t* ctx, request_rec* r)
{
    char buf[16];
    const char* t;
    int said = 0;
    int l;

    if(ctx->socket == -1)
        return;

    /* Make it non blocking */
    fcntl(ctx->socket, F_SETFL, fcntl(ctx->socket, F_GETFL, 0) | O_NONBLOCK);

    for(;;)
    {
        l = read(ctx->socket, buf, sizeof(buf) - 1);
        if(l <= 0)
            break;

        buf[l] = 0;
        t = trim_start(buf);

        if(!said && *t)
        {
            ap_log_rerror(APLOG_MARK, APLOG_WARNING, r,
                          "httpauth: received junk data from daemon");
            said = 1;
        }
    }

    fcntl(ctx->socket, F_SETFL, fcntl(ctx->socket, F_GETFL, 0) & ~O_NONBLOCK);
    errno = 0;
}

int read_line(httpauth_context_t* ctx, request_rec* r, char** line)
{
    int l;
    int al = 128;
    char* t;
    const char* e;

    e = t = NULL;
    *line = NULL;

    for(;;)
    {
        if(!*line || t + 2 == e)
        {
            char* n;
            int d;

            n = (char*)ap_palloc(r->pool, al * 2);

            if(*line)
                memcpy(n, *line, al);

            al *= 2;

            /* The difference */
            d = t - *line;

            *line = n;
            t = n + d;
            e = n + al;
        }

        l = read(ctx->socket, (void*)t, sizeof(char));

        /* We got a character */
        if(l == 1)
        {
            /* Skip junky CRLFs */
            if(*t == '\r')
            {
                *t = ' ';
                continue;
            }

            /* End of line */
            else if(*t == '\n')
            {
                t++;
                break;
            }

            t++;
        }

        /* If it's the end of file then return that */
        else if(l == 0)
        {
			/* Disconnect from socket quietly so we can reconnect later */
			disconnect_socket(ctx, r->server);
            return -1;
        }

        /* Transient errors */
        else if(l == -1 && errno == EAGAIN)
            continue;

        /* Fatal errors */
        else if(l == -1)
        {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                          "httpauth: couldn't read data from daemon");
            return -1;
        }
    }

    *t = 0;
    errno = 0;
    return 0;
}

int read_response(httpauth_context_t* ctx, request_rec* r,
                  int* code, int* ccode, char** details)
{
    int c;
    char* line;
    char* t;
    char* t2;

    if(read_line(ctx, r, &line) == -1)
        return -1;

    line = trim_space(line);

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, r,
                  "httpauth: received response line from daemon: %s", line);

    /* Get response code */
    t = ap_getword_nc(r->pool, &line, ' ');
    c = strtol(t, &t2, 10);
    if(*t2 || c < 100 || c > 999)
    {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                      "httpauth: protocol error: invalid code: %s", t);
        return -1;
    }

    if(code)
        *code = c;

    if(c >= 400)
    {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                      "httpauth: received error from httpauthd: %d %s", c, line);
        return -1;
    }

    /* Get the second response code if we're a 200 */
    if(c == 200)
    {
        t = ap_getword_nc(r->pool, &line, ' ');
        c = strtol(t, &t2, 10);
        if(*t2 || c < 100 || c > 999)
        {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                          "httpauth: protocol error: invalid code: %s", t);
            return -1;
        }

        if(ccode)
            *ccode = c;
    }

    if(details)
        *details = trim_space(line);

    return 0;
}

int read_copy_headers(httpauth_context_t* ctx, int ccode, request_rec* r)
{
    char* line;
    const char* name;
    table* headers;
    int c = 0;

    if(ccode > 299)
        headers = r->err_headers_out;
    else
        headers = r->headers_out;

    for(;;)
    {
        if(read_line(ctx, r, &line) == -1)
            return -1;

        /* If that's it then break */
        if(!*line)
            break;

        if(ap_isspace(*line))
        {
            line = (char*)trim_start(line);

            /* End of headers */
            if(!*line)
                break;

            if(c > 0)
            {
                /*
                 * TODO: We really should be supporting headers split
                 * across lines. But httpauthd doesn't currently produce
                 * headers like that, so we don't need to care about it.
                 */
                ap_log_rerror(APLOG_MARK, APLOG_WARNING, r,
                              "httpauth: protocol error: server sent us an split header, which we don't support.");
            }
            else
            {
                ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                              "httpauth: protocol error: invalid headers.");
            }
        }

        name = ap_getword_nc(r->pool, &line, ':');
        if(!name || !*name)
            break;

        /*
         * If that was the end of the line, then it's an
         * invalid header :(
         */
        if(!*line)
        {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                          "httpauth: protocol header: invalid headers");
            return -1;
        }

        line = trim_space(line);

        if(strcasecmp(name, "WWW-Authenticate") == 0)
        {
            if(strncasecmp(line, AUTH_PREFIX_BASIC, strlen(AUTH_PREFIX_BASIC)) == 0 &&
               !(ctx->types & AUTH_TYPE_BASIC))
                continue;

            else if(strncasecmp(line, AUTH_PREFIX_DIGEST, strlen(AUTH_PREFIX_DIGEST)) == 0 &&
                    !(ctx->types & AUTH_TYPE_DIGEST))
                continue;

            else if(strncasecmp(line, AUTH_PREFIX_NTLM, strlen(AUTH_PREFIX_NTLM)) == 0 &&
                    !(ctx->types & AUTH_TYPE_NTLM))
                continue;

            /* Only allow unknown if we don't have it */
            else if(!(ctx->types & AUTH_TYPE_ANY))
                continue;

            /* Fix up when we're a proxy */
            if(r->proxyreq == STD_PROXY)
                name = "Proxy-Authenticate";
        }

        else if(strcasecmp(name, "Authentication-Info") == 0)
        {
            if(r->proxyreq == STD_PROXY)
                name = "Proxy-Authentication-Info";
        }

        c++;
            ap_table_addn(headers, name, line);
    }

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, r,
                  "httpauth: received %d headers from daemon", c);

    return 0;
}

int write_data(httpauth_context_t* ctx, server_rec* s, const char* data)
{
    int r;

    if(ctx->socket == -1)
    {
        ap_log_error(APLOG_MARK, APLOG_ERR, s,
                     "httpauth: Socket to httpauthd daemon closed. Can't write data.");
        return -1;
    }

    while(*data != 0)
    {
        r = write(ctx->socket, data, strlen(data));

        if(r > 0)
            data += r;

        else if(r == -1)
        {
            if(errno == EAGAIN)
                continue;

            /* The other end closed. no message */
            if(errno == EPIPE)
                disconnect_socket(ctx, s);

            else
                ap_log_error(APLOG_MARK, APLOG_ERR, s,
                             "httpauth: Couldn't write data to daemon");

            errno = 0;
            return -1;
        }
    }

    errno = 0;
    return 0;
}

int connect_socket(httpauth_context_t* ctx, request_rec* r)
{
    struct sockaddr_any sany;
    int ret = -1;

    disconnect_socket(ctx, r->server);

    if(sock_any_pton(ctx->socketname, &sany, DEFAULT_PORT) == -1)
    {
        ap_log_rerror(APLOG_MARK, APLOG_CRIT, r,
                      "httpauth: Invalid socket name or ip.");
        goto finally;
    }

    ctx->socket = ap_psocket(ctx->child_pool, SANY_TYPE(sany), SOCK_STREAM, 0);
    if(ctx->socket == -1)
    {
        ap_log_rerror(APLOG_MARK, APLOG_CRIT, r,
                      "httpauth: Can't create socket: %s", ctx->socketname);
        goto finally;
    }

    if(connect(ctx->socket, &SANY_ADDR(sany), SANY_LEN(sany)) != 0)
    {
        ap_log_rerror(APLOG_MARK, APLOG_CRIT, r,
                      "httpauth: Can't connect to httpauthd");
        goto finally;
    }

    ret = 0;

finally:
    if(ret == -1)
        disconnect_socket(ctx, r->server);

    errno = 0;
    return ret;
}

int connect_httpauth(httpauth_context_t* ctx, request_rec* r)
{
    int ret = -1;
    int code;
    char* details;
    const char* t;

    if(connect_socket(ctx, r) == -1)
        goto finally;

    if(read_response(ctx, r, &code, NULL, &details) == -1)
        goto finally;

    if(code != 100)
    {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                      "httpauth: protocol error (Expected 100, got %d)", code);
        goto finally;
    }

    /* Check theversion number */
    details = trim_space(details);

    if(strcmp(details, "HTTPAUTH/1.0") != 0)
    {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                      "httpauth: Daemon speaking incompatible protocol version: %s", details);
        goto finally;
    }

    /* Send our handler */
    if(ctx->handler)
    {
        t = ap_pstrcat(r->pool, "SET Handler ", ctx->handler, "\n", NULL);

        if(write_data(ctx, r->server, t) == -1)
            goto finally;

        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, r,
                      "httpauth: sent handler to daemon: %s", t);

        if(read_response(ctx, r, &code, NULL, NULL) == -1)
            goto finally;

        if(code != 202)
        {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                          "httpauth: protocol error (Expected 202, got %d)", code);
            goto finally;
        }
    }

    /* Send any setup info we have */
    if(ctx->domain)
    {
        t = ap_pstrcat(r->pool, "SET Domain ", ctx->domain, "\n", NULL);

        if(write_data(ctx, r->server, t) == -1)
            goto finally;

        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, r,
                      "httpauth: sent domains to daemon: %s", t);

        if(read_response(ctx, r, &code, NULL, NULL) == -1)
            goto finally;

        if(code != 202)
        {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                          "httpauth: protocol error (Expected 202, got %d)", code);
            goto finally;
        }
    }

    /* We're cool! */
    ret = 0;
    ap_log_rerror(APLOG_MARK, APLOG_INFO, r, "httpauth: connected to daemon");

finally:
    if(ret == -1)
        disconnect_socket(ctx, r->server);

    return ret;
}

/* Make sure our connection identifier is unique */
static void connection_gone (void *data)
{
    conn_current = NULL;
    conn_seen++;
}

int write_request(httpauth_context_t* ctx, request_rec* r)
{
    char pidid[40];
    char connid[40];
    int i, c = 0;
    const char* t;
    const array_header* hdrs_arr;
    const table_entry* elts;

    /* When the connection goes away, call our handler */
    if(conn_current != r->connection)
    {
        conn_current = r->connection;
        ap_register_cleanup(r->connection->pool, r,
                            connection_gone, ap_null_cleanup);
    }

    /* A unique per connection id */
    snprintf(connid, sizeof(connid), "0x%X-%X",
             (unsigned int)r->connection, conn_seen);
    connid[sizeof(connid) - 1] = 0;
    snprintf(pidid, sizeof(pidid), "%d", (unsigned int)getpid());
    pidid[sizeof(pidid) - 1] = 0;
    t = ap_pstrcat(r->pool, pidid, ":", connid, NULL);

    /* Send the request header to httpauthd */
    t = ap_pstrcat(r->pool, "AUTH ", t, " ", r->method,
                   " ", r->unparsed_uri, "\n", NULL);

    if(write_data(ctx, r->server, t) == -1)
        return -1;

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, r,
        "httpauth: sent auth request to daemon: %s", t);

    /* Now send the headers to httpauthd */

    hdrs_arr = ap_table_elts(r->headers_in);
    elts = (const table_entry*)hdrs_arr->elts;

    for(i = 0; i < hdrs_arr->nelts; i++)
    {
        if(!elts[i].val)
            continue;

        /* Filter out headers we don't want */
        if(strcasecmp(elts[i].key, r->proxyreq == STD_PROXY ?
                      "Proxy-Authorization" : "Authorization") == 0)
        {
            t = trim_start(elts[i].val);

            if(strncasecmp(t, AUTH_PREFIX_BASIC, strlen(AUTH_PREFIX_BASIC)) == 0 &&
               !(ctx->types & AUTH_TYPE_BASIC))
                continue;

            else if(strncasecmp(t, AUTH_PREFIX_DIGEST, strlen(AUTH_PREFIX_DIGEST)) == 0 &&
                    !(ctx->types & AUTH_TYPE_DIGEST))
                continue;

            /* Only allow unknown if we don't have it */
            else if(!(ctx->types & AUTH_TYPE_ANY))
                continue;

            /* Extra blank line when at end */
            t = ap_pstrcat(r->pool, "Authorization: ", elts[i].val, "\n", NULL);

            if(write_data(ctx, r->server, t) == -1)
                return SERVER_ERROR;

            c++;
        }
    }

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, r,
                  "httpauth: sent %d headers to daemon", c);

    return write_data(ctx, r->server, "\n");
}

static int httpauth_authenticate(request_rec* r)
{
    httpauth_context_t* ctx;
    const char* authtype;
    int code = 0;
    int ccode = 0;
    char* details = NULL;
    request_rec* mainreq;
    int retried = 0;

    /* Make sure it's for us */
    if(!(authtype = ap_auth_type(r)) || strcasecmp(HTTPAUTH_AUTHTYPE, authtype) != 0)
        return DECLINED;

    ctx = (httpauth_context_t*)ap_get_module_config(r->per_dir_config,
                                                  &httpauth_module);

    if(!ctx->socketname || !ctx->handler)
        return DECLINED;

    mainreq = r;

    while(mainreq->main != NULL)
        mainreq = mainreq->main;

    while(mainreq->prev != NULL)
        mainreq = mainreq->prev;

    /* Check if we've already authenticated this request */
    if(ap_get_module_config(mainreq->request_config, &httpauth_module))
        return OK;

/* For jumping to when a connection has been closed */
retry:

    if(ctx->socket == -1)
    {
        if(connect_httpauth(ctx, r) == -1)
            return SERVER_ERROR;
    }

    /* Make sure we're starting on a clean slate */
    read_junk(ctx, r);

    /* Send off a request */
    if(write_request(ctx, r) == -1 ||
	   read_response(ctx, r, &code, &ccode, &details) == -1)
    {
        /*
         * If our connection was closed by httpauthd then this
         * is where we get the error. Just do one retry to
         * try and reconnect. This happens often when restarting
         * httpauthd.
         */

        if(ctx->socket == -1 && !retried)
        {
			errno = 0;
        	ap_log_rerror(APLOG_MARK, APLOG_WARNING, r,
                		  "httpauth: reconnecting to to httpauthd");
            retried = 1;
            goto retry;
        }

		ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
					  "httpauth: couldn't send request to httpauthd");

        return HTTP_INTERNAL_SERVER_ERROR;
    }

    if(code != 200)
    {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                "httpauth: protocol error: unexpected code: %d", code);
        return SERVER_ERROR;
    }

    /* Copy over other headers */
    if(read_copy_headers(ctx, ccode, r) == -1)
        return SERVER_ERROR;

    if(ccode == 200)
    {
        ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
                "httpauth: successful authentication for user: %s", details);

        (char*)(r->connection->user) = ap_pstrdup(r->connection->pool, details);
        r->connection->ap_auth_type = HTTPAUTH_AUTHTYPE;

        /* Mark request as successfully authenticated */
        ap_set_module_config(r->request_config, &httpauth_module, details);
        return OK;
    }

    return ccode;
}

static int httpauth_access(request_rec *r)
{
    httpauth_context_t* ctx;
    const char *user = r->connection->user;
    const char* authtype;
    int m = r->method_number;
    int method_restricted = 0;
    register int x;
    const char *t, *w;
    const array_header *reqs_arr;
    require_line *reqs;

    ctx = (httpauth_context_t*)ap_get_module_config(r->per_dir_config,
                                                    &httpauth_module);

    /* Make sure it's for us */
    if(!(authtype = ap_auth_type(r)) || strcasecmp(HTTPAUTH_AUTHTYPE, authtype) != 0)
        return DECLINED;

    reqs_arr = ap_requires(r);

    /* If there is no "requires" directive, then any user will do. */
    if (!reqs_arr)
        return OK;
    reqs = (require_line*)reqs_arr->elts;

    for (x = 0; x < reqs_arr->nelts; x++)
    {
        if (!(reqs[x].method_mask & (1 << m)))
            continue;

        method_restricted = 1;

        t = reqs[x].requirement;
        w = ap_getword_white(r->pool, &t);
        if(!strcasecmp(w, "valid-user"))
            return OK;
        else if (!strcasecmp(w, "user"))
        {
            while (t[0])
            {
                w = ap_getword_conf(r->pool, &t);
                if(!strcmp(user, w))
                    return OK;
            }
        }
        else
        {
            ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
                          "Digest: access to %s failed, reason: unknown require "
                          "directive \"%s\"", r->uri, reqs[x].requirement);
            return DECLINED;
        }
    }

    if (!method_restricted)
        return OK;

    ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
                  "Digest: access to %s failed, reason: user %s not allowed access",
                  r->uri, user);

    return AUTH_REQUIRED;
}

/* Dispatch list for API hooks */
module MODULE_VAR_EXPORT httpauth_module =
{
    STANDARD_MODULE_STUFF,
    NULL,                    /* module initializer                  */
    httpauth_dir_config,     /* create per-dir    config structures */
    NULL,                    /* merge  per-dir    config structures */
    NULL,                    /* create per-server config structures */
    NULL,                    /* merge  per-server config structures */
    httpauth_cmds,           /* table of config file commands       */
    NULL,                    /* [#8] MIME-typed-dispatched handlers */
    NULL,                    /* [#1] URI to filename translation    */
    httpauth_authenticate,   /* [#4] validate user id from request  */
    httpauth_access,         /* [#5] check if the user is ok _here_ */
    NULL,                    /* [#3] check access by host address   */
    NULL,                    /* [#6] determine MIME type            */
    NULL,                    /* [#7] pre-run fixups                 */
    NULL,                    /* [#9] log a transaction              */
    NULL,                    /* [#2] header parser                  */
    NULL,                    /* child_init                          */
    NULL,                    /* child_exit                          */
    NULL                     /* [#0] post read-request              */
#ifdef EAPI
   ,NULL,                    /* EAPI: add_module                    */
    NULL,                    /* EAPI: remove_module                 */
    NULL,                    /* EAPI: rewrite_command               */
    NULL                     /* EAPI: new_connection                */
#endif
};

/*
 * Apache modules seem to want to be all in one
 * object file, at least when statically compiled.
 * so we include this here
 */
#include "../common/sock-any.c"
#include "../common/stringx.c"