lua_request.c 95.3 KB
Newer Older
powelld's avatar
powelld committed
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 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mod_lua.h"
#include "lua_apr.h"
#include "lua_dbd.h"
#include "lua_passwd.h"
#include "scoreboard.h"
#include "util_md5.h"
#include "util_script.h"
#include "util_varbuf.h"
#include "apr_date.h"
#include "apr_pools.h"
#include "apr_thread_mutex.h"
#include "apr_tables.h"
#include "util_cookies.h"

#define APR_WANT_BYTEFUNC
#include "apr_want.h"

extern apr_global_mutex_t* lua_ivm_mutex;
extern apr_shm_t *lua_ivm_shm;

APLOG_USE_MODULE(lua);
#define POST_MAX_VARS 500

#ifndef MODLUA_MAX_REG_MATCH
#define MODLUA_MAX_REG_MATCH 25
#endif

typedef char *(*req_field_string_f) (request_rec * r);
typedef int (*req_field_int_f) (request_rec * r);
typedef req_table_t *(*req_field_apr_table_f) (request_rec * r);


void ap_lua_rstack_dump(lua_State *L, request_rec *r, const char *msg)
{
    int i;
    int top = lua_gettop(L);
    ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01484) "Lua Stack Dump: [%s]", msg);
    for (i = 1; i <= top; i++) {
        int t = lua_type(L, i);
        switch (t) {
        case LUA_TSTRING:{
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(03001)
                              "%d:  '%s'", i, lua_tostring(L, i));
                break;
            }
        case LUA_TUSERDATA:{
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(03002)
                              "%d:  userdata", i);
                break;
            }
        case LUA_TLIGHTUSERDATA:{
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(03003)
                              "%d:  lightuserdata", i);
                break;
            }
        case LUA_TNIL:{
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(03004)
                              "%d:  NIL", i);
                break;
            }
        case LUA_TNONE:{
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(03005)
                              "%d:  None", i);
                break;
            }
        case LUA_TBOOLEAN:{
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(03006)
                              "%d:  %s", i,
                              lua_toboolean(L, i) ? "true" : "false");
                break;
            }
        case LUA_TNUMBER:{
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(03007)
                              "%d:  %g", i, lua_tonumber(L, i));
                break;
            }
        case LUA_TTABLE:{
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(03008)
                              "%d:  <table>", i);
                break;
            }
        case LUA_TFUNCTION:{
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(03009)
                              "%d:  <function>", i);
                break;
            }
        default:{
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(03010)
                              "%d:  unknown: -[%s]-", i, lua_typename(L, i));
                break;
            }
        }
    }
}

/**
 * Verify that the thing at index is a request_rec wrapping
 * userdata thingamajig and return it if it is. if it is not
 * lua will enter its error handling routine.
 */
static request_rec *ap_lua_check_request_rec(lua_State *L, int index)
{
    request_rec *r;
    luaL_checkudata(L, index, "Apache2.Request");
    r = (request_rec *) lua_unboxpointer(L, index);
    return r;
}

