summaryrefslogtreecommitdiffstats
path: root/hw4/chttpd/chttpd-conn.c
blob: 538f079ecfb73f76c20da634d6dddbe11d3aadac (plain) (blame)
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
/* b01902062 藍挺瑋 */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#define CHTTPD_SERVER_ENABLE_ERRMSG

#include "chttpd-conn.h"
#include "chttpd-log.h"
#include "chttpd-server.h"
#include <l4array.h>
#include <l4strv.h>
#include <l4list.h>
#include <l4str.h>
#include <l4posix.h>

#include <ctype.h>
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#define NL "\015\012"

enum {
    HTTP_STATUS_200_OK,
    HTTP_STATUS_400_BAD_REQUEST,
    HTTP_STATUS_404_NOT_FOUND,
    HTTP_STATUS_500_INTERNAL_SERVER_ERROR
};

static char* http_status_hdr[] = {
    [HTTP_STATUS_200_OK] = "HTTP/1.1 200 OK" NL,
    [HTTP_STATUS_400_BAD_REQUEST] = "HTTP/1.1 400 Bad Request" NL,
    [HTTP_STATUS_404_NOT_FOUND] = "HTTP/1.1 404 Not Found" NL,
    [HTTP_STATUS_500_INTERNAL_SERVER_ERROR] = "HTTP/1.1 500 Internal Server Error" NL
};

static char* http_status_msg[] = {
    [HTTP_STATUS_400_BAD_REQUEST] =
        "\n<html><head><title>400 Bad Request</title></head>" NL
        "<body><p>You browser sent a broken HTTP request." NL
        "<a href=\"http://tools.ietf.org/search/rfc2616#section-10.4.1\">"
        "[400]</a></p>"
        "</body></html>" NL
};

static inline void http_status_write (int connfd, int status_enum) {
    lbs_posix_write_all (connfd, http_status_hdr[status_enum], 0);
    lbs_posix_write_all (connfd, NL, 2);
    lbs_posix_write_all (connfd, http_status_msg[status_enum], 0);
}

#define CHTTPD_CONN_THREAD_INIT \
    ChttpdConn* conn = ptr_to_ChttpdConn; \
    ChttpdServer* server = conn->server; \
    ChttpdLog* hlog = conn->hlog; \
    unsigned long long id = conn->id; \
    int connfd = conn->connfd; \
    pthread_sigmask (SIG_SETMASK, &server->conn_mask, NULL);
    
#define CHTTPD_CONN_THREAD_DESTROY \
    chttpd_log_write (hlog, "[%4llu] terminated", conn->id); \
    pthread_rwlock_wrlock (&server->lock); \
    lbs_list_remove (server->conn, conn->conn_node); \
    pthread_rwlock_unlock (&server->lock); \
    return NULL

static inline char* internal_memstr (const void* haystack,
    size_t haystacklen, const char* needle) {

    const char* haychar = haystack;
    bool matched;

    for (size_t i = 0; i < haystacklen; i++, haychar++) {
        matched = true;
        for (size_t j = 0; needle[j] != '\0'; j++) {
            if (i + j >= haystacklen || haychar[j] != needle[j]) {
                matched = false;
                break;
            }
        }
        if (matched) {
            return (char*)haychar;
        }
    }

    return NULL;
}

#define ERRLEN 256
void* chttpd_conn_admin (void* ptr_to_ChttpdConn) {
    CHTTPD_CONN_THREAD_INIT;

    chttpd_log_write (hlog, "[%4llu] sorry, function not implemented", id);
    chttpd_log_write (hlog, "[%4llu] fd is %d", connfd);

    CHTTPD_CONN_THREAD_DESTROY;
}

