aboutsummaryrefslogtreecommitdiff
path: root/src/routing.c
blob: 19102039d1c3c7716ae714fce564670078c590c9 (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
#include "../beaker.h"        
#include "beaker_globals.h"   
#include <stdio.h>            
#include <stdlib.h>           
#include <string.h>           
#include <sys/socket.h>       
#include <sys/stat.h>         
#include <unistd.h>           
#include <errno.h>

void set_handler(const char *path, RequestHandler handler) {

  if (handler_count < MAX_HANDLERS) {

    strncpy(handlers[handler_count].path, path, MAX_PATH_LEN - 1);
    handlers[handler_count].path[MAX_PATH_LEN - 1] = '\0';

    handlers[handler_count].handler = handler;

    handler_count++;
  } else {

    fprintf(stderr,
            "[WARNING] set_handler: Maximum number of handlers reached. Cannot register handler for '%s'.\n",
            path);
  }
}

const char *get_mime_type(const char *file_path) {

  const char *ext = strrchr(file_path, '.');
  if (!ext) {
    return "application/octet-stream"; 
  }
  ext++; 

  if (strcmp(ext, "html") == 0 || strcmp(ext, "htm") == 0)
    return "text/html";
  if (strcmp(ext, "css") == 0)
    return "text/css";
  if (strcmp(ext, "js") == 0)
    return "application/javascript";
  if (strcmp(ext, "json") == 0)
    return "application/json";
  if (strcmp(ext, "jpg") == 0 || strcmp(ext, "jpeg") == 0)
    return "image/jpeg";
  if (strcmp(ext, "png") == 0)
    return "image/png";
  if (strcmp(ext, "gif") == 0)
    return "image/gif";
  if (strcmp(ext, "ico") == 0)
    return "image/x-icon";
  if (strcmp(ext, "svg") == 0)
    return "image/svg+xml";
  if (strcmp(ext, "pdf") == 0)
    return "application/pdf";
  if (strcmp(ext, "txt") == 0)
    return "text/plain";

  return "application/octet-stream";
}

static int canonicalize_path(char *canonical, const char *path, size_t max_len) {
    char components[MAX_URL_PARAMS][MAX_KEY_LEN];
    int component_count = 0;

    char *path_copy = strdup(path);
    if (!path_copy) {
        return -1;
    }

    char *token = strtok(path_copy, "/");
    while (token) {
        if (strcmp(token, ".") == 0) {

        } else if (strcmp(token, "..") == 0) {

            if (component_count > 0) {
                component_count--;
            } else {

                fprintf(stderr, "[SECURITY] Path traversal attempt: %s\n", path);
                free(path_copy);
                return -1;
            }
        } else if (strlen(token) > 0) {

            if (component_count < MAX_URL_PARAMS) {
                strncpy(components[component_count], token, MAX_KEY_LEN - 1);
                components[component_count][MAX_KEY_LEN - 1] = '\0';
                component_count++;
            }
        }
        token = strtok(NULL, "/");
    }

    free(path_copy);

    canonical[0] = '\0';
    for (int i = 0; i < component_count; i++) {
        if (strlen(canonical) + strlen(components[i]) + 2 > max_len) {
            fprintf(stderr, "[ERROR] Canonical path too long\n");
            return -1;
        }
        strcat(canonical, "/");
        strcat(canonical, components[i]);
    }

    if (canonical[0] == '\0') {
        strcpy(canonical, "/");
    }

    return 0;
}

static bool is_safe_path_component(const char *component) {

    if (strstr(component, "..") ||
        strstr(component, "//") ||
        strchr(component, '\0') != component + strlen(component)) {
        return false;
    }

    for (size_t i = 0; component[i]; i++) {
        if (component[i] < 32 && component[i] != '\t') {
            return false;
        }
    }

    return true;
}

static int url_decode(char *dst, const char *src, size_t dst_size) {
    size_t i = 0, j = 0;

    while (src[i] && j < dst_size - 1) {
        if (src[i] == '%') {

            if (src[i+1] && src[i+2]) {
                char hex[3] = {src[i+1], src[i+2], '\0'};
                char *endptr;
                long value = strtol(hex, &endptr, 16);

                if (*endptr != '\0') {
                    fprintf(stderr, "[SECURITY] Invalid URL encoding: %%%s\n", hex);
                    return -1;
                }

                if (value == 0) {
                    fprintf(stderr, "[SECURITY] Null byte in URL encoding\n");
                    return -1;
                }

                dst[j++] = (char)value;
                i += 3;
            } else {
                fprintf(stderr, "[SECURITY] Incomplete URL encoding at end\n");
                return -1;
            }
        } else if (src[i] == '+') {

            dst[j++] = ' ';
            i++;
        } else {
            dst[j++] = src[i++];
        }
    }

    dst[j] = '\0';
    return 0;
}

char *parse_request_url(const char *request_line, UrlParams *params) {
    char method[16];
    char raw_path_with_query[MAX_PATH_LEN];
    char http_version[16];

    if (sscanf(request_line, "%15s %255s %15s", method, raw_path_with_query,
               http_version) != 3) {
        fprintf(stderr, "[ERROR] parse_request_url: Malformed request line\n");
        return NULL;
    }

    params->count = 0;

    char decoded_path[MAX_PATH_LEN];
    if (url_decode(decoded_path, raw_path_with_query, sizeof(decoded_path)) != 0) {
        fprintf(stderr, "[SECURITY] Invalid URL encoding in request\n");
        return NULL;
    }

    char *working_url_copy = strdup(decoded_path);
    if (!working_url_copy) {
        perror("Failed to allocate memory for URL copy");
        return NULL;
    }

    char *query_start = strchr(working_url_copy, '?');
    if (query_start) {
        *query_start = '\0';
    }

    char canonical_path[MAX_PATH_LEN];
    if (canonicalize_path(canonical_path, working_url_copy, sizeof(canonical_path)) != 0) {
        fprintf(stderr, "[SECURITY] Path canonicalization failed\n");
        free(working_url_copy);
        return NULL;
    }

    char *path_copy_for_validation = strdup(canonical_path);
    if (path_copy_for_validation) {
        char *token = strtok(path_copy_for_validation, "/");
        while (token) {
            if (!is_safe_path_component(token)) {
                fprintf(stderr, "[SECURITY] Unsafe path component: %s\n", token);
                free(path_copy_for_validation);
                free(working_url_copy);
                return NULL;
            }
            token = strtok(NULL, "/");
        }
        free(path_copy_for_validation);
    }

    if (query_start) {
        char *query_string = query_start + 1;
        char *token;
        char *saveptr;

        token = strtok_r(query_string, "&", &saveptr);
        while (token && params->count < MAX_URL_PARAMS) {
            char *equals = strchr(token, '=');
            if (equals) {
                size_t key_len = equals - token;

                char decoded_key[MAX_KEY_LEN];
                if (url_decode(decoded_key, token, key_len + 1) == 0) {
                    strncpy(params->params[params->count].key, decoded_key, MAX_KEY_LEN - 1);
                    params->params[params->count].key[MAX_KEY_LEN - 1] = '\0';

                    char decoded_value[MAX_VALUE_LEN];
                    if (url_decode(decoded_value, equals + 1, sizeof(decoded_value)) == 0) {
                        strncpy(params->params[params->count].value, decoded_value, MAX_VALUE_LEN - 1);
                        params->params[params->count].value[MAX_VALUE_LEN - 1] = '\0';
                        params->count++;
                    }
                }
            }
            token = strtok_r(NULL, "&", &saveptr);
        }
    }

    char *final_path = strdup(canonical_path);
    free(working_url_copy);
    return final_path;
}

bool serve_static_file(const char *request_path_relative_to_static) {
  char full_static_path[MAX_PATH_LEN]; 

  if (strstr(request_path_relative_to_static, "..") != NULL) {
    fprintf(stderr, "[SECURITY] Attempted directory traversal: %s\n",
            request_path_relative_to_static);

    const char *forbidden_response =
        "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n";
    send(current_client_socket, forbidden_response, strlen(forbidden_response), 0);
    return true; 
  }

  snprintf(full_static_path, sizeof(full_static_path), "%s%s", STATIC_DIR,
           request_path_relative_to_static);

  FILE *fp = fopen(full_static_path, "rb");
  if (fp == NULL) {
    fprintf(stderr,
            "[ERROR] serve_static_file: File '%s' not found or could not be opened. %s\n",
            full_static_path, strerror(errno)); 
    return false; 
  }

  struct stat st; 

  if (fstat(fileno(fp), &st) < 0) {
    perror("fstat error");
    fprintf(stderr, "[ERROR] serve_static_file: fstat failed for '%s'.\n",
            full_static_path);
    fclose(fp); 

    const char *server_error_response =
        "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n";
    send(current_client_socket, server_error_response, strlen(server_error_response), 0);
    return true; 
  }

  long file_size = st.st_size; 
  const char *mime_type = get_mime_type(full_static_path); 

  char http_header[BUFFER_SIZE]; 

  snprintf(http_header, sizeof(http_header),
           "HTTP/1.1 200 OK\r\n"
           "Content-Type: %s\r\n"      
           "Content-Length: %ld\r\n"   
           "Connection: close\r\n"     
           "\r\n",                    
           mime_type, file_size);

  if (send(current_client_socket, http_header, strlen(http_header), 0) < 0) {
    perror("Error sending static file header");
    fprintf(stderr, "[ERROR] serve_static_file: Failed to send header for '%s'.\n", full_static_path);
    fclose(fp);
    return true; 
  }

  char file_buffer[BUFFER_SIZE]; 
  size_t bytes_read;             

  while ((bytes_read = fread(file_buffer, 1, sizeof(file_buffer), fp)) > 0) {
    if (send(current_client_socket, file_buffer, bytes_read, 0) < 0) {
      perror("Error sending static file content");
      fprintf(stderr, "[ERROR] serve_static_file: Failed to send content for '%s'.\n", full_static_path);
      break; 
    }
  }

  fclose(fp); 
  return true; 
}