/* ------------------ request methods -------------------- */
/* helper callback for req_parseargs */
static int req_aprtable2luatable_cb(void *l, const char *key,
                                    const char *value)
{
    int t;
    lua_State *L = (lua_State *) l;     /* [table<s,t>, table<s,s>] */
    /* rstack_dump(L, RRR, "start of cb"); */
    /* L is [table<s,t>, table<s,s>] */
    /* build complex */

    lua_getfield(L, -1, key);   /* [VALUE, table<s,t>, table<s,s>] */
    /* rstack_dump(L, RRR, "after getfield"); */
    t = lua_type(L, -1);
    switch (t) {
    case LUA_TNIL:
    case LUA_TNONE:{
            lua_pop(L, 1);      /* [table<s,t>, table<s,s>] */
            lua_newtable(L);    /* [array, table<s,t>, table<s,s>] */
            lua_pushnumber(L, 1);       /* [1, array, table<s,t>, table<s,s>] */
            lua_pushstring(L, value);   /* [string, 1, array, table<s,t>, table<s,s>] */
            lua_settable(L, -3);        /* [array, table<s,t>, table<s,s>]  */
            lua_setfield(L, -2, key);   /* [table<s,t>, table<s,s>] */
            break;
        }
    case LUA_TTABLE:{
            /* [array, table<s,t>, table<s,s>] */
            int size = lua_rawlen(L, -1);
            lua_pushnumber(L, size + 1);        /* [#, array, table<s,t>, table<s,s>] */
            lua_pushstring(L, value);   /* [string, #, array, table<s,t>, table<s,s>] */
            lua_settable(L, -3);        /* [array, table<s,t>, table<s,s>] */
            lua_setfield(L, -2, key);   /* [table<s,t>, table<s,s>] */
            break;
        }
    }

    /* L is [table<s,t>, table<s,s>] */
    /* build simple */
    lua_getfield(L, -2, key);   /* [VALUE, table<s,s>, table<s,t>] */
    if (lua_isnoneornil(L, -1)) {       /* only set if not already set */
        lua_pop(L, 1);          /* [table<s,s>, table<s,t>]] */
        lua_pushstring(L, value);       /* [string, table<s,s>, table<s,t>] */
        lua_setfield(L, -3, key);       /* [table<s,s>, table<s,t>]  */
    }
    else {
        lua_pop(L, 1);
    }
    return 1;
}

/* helper callback for req_parseargs */
static int req_aprtable2luatable_cb_len(void *l, const char *key,
                                    const char *value, size_t len)
{
    int t;
    lua_State *L = (lua_State *) l;     /* [table<s,t>, table<s,s>] */
    /* rstack_dump(L, RRR, "start of cb"); */
    /* L is [table<s,t>, table<s,s>] */
    /* build complex */

    lua_getfield(L, -1, key);   /* [VALUE, table<s,t>, table<s,s>] */
    /* rstack_dump(L, RRR, "after getfield"); */
    t = lua_type(L, -1);
    switch (t) {
    case LUA_TNIL:
    case LUA_TNONE:{
            lua_pop(L, 1);      /* [table<s,t>, table<s,s>] */
            lua_newtable(L);    /* [array, table<s,t>, table<s,s>] */
            lua_pushnumber(L, 1);       /* [1, array, table<s,t>, table<s,s>] */
            lua_pushlstring(L, value, len);   /* [string, 1, array, table<s,t>, table<s,s>] */
            lua_settable(L, -3);        /* [array, table<s,t>, table<s,s>]  */
            lua_setfield(L, -2, key);   /* [table<s,t>, table<s,s>] */
            break;
        }
    
    case LUA_TTABLE:{
            /* [array, table<s,t>, table<s,s>] */
            int size = lua_rawlen(L, -1);
            lua_pushnumber(L, size + 1);        /* [#, array, table<s,t>, table<s,s>] */
            lua_pushlstring(L, value, len);   /* [string, #, array, table<s,t>, table<s,s>] */
            lua_settable(L, -3);        /* [array, table<s,t>, table<s,s>] */
            lua_setfield(L, -2, key);   /* [table<s,t>, table<s,s>] */
            break;
        }
    }

    /* L is [table<s,t>, table<s,s>] */
    /* build simple */
    lua_getfield(L, -2, key);   /* [VALUE, table<s,s>, table<s,t>] */
    if (lua_isnoneornil(L, -1)) {       /* only set if not already set */
        lua_pop(L, 1);          /* [table<s,s>, table<s,t>]] */
        lua_pushlstring(L, value, len);       /* [string, table<s,s>, table<s,t>] */
        lua_setfield(L, -3, key);       /* [table<s,s>, table<s,t>]  */
    }
    else {
        lua_pop(L, 1);
    }
    return 1;
}


