test: Fix memory leak when reading request line again
[libisds.git] / test / simline / http.c
blobc60d2c544bb3cdcd6e6ce8805ba8c81850e44ba8
1 #ifndef _XOPEN_SOURCE
2 #define _XOPEN_SOURCE 500 /* For strdup() */
3 #endif
5 #include "http.h"
6 #include "../test-tools.h"
7 #include <stdlib.h>
8 #include <errno.h>
9 #include <unistd.h>
10 #include <string.h>
11 #include <stdio.h> /* fprintf() */
12 #include <limits.h>
13 #include <string.h> /* strdup() */
14 #include <strings.h> /* strcasecmp() */
15 #include <stdint.h> /* int8_t */
16 #include <stddef.h> /* size_t, NULL */
17 #include <ctype.h> /* isprint() */
18 #include <sys/socket.h> /* MSG_NOSIGNAL for http_send_callback() */
21 Base64 encoder is part of the libb64 project, and has been placed in the public domain.
22 For details, see http://sourceforge.net/projects/libb64
23 It's copy of ../../src/cencode.c due to symbol names.
27 typedef enum {
28 step_A, step_B, step_C
29 } base64_encodestep;
31 typedef struct {
32 base64_encodestep step;
33 int8_t result;
34 int stepcount; /* number of encoded octet triplets on a line,
35 or -1 to for end-less line */
36 } base64_encodestate;
38 static const int CHARS_PER_LINE = 72;
40 /* Initialize Base64 coder.
41 * @one_line is false for multi-line MIME encoding,
42 * true for endless one-line format. */
43 static void base64_init_encodestate(base64_encodestate* state_in, _Bool one_line) {
44 state_in->step = step_A;
45 state_in->result = 0;
46 state_in->stepcount = (one_line) ? -1 : 0;
50 static int8_t base64_encode_value(int8_t value_in) {
51 /* XXX: CHAR_BIT == 8 because of <stdint.h> */
52 static const int8_t encoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
53 if (value_in > 63) return '=';
54 return encoding[value_in];
58 static size_t base64_encode_block(const int8_t* plaintext_in,
59 size_t length_in, int8_t *code_out, base64_encodestate* state_in) {
60 const int8_t *plainchar = plaintext_in;
61 const int8_t* const plaintextend = plaintext_in + length_in;
62 int8_t *codechar = code_out;
63 int8_t result;
64 int8_t fragment;
66 result = state_in->result;
68 switch (state_in->step) {
69 while (1) {
70 case step_A:
71 if (plainchar == plaintextend) {
72 state_in->result = result;
73 state_in->step = step_A;
74 return codechar - code_out;
76 fragment = *plainchar++;
77 result = (fragment & 0x0fc) >> 2;
78 *codechar++ = base64_encode_value(result);
79 result = (fragment & 0x003) << 4;
80 case step_B:
81 if (plainchar == plaintextend) {
82 state_in->result = result;
83 state_in->step = step_B;
84 return codechar - code_out;
86 fragment = *plainchar++;
87 result |= (fragment & 0x0f0) >> 4;
88 *codechar++ = base64_encode_value(result);
89 result = (fragment & 0x00f) << 2;
90 case step_C:
91 if (plainchar == plaintextend) {
92 state_in->result = result;
93 state_in->step = step_C;
94 return codechar - code_out;
96 fragment = *plainchar++;
97 result |= (fragment & 0x0c0) >> 6;
98 *codechar++ = base64_encode_value(result);
99 result = (fragment & 0x03f) >> 0;
100 *codechar++ = base64_encode_value(result);
102 if (state_in->stepcount >= 0) {
103 ++(state_in->stepcount);
104 if (state_in->stepcount == CHARS_PER_LINE/4) {
105 *codechar++ = '\n';
106 state_in->stepcount = 0;
109 } /* while */
110 } /* switch */
112 /* control should not reach here */
113 return codechar - code_out;
117 static size_t base64_encode_blockend(int8_t *code_out,
118 base64_encodestate* state_in) {
119 int8_t *codechar = code_out;
121 switch (state_in->step) {
122 case step_B:
123 *codechar++ = base64_encode_value(state_in->result);
124 *codechar++ = '=';
125 *codechar++ = '=';
126 break;
127 case step_C:
128 *codechar++ = base64_encode_value(state_in->result);
129 *codechar++ = '=';
130 break;
131 case step_A:
132 break;
134 if (state_in->stepcount >= 0)
135 *codechar++ = '\n';
137 return codechar - code_out;
141 /* Encode given data into MIME Base64 encoded zero terminated string.
142 * @plain are input data (binary stream)
143 * @length is length of @plain data in bytes
144 * @one_line is false for multi-line MIME encoding,
145 * true for endless one-line format.
146 * @return allocated string of base64 encoded plain data or NULL in case of
147 * error. You must free it. */
148 /* TODO: Allow one-line format */
149 static char *base64encode(const void *plain, const size_t length,
150 _Bool one_line) {
152 base64_encodestate state;
153 size_t code_length;
154 char *buffer, *new_buffer;
156 if (!plain) {
157 if (length) return NULL;
158 /* Empty input is valid input */
159 plain = "";
162 base64_init_encodestate(&state, one_line);
164 /* Allocate buffer
165 * (4 is padding, 1 is final new line, and 1 is string terminator) */
166 buffer = malloc(length * 2 + 4 + 1 + 1);
167 if (!buffer) return NULL;
169 /* Encode plain data */
170 code_length = base64_encode_block(plain, length, (int8_t *)buffer,
171 &state);
172 code_length += base64_encode_blockend(((int8_t*)buffer) + code_length,
173 &state);
175 /* Terminate string */
176 buffer[code_length++] = '\0';
178 /* Shrink the buffer */
179 new_buffer = realloc(buffer, code_length);
180 if (new_buffer) buffer = new_buffer;
182 return buffer;
186 /* Convert hexadecimal digit to integer. Return negative value if charcter is
187 * not valid hexadecimal digit. */
188 static int hex2i(char digit) {
189 if (digit >= '0' && digit <= '9')
190 return digit - '0';
191 if (digit >= 'a' && digit <= 'f')
192 return digit - 'a' + 10;
193 if (digit >= 'A' && digit <= 'F')
194 return digit - 'A' + 10;
195 return -1;
199 /* Decode URI-coded string.
200 * @return allocated decoded string or NULL in case of error. */
201 static char *uri_decode(const char *coded) {
202 char *plain, *p;
203 int digit1, digit2;
205 if (coded == NULL) return NULL;
206 plain = malloc(strlen(coded) + 1);
207 if (plain == NULL) return NULL;
209 for (p = plain; *coded != '\0'; p++, coded++) {
210 if (*coded == '%') {
211 digit1 = hex2i(coded[1]);
212 if (digit1 < 0) {
213 free(plain);
214 return NULL;
216 digit2 = hex2i(coded[2]);
217 if (digit2< 0) {
218 free(plain);
219 return NULL;
221 *plain = (digit1 << 4) + digit2;
222 coded += 2;
223 } else {
224 *p = *coded;
227 *p = '\0';
229 return plain;
233 /* Read a line from HTTP socket.
234 * @connection is HTTP connection to read from.
235 * @line is auto-reallocated just read line. Will be NULL if EOF has been
236 * reached or error occured.
237 * @buffer is automatically reallocated buffer for the socket. It can preserve
238 * prematurately read socket data.
239 * @buffer_size is allocated size of @buffer
240 * @buffer_length is size of head of the buffer that holds read data.
241 * @return 0 in success. */
242 static int http_read_line(const struct http_connection *connection,
243 char **line, char **buffer, size_t *buffer_size,
244 size_t *buffer_used) {
245 ssize_t got;
246 char *p, *tmp;
248 if (line == NULL) return HTTP_ERROR_SERVER;
249 free(*line);
250 *line = NULL;
252 if (connection == NULL || connection->recv_callback == NULL)
253 return HTTP_ERROR_SERVER;
254 if (buffer == NULL || buffer_size == NULL || buffer_used == NULL)
255 return HTTP_ERROR_SERVER;
256 if (*buffer == NULL && *buffer_size > 0) return HTTP_ERROR_SERVER;
257 if (*buffer_size < *buffer_used) return HTTP_ERROR_SERVER;
259 #define BURST 1024
260 while (1) {
261 /* Check for EOL */
262 for (p = *buffer; p < *buffer + *buffer_used; p++)
264 if (*p != '\r')
265 continue;
266 if (!(p + 1 < *buffer + *buffer_used && p[1] == '\n'))
267 continue;
269 /* EOL found */
270 /* Crop by zero at EOL */
271 *p = '\0';
272 p += 2;
273 /* Copy read ahead data to new buffer and point line to original
274 * buffer. */
275 tmp = malloc(BURST);
276 if (tmp == NULL) return HTTP_ERROR_SERVER;
277 memcpy(tmp, p, *buffer + *buffer_used - p);
278 *line = *buffer;
279 *buffer_size = BURST;
280 *buffer_used = *buffer + *buffer_used - p;
281 *buffer = tmp;
282 /* And exit */
283 return HTTP_ERROR_SUCCESS;
286 if (*buffer_size == *buffer_used) {
287 /* Grow buffer */
288 tmp = realloc(*buffer, *buffer_size + BURST);
289 if (tmp == NULL) return HTTP_ERROR_SERVER;
290 *buffer = tmp;
291 *buffer_size += BURST;
294 /* Read data */
295 got = connection->recv_callback(connection, *buffer + *buffer_used,
296 *buffer_size - *buffer_used);
297 if (got == -1) return HTTP_ERROR_CLIENT;
299 /* Check for EOF */
300 if (got == 0) return HTTP_ERROR_CLIENT;
302 /* Move end of buffer */
303 *buffer_used += got;
305 #undef BURST
307 return HTTP_ERROR_SERVER;
311 /* Write a bulk data into HTTP socket.
312 * @connection is HTTP connection to write to.
313 * @data are bitstream to send to client.
314 * @length is size of @data in bytes.
315 * @return 0 in success. */
316 static int http_write_bulk(const struct http_connection *connection,
317 const void *data, size_t length) {
318 ssize_t written;
319 const void *end;
321 if (connection == NULL || connection->send_callback == NULL)
322 return HTTP_ERROR_SERVER;
323 if (data == NULL && length > 0) return HTTP_ERROR_SERVER;
325 for (end = data + length; data != end; data += written, length -= written) {
326 written = connection->send_callback(connection, data, length);
327 if (written == -1) return HTTP_ERROR_CLIENT;
330 return HTTP_ERROR_SUCCESS;
334 /* Write a line into HTTP socket.
335 * @connection is HTTP connection to write to.
336 * @line is NULL terminated string to send to client. HTTP EOL will be added.
337 * @return 0 in success. */
338 static int http_write_line(const struct http_connection *connection,
339 const char *line) {
340 int error;
341 if (line == NULL) return HTTP_ERROR_SERVER;
343 fprintf(stderr, "Response: <%s>\n", line);
345 /* Send the line */
346 if ((error = http_write_bulk(connection, line, strlen(line))))
347 return error;
349 /* Send EOL */
350 if ((error = http_write_bulk(connection, "\r\n", 2)))
351 return error;
353 return HTTP_ERROR_SUCCESS;
357 /* Read data of given length from HTTP socket.
358 * @connection is HTTP connection to read from.
359 * @data is auto-allocated just read data bulk. Will be NULL if EOF has been
360 * reached or error occured.
361 * @data_length is size of bytes to read.
362 * @buffer is automatically reallocated buffer for the socket. It can preserve
363 * prematurately read socket data.
364 * @buffer_size is allocated size of @buffer
365 * @buffer_length is size of head of the buffer that holds read data.
366 * @return 0 in success. */
367 static int http_read_bulk(const struct http_connection *connection,
368 void **data, size_t data_length,
369 char **buffer, size_t *buffer_size, size_t *buffer_used) {
370 ssize_t got;
371 char *tmp;
373 if (data == NULL) return HTTP_ERROR_SERVER;
374 *data = NULL;
376 if (connection == NULL || connection->recv_callback == NULL)
377 return HTTP_ERROR_SERVER;
378 if (buffer == NULL || buffer_size == NULL || buffer_used == NULL)
379 return HTTP_ERROR_SERVER;
380 if (*buffer == NULL && *buffer_size > 0) return HTTP_ERROR_SERVER;
381 if (*buffer_size < *buffer_used) return HTTP_ERROR_SERVER;
383 if (data_length <= 0) return HTTP_ERROR_SUCCESS;
385 #define BURST 1024
386 while (1) {
387 /* Check whether enought data have been read */
388 if (*buffer_used >= data_length) {
389 /* Copy read ahead data to new buffer and point data to original
390 * buffer. */
391 tmp = malloc(BURST);
392 if (tmp == NULL) return HTTP_ERROR_SERVER;
393 memcpy(tmp, *buffer + data_length, *buffer_used - data_length);
394 *data = *buffer;
395 *buffer_size = BURST;
396 *buffer_used = *buffer_used - data_length;
397 *buffer = tmp;
398 /* And exit */
399 return HTTP_ERROR_SUCCESS;
402 if (*buffer_size == *buffer_used) {
403 /* Grow buffer */
404 tmp = realloc(*buffer, *buffer_size + BURST);
405 if (tmp == NULL) return HTTP_ERROR_SERVER;
406 *buffer = tmp;
407 *buffer_size += BURST;
410 /* Read data */
411 got = connection->recv_callback(connection, *buffer + *buffer_used,
412 *buffer_size - *buffer_used);
413 if (got == -1) return HTTP_ERROR_CLIENT;
415 /* Check for EOF */
416 if (got == 0) return HTTP_ERROR_CLIENT;
418 /* Move end of buffer */
419 *buffer_used += got;
421 #undef BURST
423 return HTTP_ERROR_SERVER;
427 /* Parse HTTP request header.
428 * @request is pre-allocated HTTP request.
429 * @return 0 if success. */
430 static int http_parse_request_header(char *line,
431 struct http_request *request) {
432 char *p;
434 fprintf(stderr, "Request: <%s>\n", line);
436 /* Get method */
437 p = strchr(line, ' ');
438 if (p == NULL) return HTTP_ERROR_SERVER;
439 *p = '\0';
440 if (!strcmp(line, "GET"))
441 request->method = HTTP_METHOD_GET;
442 else if (!strcmp(line, "POST"))
443 request->method = HTTP_METHOD_POST;
444 else
445 request->method = HTTP_METHOD_UNKNOWN;
446 line = p + 1;
448 /* Get URI */
449 p = strchr(line, ' ');
450 if (p != NULL) *p = '\0';
451 request->uri = uri_decode(line);
452 if (request->uri == NULL) return HTTP_ERROR_SERVER;
454 /* Do not care about HTTP version */
456 fprintf(stderr, "Request-URI: <%s>\n", request->uri);
457 return HTTP_ERROR_SUCCESS;
461 /* Send HTTP response status line to client.
462 * @return 0 if success. */
463 static int http_write_response_status(const struct http_connection *connection,
464 const struct http_response *response) {
465 char *buffer = NULL;
466 int error;
468 if (response == NULL) return HTTP_ERROR_SERVER;
470 if (-1 == test_asprintf(&buffer, "HTTP/1.0 %u %s", response->status,
471 (response->reason == NULL) ? "" : response->reason))
472 return HTTP_ERROR_SERVER;
473 error = http_write_line(connection, buffer);
474 free(buffer);
476 return error;
480 /* Parse generic HTTP header.
481 * @request is pre-allocated HTTP request.
482 * @return 0 if success, negative value if internal error, positive value if
483 * header is not valid. */
484 static int http_parse_header(char *line, struct http_request *request) {
485 struct http_header *header;
487 if (line == NULL || request == NULL) return HTTP_ERROR_SERVER;
489 fprintf(stderr, "Header: <%s>\n", line);
491 /* Find last used header */
492 for (header = request->headers; header != NULL && header->next != NULL;
493 header = header->next);
495 if (*line == ' ' || *line == '\t') {
496 /* Line is continuation of last header */
497 if (header == NULL)
498 return HTTP_ERROR_CLIENT; /* No previous header to continue */
499 line++;
500 size_t old_length = strlen(header->value);
501 char *tmp = realloc(header->value,
502 sizeof(header->value[0]) * (old_length + strlen(line) + 1));
503 if (tmp == NULL) return HTTP_ERROR_SERVER;
504 header->value = tmp;
505 strcpy(&header->value[old_length], line);
506 } else {
507 /* New header */
508 struct http_header *new_header = calloc(sizeof(*new_header), 1);
509 if (new_header == NULL) return HTTP_ERROR_SERVER;
511 char *p = strstr(line, ": ");
512 if (p == NULL) return HTTP_ERROR_CLIENT;
514 size_t length = p - line;
515 new_header->name = malloc(sizeof(line[0]) * (length + 1));
516 if (new_header->name == NULL) {
517 http_header_free(&new_header);
518 return HTTP_ERROR_SERVER;
520 strncpy(new_header->name, line, length);
521 new_header->name[length] = '\0';
523 p += 2;
524 length = strlen(p);
525 new_header->value = malloc(sizeof(p[0]) * (length + 1));
526 if (new_header->value == NULL) {
527 http_header_free(&new_header);
528 return HTTP_ERROR_SERVER;
530 strcpy(new_header->value, p);
532 if (request->headers == NULL)
533 request->headers = new_header;
534 else
535 header->next = new_header;
539 /* FIXME: Decode. After parsing all headers as we could decode begining
540 * and then got encoded continuation. */
541 return HTTP_ERROR_SUCCESS;
545 /* Send HTTP header to client.
546 * @return 0 if success. */
547 static int http_write_header(const struct http_connection *connection,
548 const struct http_header *header) {
549 char *buffer = NULL;
550 int error;
552 if (header == NULL) return HTTP_ERROR_SERVER;
554 if (header->name == NULL) return HTTP_ERROR_SERVER;
556 /* TODO: Quote, split long lines */
557 if (-1 == test_asprintf(&buffer, "%s: %s", header->name,
558 (header->value == NULL) ? "" : header->value))
559 return HTTP_ERROR_SERVER;
560 error = http_write_line(connection, buffer);
561 free(buffer);
563 return error;
567 /* Find Content-Length value in HTTP request headers and set it into @request.
568 * @return 0 in success. */
569 static int find_content_length(struct http_request *request) {
570 struct http_header *header;
571 if (request == NULL) return HTTP_ERROR_SERVER;
573 for (header = request->headers; header != NULL; header = header->next) {
574 if (header->name == NULL) continue;
575 if (!strcasecmp(header->name, "Content-Length")) break;
578 if (header != NULL && header->value != NULL) {
579 char *p;
580 long long int value = strtol(header->value, &p, 10);
581 if (*p != '\0')
582 return HTTP_ERROR_CLIENT;
583 if ((value == LLONG_MIN || value == LLONG_MAX) && errno == ERANGE)
584 return HTTP_ERROR_SERVER;
585 if (value < 0)
586 return HTTP_ERROR_CLIENT;
587 if (value > SIZE_MAX)
588 return HTTP_ERROR_SERVER;
589 request->body_length = value;
590 } else {
591 request->body_length = 0;
593 return HTTP_ERROR_SUCCESS;
597 /* Print binary stream to STDERR with some escapes */
598 static void dump_body(const void *data, size_t length) {
599 fprintf(stderr, "===BEGIN BODY===\n");
600 if (length > 0 && NULL != data) {
601 for (size_t i = 0; i < length; i++) {
602 if (isprint(((const unsigned char *)data)[i]))
603 fprintf(stderr, "%c", ((const unsigned char *)data)[i]);
604 else
605 fprintf(stderr, "\\x%02x", ((const unsigned char*)data)[i]);
607 fprintf(stderr, "\n");
609 fprintf(stderr, "===END BODY===\n");
613 /* Read a HTTP request from connection.
614 * @http_request is heap-allocated received HTTP request,
615 * or NULL in case of error.
616 * @return http_error code. */
617 http_error http_read_request(const struct http_connection *connection,
618 struct http_request **request) {
619 char *line = NULL;
620 char *buffer = NULL;
621 size_t buffer_size = 0, buffer_used = 0;
622 int error;
624 if (request == NULL) return HTTP_ERROR_SERVER;
626 *request = calloc(1, sizeof(**request));
627 if (*request == NULL) return HTTP_ERROR_SERVER;
629 /* Get request header */
630 if ((error = http_read_line(connection, &line, &buffer, &buffer_size,
631 &buffer_used)))
632 goto leave;
633 if ((error = http_parse_request_header(line, *request)))
634 goto leave;
636 /* Get other headers */
637 while (1) {
638 if ((error = http_read_line(connection, &line, &buffer, &buffer_size,
639 &buffer_used))) {
640 fprintf(stderr, "Error while reading HTTP request line\n");
641 goto leave;
644 /* Check for headers delimiter */
645 if (line == NULL || *line == '\0') {
646 break;
649 if ((error = http_parse_header(line, *request))) {
650 fprintf(stderr, "Error while parsing HTTP request line: <%s>\n",
651 line);
652 goto leave;
656 /* Get body */
657 if ((error = find_content_length(*request))) {
658 fprintf(stderr, "Could not determine length of body\n");
659 goto leave;
661 if ((error = http_read_bulk(connection,
662 &(*request)->body, (*request)->body_length,
663 &buffer, &buffer_size, &buffer_used))) {
664 fprintf(stderr, "Could not read request body\n");
665 goto leave;
667 fprintf(stderr, "Body of size %zu B has been received:\n",
668 (*request)->body_length);
669 dump_body((*request)->body, (*request)->body_length);
671 leave:
672 free(line);
673 free(buffer);
674 if (error) http_request_free(request);
675 return error;
679 /* Write a HTTP response to connection. Auto-add Content-Length header.
680 * @return 0 in case of success. */
681 int http_write_response(const struct http_connection *connection,
682 const struct http_response *response) {
683 char *buffer = NULL;
684 int error = -1;
686 if (response == NULL) return HTTP_ERROR_SERVER;
688 /* Status line */
689 error = http_write_response_status(connection, response);
690 if (error) return error;
692 /* Headers */
693 for (struct http_header *header = response->headers; header != NULL;
694 header = header->next) {
695 error = http_write_header(connection, header);
696 if (error) return error;
698 if (-1 == test_asprintf(&buffer, "Content-Length: %u",
699 response->body_length))
700 return HTTP_ERROR_SERVER;
701 error = http_write_line(connection, buffer);
702 if (error) return error;
704 /* Headers trailer */
705 error = http_write_line(connection, "");
706 if (error) return error;
708 /* Body */
709 if (response->body_length > 0) {
710 error = http_write_bulk(connection, response->body,
711 response->body_length);
712 if (error) return error;
714 fprintf(stderr, "Body of size %zu B has been sent:\n",
715 response->body_length);
716 dump_body(response->body, response->body_length);
718 free(buffer);
719 return HTTP_ERROR_SUCCESS;
723 /* Build Set-Cookie header. In case of error, return NULL. Caller must free
724 * the header. */
725 static struct http_header *http_build_setcookie_header (
726 const char *cokie_name, const char *cookie_value,
727 const char *cookie_domain, const char *cookie_path) {
728 struct http_header *header = NULL;
729 char *domain_parameter = NULL;
730 char *path_parameter = NULL;
732 if (cokie_name == NULL) goto error;
734 header = calloc(1, sizeof(*header));
735 if (header == NULL) goto error;
737 header->name = strdup("Set-Cookie");
738 if (header->name == NULL) goto error;
740 if (cookie_domain != NULL)
741 if (-1 == test_asprintf(&domain_parameter, "; Domain=%s",
742 cookie_domain))
743 goto error;
745 if (cookie_path != NULL)
746 if (-1 == test_asprintf(&path_parameter, "; Path=%s",
747 cookie_path))
748 goto error;
750 if (-1 == test_asprintf(&header->value, "%s=%s%s%s",
751 cokie_name,
752 (cookie_value == NULL) ? "" : cookie_value,
753 (domain_parameter == NULL) ? "": domain_parameter,
754 (path_parameter == NULL) ? "": path_parameter))
755 goto error;
756 goto ok;
758 error:
759 http_header_free(&header);
761 free(domain_parameter);
762 free(path_parameter);
763 return header;
767 /* Send a 200 Ok response with a cookie */
768 int http_send_response_200_cookie(const struct http_connection *connection,
769 const char *cokie_name, const char *cookie_value,
770 const char *cookie_domain, const char *cookie_path,
771 const void *body, size_t body_length, const char *type) {
772 int retval;
773 struct http_header *header_cookie = NULL;
774 struct http_header header_contenttype = {
775 .name = "Content-Type",
776 .value = (char *)type,
777 .next = NULL
779 struct http_response response = {
780 .status = 200,
781 .reason = "OK",
782 .headers = NULL,
783 .body_length = body_length,
784 .body = (void *)body
787 if (cokie_name != NULL) {
788 if (NULL == (header_cookie = http_build_setcookie_header(
789 cokie_name, cookie_value, cookie_domain, cookie_path)))
790 return http_send_response_500(connection,
791 "Could not build Set-Cookie header");
794 /* Link defined headers */
795 if (type != NULL) {
796 response.headers = &header_contenttype;
798 if (header_cookie != NULL) {
799 header_cookie->next = response.headers;
800 response.headers = header_cookie;
803 retval = http_write_response(connection, &response);
804 http_header_free(&header_cookie);
805 return retval;
809 /* Send a 200 Ok response */
810 int http_send_response_200(const struct http_connection *connection,
811 const void *body, size_t body_length, const char *type) {
812 return http_send_response_200_cookie(connection,
813 NULL, NULL, NULL, NULL,
814 body, body_length, type);
818 /* Send a 302 Found response setting a cookie */
819 int http_send_response_302_cookie(const struct http_connection *connection,
820 const char *cokie_name, const char *cookie_value,
821 const char *cookie_domain, const char *cookie_path,
822 const char *location) {
823 int retval;
824 struct http_header *header_cookie = NULL;
825 struct http_header header_location = {
826 .name = "Location",
827 .value = (char *) location,
828 .next = NULL
830 struct http_response response = {
831 .status = 302,
832 .reason = "Found",
833 .headers = NULL,
834 .body_length = 0,
835 .body = NULL
838 if (cokie_name != NULL) {
839 if (NULL == (header_cookie = http_build_setcookie_header(
840 cokie_name, cookie_value, cookie_domain, cookie_path)))
841 return http_send_response_500(connection,
842 "Could not build Set-Cookie header");
845 /* Link defined headers */
846 if (location != NULL) {
847 response.headers = &header_location;
849 if (header_cookie != NULL) {
850 header_cookie->next = response.headers;
851 response.headers = header_cookie;
854 retval = http_write_response(connection, &response);
855 http_header_free(&header_cookie);
856 return retval;
860 /* Send a 302 Found response with totp authentication scheme header */
861 int http_send_response_302_totp(const struct http_connection *connection,
862 const char *code, const char *text, const char *location) {
863 struct http_header header_code = {
864 .name = "X-Response-message-code",
865 .value = (char *) code,
866 .next = NULL
868 struct http_header header_text = {
869 .name = "X-Response-message-text",
870 .value = (char *) text,
871 .next = NULL
873 struct http_header header_location = {
874 .name = "Location",
875 .value = (char *) location,
876 .next = NULL
878 struct http_response response = {
879 .status = 302,
880 .reason = "Found",
881 .headers = NULL,
882 .body_length = 0,
883 .body = NULL
886 /* Link defined headers */
887 if (location != NULL) {
888 response.headers = &header_location;
890 if (text != NULL) {
891 header_text.next = response.headers;
892 response.headers = &header_text;
894 if (code != NULL) {
895 header_code.next = response.headers;
896 response.headers = &header_code;
899 return http_write_response(connection, &response);
903 /* Send a 400 Bad Request response.
904 * Use non-NULL @reason to override status message. */
905 int http_send_response_400(const struct http_connection *connection,
906 const char *reason) {
907 struct http_response response = {
908 .status = 400,
909 .reason = (reason == NULL) ? "Bad Request" : (char *) reason,
910 .headers = NULL,
911 .body_length = 0,
912 .body = NULL
915 return http_write_response(connection, &response);
919 /* Send a 401 Unauthorized response with Basic authentication scheme header */
920 int http_send_response_401_basic(const struct http_connection *connection) {
921 struct http_header header = {
922 .name = "WWW-Authenticate",
923 .value = "Basic realm=\"SimulatedISDSServer\"",
924 .next = NULL
926 struct http_response response = {
927 .status = 401,
928 .reason = "Unauthorized",
929 .headers = &header,
930 .body_length = 0,
931 .body = NULL
934 return http_write_response(connection, &response);
938 /* Send a 401 Unauthorized response with OTP authentication scheme header for
939 * given @method. */
940 int http_send_response_401_otp(const struct http_connection *connection,
941 const char *method, const char *code, const char *text) {
942 int retval;
943 struct http_header header = {
944 .name = "WWW-Authenticate",
945 .value = NULL,
946 .next = NULL
948 struct http_header header_code = {
949 .name = "X-Response-message-code",
950 .value = (char *) code,
951 .next = NULL
953 struct http_header header_text = {
954 .name = "X-Response-message-text",
955 .value = (char *) text,
956 .next = NULL
958 struct http_response response = {
959 .status = 401,
960 .reason = "Unauthorized",
961 .headers = &header,
962 .body_length = 0,
963 .body = NULL
966 if (-1 == test_asprintf(&header.value, "%s realm=\"SimulatedISDSServer\"",
967 method)) {
968 return http_send_response_500(connection,
969 "Could not build WWW-Authenticate header value");
972 /* Link defined headers */
973 if (code != NULL) header.next = &header_code;
974 if (text != NULL) {
975 if (code != NULL)
976 header_code.next = &header_text;
977 else
978 header.next = &header_text;
981 retval = http_write_response(connection, &response);
982 free(header.value);
983 return retval;
987 /* Send a 403 Forbidden response */
988 int http_send_response_403(const struct http_connection *connection) {
989 struct http_response response = {
990 .status = 403,
991 .reason = "Forbidden",
992 .headers = NULL,
993 .body_length = 0,
994 .body = NULL
997 return http_write_response(connection, &response);
1001 /* Send a 500 Internal Server Error response.
1002 * Use non-NULL @reason to override status message. */
1003 int http_send_response_500(const struct http_connection *connection,
1004 const char *reason) {
1005 struct http_response response = {
1006 .status = 500,
1007 .reason = (NULL == reason) ? "Internal Server Error" : (char *) reason,
1008 .headers = NULL,
1009 .body_length = 0,
1010 .body = NULL
1013 return http_write_response(connection, &response);
1017 /* Send a 503 Service Temporarily Unavailable response */
1018 int http_send_response_503(const struct http_connection *connection,
1019 const void *body, size_t body_length, const char *type) {
1020 struct http_header header = {
1021 .name = "Content-Type",
1022 .value = (char *)type
1024 struct http_response response = {
1025 .status = 503,
1026 .reason = "Service Temporarily Unavailable",
1027 .headers = (type == NULL) ? NULL : &header,
1028 .body_length = body_length,
1029 .body = (void *)body
1032 return http_write_response(connection, &response);
1036 /* Returns Authorization header in given request */
1037 static const struct http_header *find_authorization(
1038 const struct http_request *request) {
1039 const struct http_header *header;
1040 if (request == NULL) return NULL;
1041 for (header = request->headers; header != NULL; header = header->next) {
1042 if (header->name != NULL &&
1043 !strcasecmp(header->name, "Authorization"))
1044 break;
1046 return header;
1050 /* Return true if request carries Authorization header */
1051 int http_client_authenticates(const struct http_request *request) {
1052 if (find_authorization(request))
1053 return 1;
1054 else
1055 return 0;
1059 /* Return HTTP_ERROR_SUCCESS if request carries valid Basic credentials.
1060 * NULL @username or @password equales to empty string. */
1061 http_error http_authenticate_basic(const struct http_request *request,
1062 const char *username, const char *password) {
1063 const struct http_header *header;
1064 const char *basic_cookie_client;
1065 char *basic_cookie_plain = NULL, *basic_cookie_encoded = NULL;
1066 _Bool is_valid;
1068 header = find_authorization(request);
1069 if (header == NULL) return HTTP_ERROR_CLIENT;
1071 if (strncmp(header->value, "Basic ", 6)) return HTTP_ERROR_CLIENT;
1072 basic_cookie_client = header->value + 6;
1074 if (-1 == test_asprintf(&basic_cookie_plain, "%s:%s",
1075 (username == NULL) ? "" : username,
1076 (password == NULL) ? "" : password)) {
1077 return HTTP_ERROR_SERVER;
1080 basic_cookie_encoded = base64encode(basic_cookie_plain,
1081 strlen(basic_cookie_plain), 1);
1082 if (basic_cookie_encoded == NULL) {
1083 free(basic_cookie_plain);
1084 return HTTP_ERROR_SERVER;
1087 fprintf(stderr, "Authenticating basic: got=<%s>, expected=<%s> (%s)\n",
1088 basic_cookie_client, basic_cookie_encoded, basic_cookie_plain);
1089 free(basic_cookie_plain);
1091 is_valid = !strcmp(basic_cookie_encoded, basic_cookie_client);
1092 free(basic_cookie_encoded);
1094 return (is_valid) ? HTTP_ERROR_SUCCESS : HTTP_ERROR_CLIENT;
1098 /* Return HTTP_ERROR_SUCCESS if request carries valid OTP credentials.
1099 * NULL @username or @password or @otp equal to empty string. */
1100 http_error http_authenticate_otp(const struct http_request *request,
1101 const char *username, const char *password, const char *otp) {
1102 char *basic_password = NULL;
1103 http_error retval;
1105 /* Concatenate password and OTP code */
1106 if (-1 == test_asprintf(&basic_password, "%s%s",
1107 (password == NULL) ? "": password,
1108 (otp == NULL) ? "" : otp)) {
1109 return HTTP_ERROR_SERVER;
1112 /* Use Basic authentication */
1113 /* XXX: Specification does not define authorization method string */
1114 retval = http_authenticate_basic(request, username, basic_password);
1116 free(basic_password);
1117 return retval;
1121 /* Return cookie value by name or NULL if does not present. */
1122 const char *http_find_cookie(const struct http_request *request,
1123 const char *name) {
1124 const struct http_header *header;
1125 size_t length;
1126 const char *value = NULL;
1128 if (request == NULL || name == NULL) return NULL;
1129 length = strlen(name);
1131 for (header = request->headers; header != NULL; header = header->next) {
1132 if (header->name != NULL && !strcasecmp(header->name, "Cookie") &&
1133 header->value != NULL) {
1134 if (!strncmp(header->value, name, length) &&
1135 header->value[length] == '=') {
1136 /* Return last cookie with the name */
1137 value = header->value + length + 1;
1141 return value;
1145 /* Return Host header value or NULL if does not present. Returned string is
1146 * statically allocated. */
1147 const char *http_find_host(const struct http_request *request) {
1148 const struct http_header *header;
1149 const char *value = NULL;
1151 if (request == NULL) return NULL;
1153 for (header = request->headers; header != NULL; header = header->next) {
1154 if (header->name != NULL && !strcmp(header->name, "Host")) {
1155 value = header->value;
1158 return value;
1162 /* Free a HTTP header and set it to NULL */
1163 void http_header_free(struct http_header **header) {
1164 if (header == NULL || *header == NULL) return;
1165 free((*header)->name);
1166 free((*header)->value);
1167 free(*header);
1168 *header = NULL;
1172 /* Free linked list of HTTP headers and set it to NULL */
1173 void http_headers_free(struct http_header **headers) {
1174 struct http_header *header, *next;
1176 if (headers == NULL || *headers == NULL) return;
1178 for (header = *headers; header != NULL;) {
1179 next = header->next;
1180 http_header_free(&header);
1181 header = next;
1184 *headers = NULL;
1187 /* Free HTTP request and set it to NULL */
1188 void http_request_free(struct http_request **request) {
1189 if (request == NULL || *request == NULL) return;
1190 free((*request)->uri);
1191 http_headers_free(&((*request)->headers));
1192 free((*request)->body);
1193 free(*request);
1194 *request = NULL;
1197 /* Free HTTP response and set it to NULL */
1198 void http_response_free(struct http_response **response) {
1199 if (response == NULL || *response == NULL) return;
1200 free((*response)->reason);
1201 http_headers_free(&((*response)->headers));
1202 free((*response)->body);
1203 free(*response);
1204 *response = NULL;