void* chttpd_conn_http (void* ptr_to_ChttpdConn) {
    CHTTPD_CONN_THREAD_INIT;

    const char hdr_delim[] = "\015\012\015\012";
    _Static_assert (LBS_STR_STATIC_STRLEN (hdr_delim) == 4,
        "HTTP header delimiter length must be 4 bytes!");

    const char line_delim[] = "\015\012";
    _Static_assert (LBS_STR_STATIC_STRLEN (line_delim) == 2,
        "HTTP line delimiter length must be 2bytes!");

    char errmsg[ERRLEN];
    LbsArray* hdr_buf = lbs_array_new (sizeof (char));
    LbsArray* out_buf = lbs_array_new (sizeof (char));
    size_t data_offset;

    while (true) {
        ssize_t r = read (connfd, conn->buf, CHTTPD_CONN_BUF_SIZE);
        if (r < 0) {
            if (errno == EINTR || errno == EAGAIN) {
                continue;
            }
            chttpd_log_write (hlog, "[%4llu] incomplete header: read: %s",
                id, get_errmsg (errno, errmsg, ERRLEN));
            goto http_exit;
        } else if (r == 0) {
            chttpd_log_write (hlog, "[%4llu] incomplete header: premature EOF",
                id);
            goto http_exit;
        }

        const char* hdr_end = internal_memstr (conn->buf, r, hdr_delim);
        if (hdr_end != NULL) {
            data_offset = hdr_end - conn->buf;
            lbs_array_append_mass (hdr_buf, conn->buf, data_offset);
            lbs_array_append_data (hdr_buf, &(char){ '\0' });
            data_offset += 4;
            break;
        } else {
            lbs_array_append_mass (hdr_buf, conn->buf, r);
        }
    }

    char* method_start = hdr_buf->data;
    char* hdr_start = internal_memstr (hdr_buf->data, hdr_buf->len, line_delim);
    if (hdr_start != NULL) {
        *hdr_start = '\0';
        hdr_start += 2;
    }
    chttpd_log_write (hlog, "[%4llu] client request: %s", id, method_start);

    /* Parse method line */
    char* tokstore;
    char* ma1 = strtok_r (method_start, " \t", &tokstore);
    if (ma1 == NULL) {
        chttpd_log_write (hlog, "[%4llu] 400 Bad Request: URL not found", id);
        http_status_write (connfd, HTTP_STATUS_400_BAD_REQUEST);
        goto http_exit;
    }
    char* ma2 = strtok_r (NULL, " \t", &tokstore);
    if (ma2 == NULL) {
        chttpd_log_write (hlog, "[%4llu] 400 Bad Request: What?", id);
        http_status_write (connfd, HTTP_STATUS_400_BAD_REQUEST);
        goto http_exit;
    } else {
        if (*ma2 != '/') {
            chttpd_log_write (hlog,
                "[%4llu] 400 Bad Request: URL not started with /", id);
            http_status_write (connfd, HTTP_STATUS_400_BAD_REQUEST);
            goto http_exit;
        }
    }
    char* ma3 = strtok_r (NULL, " \t", &tokstore);

    char* request_method = ma1;
    char* request_uri = ma2 + 1;
    char* server_protocol = (ma3 == NULL) ? "" : ma3;
    char* query_string = strtok_r (request_uri, "?", &tokstore);
    query_string = (query_string == NULL) ? "" : query_string;

#ifdef SPHW_RESTRICTION
    for (char* p = request_uri; *p != '\0'; p++) {
        if (!(*p == '_' || isalnum (*p))) {
            chttpd_log_write (hlog, "[%4llu] 400 Bad Request: character"
                " `%c\' in request URI is not allowed", id, *p);
            http_status_write (connfd, HTTP_STATUS_400_BAD_REQUEST);
            goto http_exit;
        }
    }
    for (char* p = query_string; *p != '\0'; p++) {
        if (!(*p == '_' || *p == '=' || *p == '&' || isalnum (*p))) {
            chttpd_log_write (hlog, "[%4llu] 400 Bad Request: character"
                " `%c\' in query string is not allowed", id, *p);
            http_status_write (connfd, HTTP_STATUS_400_BAD_REQUEST);
            goto http_exit;
        }
    }
#endif



http_exit:
    lbs_array_unref (hdr_buf);
    lbs_array_unref (out_buf);
    CHTTPD_CONN_THREAD_DESTROY;
}
#undef ERRLEN

void chttpd_conn_ctor (void* conn_generic, unsigned long long id, int connfd,
    ChttpdLog* hlog, ChttpdServer* server, LbsListMeta* slist) {

    ChttpdConn* conn = conn_generic;
    conn->id = id;
    conn->connfd = connfd;
    conn->hlog = chttpd_log_ref (hlog);
    conn->server = server;
    conn->slist = slist;
    pthread_rwlock_init (&conn->lock, NULL);
    conn->pid = -1;
}

void chttpd_conn_dtor (void* conn_generic) {
    ChttpdConn* conn = conn_generic;
    close (conn->connfd);
    chttpd_log_unref (conn->hlog);
    pthread_rwlock_wrlock (&conn->lock);
    pthread_rwlock_unlock (&conn->lock);
    pthread_rwlock_destroy (&conn->lock);
    free (conn);
}