/*
 =======================================================================================================================
    lua_read_body(request_rec *r, const char **rbuf, apr_off_t *size): Reads any additional form data sent in POST/PUT
    requests. Used for multipart POST data.
 =======================================================================================================================
 */
static int lua_read_body(request_rec *r, const char **rbuf, apr_off_t *size,
        apr_off_t maxsize)
{
    int rc = OK;

    if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) {
        return (rc);
    }
    if (ap_should_client_block(r)) {

        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
        char         argsbuffer[HUGE_STRING_LEN];
        apr_off_t    rsize, len_read, rpos = 0;
        apr_off_t length = r->remaining;
        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

        if (maxsize != 0 && length > maxsize) {
            return APR_EINCOMPLETE; /* Only room for incomplete data chunk :( */
        }
        *rbuf = (const char *) apr_pcalloc(r->pool, (apr_size_t) (length + 1));
        *size = length;
        while ((len_read = ap_get_client_block(r, argsbuffer, sizeof(argsbuffer))) > 0) {
            if ((rpos + len_read) > length) {
                rsize = length - rpos;
            }
            else {
                rsize = len_read;
            }

            memcpy((char *) *rbuf + rpos, argsbuffer, (size_t) rsize);
            rpos += rsize;
        }
    }

    return (rc);
}


/*
 * =======================================================================================================================
 * lua_write_body: Reads any additional form data sent in POST/PUT requests
 * and writes to a file.
 * =======================================================================================================================
 */
static apr_status_t lua_write_body(request_rec *r, apr_file_t *file, apr_off_t *size)
{
    apr_status_t rc = OK;

    if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
        return rc;
    if (ap_should_client_block(r)) {
        char argsbuffer[HUGE_STRING_LEN];
        apr_off_t rsize,
                  len_read,
                  rpos = 0;
        apr_off_t length = r->remaining;

        *size = length;
        while ((len_read =
                    ap_get_client_block(r, argsbuffer,
                                        sizeof(argsbuffer))) > 0) {
            if ((rpos + len_read) > length)
                rsize = (apr_size_t) length - rpos;
            else
                rsize = len_read;

            rc = apr_file_write_full(file, argsbuffer, (apr_size_t) rsize,
                                     NULL);
            if (rc != APR_SUCCESS)
                return rc;
            rpos += rsize;
        }
    }

    return rc;
}

/* r:parseargs() returning a lua table */
static int req_parseargs(lua_State *L)
{
    apr_table_t *form_table;
    request_rec *r = ap_lua_check_request_rec(L, 1);
    lua_newtable(L);
    lua_newtable(L);            /* [table, table] */
    ap_args_to_table(r, &form_table);
    apr_table_do(req_aprtable2luatable_cb, L, form_table, NULL);
    return 2;                   /* [table<string, string>, table<string, array<string>>] */
}

/* ap_lua_binstrstr: Binary strstr function for uploaded data with NULL bytes */
static char* ap_lua_binstrstr (const char * haystack, size_t hsize, const char* needle, size_t nsize)
{
    size_t p;
    if (haystack == NULL) return NULL;
    if (needle == NULL) return NULL;
    if (hsize < nsize) return NULL;
    for (p = 0; p <= (hsize - nsize); ++p) {
        if (memcmp(haystack + p, needle, nsize) == 0) {
            return (char*) (haystack + p);
        }
    }
    return NULL;
} 

/* r:parsebody(): Parses regular (url-enocded) or multipart POST data and returns two tables*/
static int req_parsebody(lua_State *L)
{
    apr_array_header_t          *pairs;
    apr_off_t len;
    int res;
    apr_size_t size;
    apr_size_t max_post_size;
    char *multipart;
    const char *contentType;
    request_rec *r = ap_lua_check_request_rec(L, 1);
    max_post_size = (apr_size_t) luaL_optinteger(L, 2, MAX_STRING_LEN);
    multipart = apr_pcalloc(r->pool, 256);
    contentType = apr_table_get(r->headers_in, "Content-Type");
    lua_newtable(L);
    lua_newtable(L);            /* [table, table] */    
    if (contentType != NULL && (sscanf(contentType, "multipart/form-data; boundary=%250c", multipart) == 1)) {
        char        *buffer, *key, *filename;
        char        *start = 0, *end = 0, *crlf = 0;
        const char  *data;
        int         i;
        size_t      vlen = 0;
        size_t      len = 0;
        if (lua_read_body(r, &data, (apr_off_t*) &size, max_post_size) != OK) {
            return 2;
        }
        len = strlen(multipart);
        i = 0;
        for
        (
            start = strstr((char *) data, multipart);
            start != NULL;
            start = end
        ) {
            i++;
            if (i == POST_MAX_VARS) break;
            crlf = strstr((char *) start, "\r\n\r\n");
            if (!crlf) break;
            end = ap_lua_binstrstr(crlf, (size - (crlf - data)), multipart, len);
            if (end == NULL) break;
            key = (char *) apr_pcalloc(r->pool, 256);
            filename = (char *) apr_pcalloc(r->pool, 256);
            vlen = end - crlf - 8;
            buffer = (char *) apr_pcalloc(r->pool, vlen+1);
            memcpy(buffer, crlf + 4, vlen);
            sscanf(start + len + 2,
                "Content-Disposition: form-data; name=\"%255[^\"]\"; filename=\"%255[^\"]\"",
                key, filename);
            if (*key) {
                req_aprtable2luatable_cb_len(L, key, buffer, vlen);
            }
        }
    }
    else {
        char *buffer;
        res = ap_parse_form_data(r, NULL, &pairs, -1, max_post_size);
        if (res == OK) {
            while(pairs && !apr_is_empty_array(pairs)) {
                ap_form_pair_t *pair = (ap_form_pair_t *) apr_array_pop(pairs);
                apr_brigade_length(pair->value, 1, &len);
                size = (apr_size_t) len;
                buffer = apr_palloc(r->pool, size + 1);
                apr_brigade_flatten(pair->value, buffer, &size);
                buffer[len] = 0;
                req_aprtable2luatable_cb(L, pair->name, buffer);
            }
        }
    }
    return 2;                   /* [table<string, string>, table<string, array<string>>] */
}


/*
 * lua_ap_requestbody; r:requestbody([filename]) - Reads or stores the request
 * body
 */
static int lua_ap_requestbody(lua_State *L)
{
    const char     *filename;
    request_rec    *r;
    apr_off_t      maxSize;
    
    r = ap_lua_check_request_rec(L, 1);
    filename = luaL_optstring(L, 2, 0);
    maxSize = (apr_off_t)luaL_optinteger(L, 3, 0);

    if (r) {
        apr_off_t size;
        if (maxSize > 0 && r->remaining > maxSize) {
            lua_pushnil(L);
            lua_pushliteral(L, "Request body was larger than the permitted size.");
            return 2;
        }
        if (r->method_number != M_POST && r->method_number != M_PUT)
            return (0);
        if (!filename) {
            const char     *data;

            if (lua_read_body(r, &data, &size, maxSize) != OK)
                return (0);

            lua_pushlstring(L, data, (size_t) size);
            lua_pushinteger(L, (lua_Integer) size);
            return (2);
        } else {
            apr_status_t rc;
            apr_file_t     *file;

            rc = apr_file_open(&file, filename, APR_CREATE | APR_FOPEN_WRITE,
                               APR_FPROT_OS_DEFAULT, r->pool);
            lua_settop(L, 0);
            if (rc == APR_SUCCESS) {
                rc = lua_write_body(r, file, &size);
                apr_file_close(file);
                if (rc != OK) {
                    lua_pushboolean(L, 0);
                    return 1;
                }
                lua_pushinteger(L, (lua_Integer) size);
                return (1);
            } else
                lua_pushboolean(L, 0);
            return (1);
        }
    }

    return (0);
}

/* wrap ap_rputs as r:puts(String) */
static int req_puts(lua_State *L)
{
    request_rec *r = ap_lua_check_request_rec(L, 1);

    int argc = lua_gettop(L);
    int i;

    for (i = 2; i <= argc; i++) {
        ap_rputs(luaL_checkstring(L, i), r);
    }
    return 0;
}

/* wrap ap_rwrite as r:write(String) */
static int req_write(lua_State *L)
{
    request_rec *r = ap_lua_check_request_rec(L, 1);
    size_t n;
    int rv;
    const char *buf = luaL_checklstring(L, 2, &n);

    rv = ap_rwrite((void *) buf, n, r);
    lua_pushinteger(L, rv);
    return 1;
}

/* r:addoutputfilter(name|function) */
static int req_add_output_filter(lua_State *L)
{
    request_rec *r = ap_lua_check_request_rec(L, 1);
    const char *name = luaL_checkstring(L, 2);
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01485) "adding output filter %s",
                  name);
    ap_add_output_filter(name, L, r, r->connection);
    return 0;
}

/* wrap ap_construct_url as r:construct_url(String) */
static int req_construct_url(lua_State *L)
{
    request_rec *r = ap_lua_check_request_rec(L, 1);
    const char *name = luaL_checkstring(L, 2);
    lua_pushstring(L, ap_construct_url(r->pool, name, r));
    return 1;
}

/* wrap ap_escape_html r:escape_html(String) */
static int req_escape_html(lua_State *L)
{
    request_rec *r = ap_lua_check_request_rec(L, 1);
    const char *s = luaL_checkstring(L, 2);
    lua_pushstring(L, ap_escape_html(r->pool, s));
    return 1;
}

/* wrap optional ssl_var_lookup as  r:ssl_var_lookup(String) */
static int req_ssl_var_lookup(lua_State *L)
{
    request_rec *r = ap_lua_check_request_rec(L, 1);
    const char *s = luaL_checkstring(L, 2);
    const char *res = ap_lua_ssl_val(r->pool, r->server, r->connection, r, 
                                     (char *)s);
    lua_pushstring(L, res);
    return 1;
}

/* BEGIN dispatch mathods for request_rec fields */

/* not really a field, but we treat it like one */
static const char *req_document_root(request_rec *r)
{
    return ap_document_root(r);
}

static const char *req_context_prefix(request_rec *r)
{
    return ap_context_prefix(r);
}

static const char *req_context_document_root(request_rec *r)
{
    return ap_context_document_root(r);
}

static char *req_uri_field(request_rec *r)
{
    return r->uri;
}

static const char *req_method_field(request_rec *r)
{
    return r->method;
}
static const char *req_handler_field(request_rec *r)
{
    return r->handler;
}
static const char *req_proxyreq_field(request_rec *r)
{
    switch (r->proxyreq) {
        case PROXYREQ_NONE:     return "PROXYREQ_NONE";
        case PROXYREQ_PROXY:    return "PROXYREQ_PROXY";
        case PROXYREQ_REVERSE:  return "PROXYREQ_REVERSE";
        case PROXYREQ_RESPONSE: return "PROXYREQ_RESPONSE";
        default: return NULL;
    }
}
static const char *req_hostname_field(request_rec *r)
{
    return r->hostname;
}

static const char *req_args_field(request_rec *r)
{
    return r->args;
}

static const char *req_path_info_field(request_rec *r)
{
    return r->path_info;
}

static const char *req_canonical_filename_field(request_rec *r)
{
    return r->canonical_filename;
}

static const char *req_filename_field(request_rec *r)
{
    return r->filename;
}

static const char *req_user_field(request_rec *r)
{
    return r->user;
}

static const char *req_unparsed_uri_field(request_rec *r)
{
    return r->unparsed_uri;
}

static const char *req_ap_auth_type_field(request_rec *r)
{
    return r->ap_auth_type;
}

static const char *req_content_encoding_field(request_rec *r)
{
    return r->content_encoding;
}

static const char *req_content_type_field(request_rec *r)
{
    return r->content_type;
}

static const char *req_range_field(request_rec *r)
{
    return r->range;
}

static const char *req_protocol_field(request_rec *r)
{
    return r->protocol;
}

static const char *req_the_request_field(request_rec *r)
{
    return r->the_request;
}

static const char *req_log_id_field(request_rec *r)
{
    return r->log_id;
}

static const char *req_useragent_ip_field(request_rec *r)
{
    return r->useragent_ip;
}

static int req_remaining_field(request_rec *r)
{
    return r->remaining;
}

static int req_status_field(request_rec *r)
{
    return r->status;
}

static int req_assbackwards_field(request_rec *r)
{
    return r->assbackwards;
}

static req_table_t* req_headers_in(request_rec *r)
{
  req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
  t->r = r;
  t->t = r->headers_in;
  t->n = "headers_in";
  return t;
}

static req_table_t* req_headers_out(request_rec *r)
{
  req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
  t->r = r;
  t->t = r->headers_out;
  t->n = "headers_out";
  return t;
}

static req_table_t* req_err_headers_out(request_rec *r)
{
  req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
  t->r = r;
  t->t = r->err_headers_out;
  t->n = "err_headers_out";
  return t;
}

static req_table_t* req_subprocess_env(request_rec *r)
{
  req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
  t->r = r;
  t->t = r->subprocess_env;
  t->n = "subprocess_env";
  return t;
}

static req_table_t* req_notes(request_rec *r)
{
  req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
  t->r = r;
  t->t = r->notes;
  t->n = "notes";
  return t;
}

static int req_ssl_is_https_field(request_rec *r)
{
    return ap_lua_ssl_is_https(r->connection);
}

static int req_ap_get_server_port(request_rec *r)
{
    return (int) ap_get_server_port(r);
}

static int lua_ap_rflush (lua_State *L) {

    int returnValue;
    request_rec *r;
    luaL_checktype(L, 1, LUA_TUSERDATA);
    r = ap_lua_check_request_rec(L, 1);
    returnValue = ap_rflush(r);
    lua_pushboolean(L, (returnValue == 0));
    return 1;
}


static const char* lua_ap_options(request_rec* r) 
{
    int opts;
    opts = ap_allow_options(r);
    return apr_psprintf(r->pool, "%s %s %s %s %s %s", (opts&OPT_INDEXES) ? "Indexes" : "", (opts&OPT_INCLUDES) ? "Includes" : "", (opts&OPT_SYM_LINKS) ? "FollowSymLinks" : "", (opts&OPT_EXECCGI) ? "ExecCGI" : "", (opts&OPT_MULTI) ? "MultiViews" : "", (opts&OPT_ALL) == OPT_ALL ? "All" : "" );
}

static const char* lua_ap_allowoverrides(request_rec* r) 
{
    int opts;
    opts = ap_allow_overrides(r);
    if ( (opts & OR_ALL) == OR_ALL) {
        return "All";
    }
    else if (opts == OR_NONE) {
        return "None";
    }
    return apr_psprintf(r->pool, "%s %s %s %s %s", (opts & OR_LIMIT) ? "Limit" : "", (opts & OR_OPTIONS) ? "Options" : "", (opts & OR_FILEINFO) ? "FileInfo" : "", (opts & OR_AUTHCFG) ? "AuthCfg" : "", (opts & OR_INDEXES) ? "Indexes" : "" );
    
}

static int lua_ap_started(request_rec* r) 
{
    return (int)(ap_scoreboard_image->global->restart_time / 1000000);
}

static const char* lua_ap_basic_auth_pw(request_rec* r) 
{
    const char* pw = NULL;
    ap_get_basic_auth_pw(r, &pw);
    return pw ? pw : "";
}

static int lua_ap_limit_req_body(request_rec* r) 
{
    return (int) ap_get_limit_req_body(r);
}

static int lua_ap_is_initial_req(request_rec *r)
{
    return ap_is_initial_req(r);
}

static int lua_ap_some_auth_required(request_rec *r)
{
    return ap_some_auth_required(r);
}

static int lua_ap_sendfile(lua_State *L)
{

    apr_finfo_t file_info;
    const char  *filename;
    request_rec *r;

    luaL_checktype(L, 1, LUA_TUSERDATA);
    luaL_checktype(L, 2, LUA_TSTRING);
    r = ap_lua_check_request_rec(L, 1);
    filename = lua_tostring(L, 2);
    apr_stat(&file_info, filename, APR_FINFO_MIN, r->pool);
    if (file_info.filetype == APR_NOFILE || file_info.filetype == APR_DIR) {
        lua_pushboolean(L, 0);
    }
    else {
        apr_size_t      sent;
        apr_status_t    rc;
        apr_file_t      *file;

        rc = apr_file_open(&file, filename, APR_READ, APR_OS_DEFAULT,
                            r->pool);
        if (rc == APR_SUCCESS) {
            ap_send_fd(file, r, 0, (apr_size_t)file_info.size, &sent);
            apr_file_close(file);
            lua_pushinteger(L, sent);
        }
        else {
            lua_pushboolean(L, 0);
        }
    }

    return (1);
}


/*
 * lua_apr_b64encode; r:encode_base64(string) - encodes a string to Base64
 * format
 */
static int lua_apr_b64encode(lua_State *L)
{
    const char     *plain;
    char           *encoded;
    size_t          plain_len, encoded_len;
    request_rec    *r;

    r = ap_lua_check_request_rec(L, 1);
    luaL_checktype(L, 2, LUA_TSTRING);
    plain = lua_tolstring(L, 2, &plain_len);
    encoded_len = apr_base64_encode_len(plain_len);
    if (encoded_len) {
        encoded = apr_palloc(r->pool, encoded_len);
        encoded_len = apr_base64_encode(encoded, plain, plain_len);
        if (encoded_len > 0 && encoded[encoded_len - 1] == '\0')
            encoded_len--; 
        lua_pushlstring(L, encoded, encoded_len);
        return 1;
    }
    return 0;
}

/*
 * lua_apr_b64decode; r:decode_base64(string) - decodes a Base64 string
 */
static int lua_apr_b64decode(lua_State *L)
{
    const char     *encoded;
    char           *plain;
    size_t          encoded_len, decoded_len;
    request_rec    *r;

    r = ap_lua_check_request_rec(L, 1);
    luaL_checktype(L, 2, LUA_TSTRING);
    encoded = lua_tolstring(L, 2, &encoded_len);
    decoded_len = apr_base64_decode_len(encoded);
    if (decoded_len) {
        plain = apr_palloc(r->pool, decoded_len);
        decoded_len = apr_base64_decode(plain, encoded);
        if (decoded_len > 0 && plain[decoded_len - 1] == '\0')
            decoded_len--; 
        lua_pushlstring(L, plain, decoded_len);
        return 1;
    }
    return 0;
}

/*
 * lua_ap_unescape; r:unescape(string) - Unescapes an URL-encoded string
 */
static int lua_ap_unescape(lua_State *L)
{
    const char     *escaped;
    char           *plain;
    size_t x,
           y;
    request_rec    *r;
    r = ap_lua_check_request_rec(L, 1);
    luaL_checktype(L, 2, LUA_TSTRING);
    escaped = lua_tolstring(L, 2, &x);
    plain = apr_pstrdup(r->pool, escaped);
    y = ap_unescape_urlencoded(plain);
    if (!y) {
        lua_pushstring(L, plain);
        return 1;
    }
    return 0;
}

/*
 * lua_ap_escape; r:escape(string) - URL-escapes a string
 */
static int lua_ap_escape(lua_State *L)
{
    const char     *plain;
    char           *escaped;
    size_t x;
    request_rec    *r;
    r = ap_lua_check_request_rec(L, 1);
    luaL_checktype(L, 2, LUA_TSTRING);
    plain = lua_tolstring(L, 2, &x);
    escaped = ap_escape_urlencoded(r->pool, plain);
    lua_pushstring(L, escaped);
    return 1;
}

/*
 * lua_apr_md5; r:md5(string) - Calculates an MD5 digest of a string
 */
static int lua_apr_md5(lua_State *L)
{
    const char     *buffer;
    char           *result;
    size_t len;
    request_rec    *r;

    r = ap_lua_check_request_rec(L, 1);
    luaL_checktype(L, 2, LUA_TSTRING);
    buffer = lua_tolstring(L, 2, &len);
    result = ap_md5_binary(r->pool, (const unsigned char *)buffer, len);
    lua_pushstring(L, result);
    return 1;
}

/*
 * lua_apr_sha1; r:sha1(string) - Calculates the SHA1 digest of a string
 */
static int lua_apr_sha1(lua_State *L)
{
    unsigned char digest[APR_SHA1_DIGESTSIZE];
    apr_sha1_ctx_t sha1;
    const char     *buffer;
    char           *result;
    size_t len;
    request_rec    *r;

    r = ap_lua_check_request_rec(L, 1);
    luaL_checktype(L, 2, LUA_TSTRING);
    result = apr_pcalloc(r->pool, sizeof(digest) * 2 + 1);
    buffer = lua_tolstring(L, 2, &len);
    apr_sha1_init(&sha1);
    apr_sha1_update(&sha1, buffer, len);
    apr_sha1_final(digest, &sha1);
    
    ap_bin2hex(digest, sizeof(digest), result);
    lua_pushstring(L, result);
    return 1;
}

/*
 * lua_apr_htpassword; r:htpassword(string [, algorithm [, cost]]) - Creates
 * a htpassword hash from a string
 */
static int lua_apr_htpassword(lua_State *L)
{
    passwd_ctx     ctx = { 0 };
    request_rec    *r;

    r = ap_lua_check_request_rec(L, 1);
    luaL_checktype(L, 2, LUA_TSTRING);
    ctx.passwd = apr_pstrdup(r->pool, lua_tostring(L, 2));
    ctx.alg = luaL_optinteger(L, 3, ALG_APMD5);
    ctx.cost = luaL_optinteger(L, 4, 0);
    ctx.pool = r->pool;
    ctx.out = apr_pcalloc(r->pool, MAX_PASSWD_LEN);
    ctx.out_len = MAX_PASSWD_LEN;
    if (mk_password_hash(&ctx)) {
        lua_pushboolean(L, 0);
        lua_pushstring(L, ctx.errstr);
        return 2;
    } else {
        lua_pushstring(L, ctx.out);
    }
    return 1;
}

/*
 * lua_apr_touch; r:touch(string [, time]) - Sets mtime of a file
 */
static int lua_apr_touch(lua_State *L)
{
    request_rec     *r;
    const char      *path;
    apr_status_t    status;
    apr_time_t      mtime;

    r = ap_lua_check_request_rec(L, 1);
    luaL_checktype(L, 2, LUA_TSTRING);
    path = lua_tostring(L, 2);
    mtime = (apr_time_t)luaL_optnumber(L, 3, (lua_Number)apr_time_now());
    status = apr_file_mtime_set(path, mtime, r->pool);
    lua_pushboolean(L, (status == 0));
    return 1;
}

/*
 * lua_apr_mkdir; r:mkdir(string [, permissions]) - Creates a directory
 */
static int lua_apr_mkdir(lua_State *L)
{
    request_rec     *r;
    const char      *path;