test: server: Use TLS call-back in HTTP
[libisds.git] / test / simline / http.c
blob3a685ee995f1c12a748cbe9517c24db8ee1a3452
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 /* Call-backs set by application */
234 http_recv_callback_t http_recv_callback = NULL;
235 http_send_callback_t http_send_callback = NULL;
236 void *http_recv_context = NULL;
237 void *http_send_context = NULL;
239 /* Read a line from HTTP socket.
240 * @socket is descriptor to read from.
241 * @line is auto-allocated just read line. Will be NULL if EOF has been
242 * reached or error occured.
243 * @buffer is automatically reallocated buffer for the socket. It can preserve
244 * prematurately read socket data.
245 * @buffer_size is allocated size of @buffer
246 * @buffer_length is size of head of the buffer that holds read data.
247 * @return 0 in success. */
248 static int http_read_line(int socket, char **line,
249 char **buffer, size_t *buffer_size, size_t *buffer_used) {
250 ssize_t got;
251 char *p, *tmp;
253 if (line == NULL) return HTTP_ERROR_SERVER;
254 *line = NULL;
256 if (buffer == NULL || buffer_size == NULL || buffer_used == NULL)
257 return HTTP_ERROR_SERVER;
258 if (*buffer == NULL && *buffer_size > 0) return HTTP_ERROR_SERVER;
259 if (*buffer_size < *buffer_used) return HTTP_ERROR_SERVER;
261 #define BURST 1024
262 while (1) {
263 /* Check for EOL */
264 for (p = *buffer; p < *buffer + *buffer_used; p++)
266 if (*p != '\r')
267 continue;
268 if (!(p + 1 < *buffer + *buffer_used && p[1] == '\n'))
269 continue;
271 /* EOL found */
272 /* Crop by zero at EOL */
273 *p = '\0';
274 p += 2;
275 /* Copy read ahead data to new buffer and point line to original
276 * buffer. */
277 tmp = malloc(BURST);
278 if (tmp == NULL) return HTTP_ERROR_SERVER;
279 memcpy(tmp, p, *buffer + *buffer_used - p);
280 *line = *buffer;
281 *buffer_size = BURST;
282 *buffer_used = *buffer + *buffer_used - p;
283 *buffer = tmp;
284 /* And exit */
285 return HTTP_ERROR_SUCCESS;
288 if (*buffer_size == *buffer_used) {
289 /* Grow buffer */
290 tmp = realloc(*buffer, *buffer_size + BURST);
291 if (tmp == NULL) return HTTP_ERROR_SERVER;
292 *buffer = tmp;
293 *buffer_size += BURST;
296 /* Read data */
297 got = http_recv_callback(http_recv_context, *buffer + *buffer_used,
298 *buffer_size - *buffer_used, 0);
299 if (got == -1) return HTTP_ERROR_CLIENT;
301 /* Check for EOF */
302 if (got == 0) return HTTP_ERROR_CLIENT;
304 /* Move end of buffer */
305 *buffer_used += got;
307 #undef BURST
309 return HTTP_ERROR_SERVER;
313 /* Write a bulk data into HTTP socket.
314 * @socket is descriptor to write to.
315 * @data are bitstream to send to client.
316 * @length is size of @data in bytes.
317 * @return 0 in success. */
318 static int http_write_bulk(int socket, const void *data, size_t length) {
319 ssize_t written;
320 const void *end;
322 if (data == NULL && length > 0) return HTTP_ERROR_SERVER;
324 for (end = data + length; data != end; data += written, length -= written) {
325 written = http_send_callback(http_send_context, data, length,
326 MSG_NOSIGNAL);
327 if (written == -1) return HTTP_ERROR_CLIENT;
330 return HTTP_ERROR_SUCCESS;
334 /* Write a line into HTTP socket.
335 * @socket is descriptor 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(int socket, const char *line) {
339 int error;
340 if (line == NULL) return HTTP_ERROR_SERVER;
342 fprintf(stderr, "Response: <%s>\n", line);
344 /* Send the line */
345 if ((error = http_write_bulk(socket, line, strlen(line))))
346 return error;
348 /* Send EOL */
349 if ((error = http_write_bulk(socket, "\r\n", 2)))
350 return error;
352 return HTTP_ERROR_SUCCESS;
356 /* Read data of given length from HTTP socket.
357 * @socket is descriptor to read from.
358 * @data is auto-allocated just read data bulk. Will be NULL if EOF has been
359 * reached or error occured.
360 * @data_length is size of bytes to read.
361 * @buffer is automatically reallocated buffer for the socket. It can preserve
362 * prematurately read socket data.
363 * @buffer_size is allocated size of @buffer
364 * @buffer_length is size of head of the buffer that holds read data.
365 * @return 0 in success. */
366 static int http_read_bulk(int socket, void **data, size_t data_length,
367 char **buffer, size_t *buffer_size, size_t *buffer_used) {
368 ssize_t got;
369 char *tmp;
371 if (data == NULL) return HTTP_ERROR_SERVER;
372 *data = NULL;
374 if (buffer == NULL || buffer_size == NULL || buffer_used == NULL)
375 return HTTP_ERROR_SERVER;
376 if (*buffer == NULL && *buffer_size > 0) return HTTP_ERROR_SERVER;
377 if (*buffer_size < *buffer_used) return HTTP_ERROR_SERVER;
379 if (data_length <= 0) return HTTP_ERROR_SUCCESS;
381 #define BURST 1024
382 while (1) {
383 /* Check whether enought data have been read */
384 if (*buffer_used >= data_length) {
385 /* Copy read ahead data to new buffer and point data to original
386 * buffer. */
387 tmp = malloc(BURST);
388 if (tmp == NULL) return HTTP_ERROR_SERVER;
389 memcpy(tmp, *buffer + data_length, *buffer_used - data_length);
390 *data = *buffer;
391 *buffer_size = BURST;
392 *buffer_used = *buffer_used - data_length;
393 *buffer = tmp;
394 /* And exit */
395 return HTTP_ERROR_SUCCESS;
398 if (*buffer_size == *buffer_used) {
399 /* Grow buffer */
400 tmp = realloc(*buffer, *buffer_size + BURST);
401 if (tmp == NULL) return HTTP_ERROR_SERVER;
402 *buffer = tmp;
403 *buffer_size += BURST;
406 /* Read data */
407 got = http_recv_callback(http_recv_context, *buffer + *buffer_used,
408 *buffer_size - *buffer_used, 0);
409 if (got == -1) return HTTP_ERROR_CLIENT;
411 /* Check for EOF */
412 if (got == 0) return HTTP_ERROR_CLIENT;
414 /* Move end of buffer */
415 *buffer_used += got;
417 #undef BURST
419 return HTTP_ERROR_SERVER;
423 /* Parse HTTP request header.
424 * @request is pre-allocated HTTP request.
425 * @return 0 if success. */
426 static int http_parse_request_header(char *line,
427 struct http_request *request) {
428 char *p;
430 fprintf(stderr, "Request: <%s>\n", line);
432 /* Get method */
433 p = strchr(line, ' ');
434 if (p == NULL) return HTTP_ERROR_SERVER;
435 *p = '\0';
436 if (!strcmp(line, "GET"))
437 request->method = HTTP_METHOD_GET;
438 else if (!strcmp(line, "POST"))
439 request->method = HTTP_METHOD_POST;
440 else
441 request->method = HTTP_METHOD_UNKNOWN;
442 line = p + 1;
444 /* Get URI */
445 p = strchr(line, ' ');
446 if (p != NULL) *p = '\0';
447 request->uri = uri_decode(line);
448 if (request->uri == NULL) return HTTP_ERROR_SERVER;
450 /* Do not care about HTTP version */
452 fprintf(stderr, "Request-URI: <%s>\n", request->uri);
453 return HTTP_ERROR_SUCCESS;
457 /* Send HTTP response status line to client.
458 * @return 0 if success. */
459 static int http_write_response_status(int socket,
460 const struct http_response *response) {
461 char *buffer = NULL;
462 int error;
464 if (response == NULL) return HTTP_ERROR_SERVER;
466 if (-1 == test_asprintf(&buffer, "HTTP/1.0 %u %s", response->status,
467 (response->reason == NULL) ? "" : response->reason))
468 return HTTP_ERROR_SERVER;
469 error = http_write_line(socket, buffer);
470 free(buffer);
472 return error;
476 /* Parse generic HTTP header.
477 * @request is pre-allocated HTTP request.
478 * @return 0 if success, negative value if internal error, positive value if
479 * header is not valid. */
480 static int http_parse_header(char *line, struct http_request *request) {
481 struct http_header *header;
483 if (line == NULL || request == NULL) return HTTP_ERROR_SERVER;
485 fprintf(stderr, "Header: <%s>\n", line);
487 /* Find last used header */
488 for (header = request->headers; header != NULL && header->next != NULL;
489 header = header->next);
491 if (*line == ' ' || *line == '\t') {
492 /* Line is continuation of last header */
493 if (header == NULL)
494 return HTTP_ERROR_CLIENT; /* No previous header to continue */
495 line++;
496 size_t old_length = strlen(header->value);
497 char *tmp = realloc(header->value,
498 sizeof(header->value[0]) * (old_length + strlen(line) + 1));
499 if (tmp == NULL) return HTTP_ERROR_SERVER;
500 header->value = tmp;
501 strcpy(&header->value[old_length], line);
502 } else {
503 /* New header */
504 struct http_header *new_header = calloc(sizeof(*new_header), 1);
505 if (new_header == NULL) return HTTP_ERROR_SERVER;
507 char *p = strstr(line, ": ");
508 if (p == NULL) return HTTP_ERROR_CLIENT;
510 size_t length = p - line;
511 new_header->name = malloc(sizeof(line[0]) * (length + 1));
512 if (new_header->name == NULL) {
513 http_header_free(&new_header);
514 return HTTP_ERROR_SERVER;
516 strncpy(new_header->name, line, length);
517 new_header->name[length] = '\0';
519 p += 2;
520 length = strlen(p);
521 new_header->value = malloc(sizeof(p[0]) * (length + 1));
522 if (new_header->value == NULL) {
523 http_header_free(&new_header);
524 return HTTP_ERROR_SERVER;
526 strcpy(new_header->value, p);
528 if (request->headers == NULL)
529 request->headers = new_header;
530 else
531 header->next = new_header;
535 /* FIXME: Decode. After parsing all headers as we could decode begining
536 * and then got encoded continuation. */
537 return HTTP_ERROR_SUCCESS;
541 /* Send HTTP header to client.
542 * @return 0 if success. */
543 static int http_write_header(int socket, const struct http_header *header) {
544 char *buffer = NULL;
545 int error;
547 if (header == NULL) return HTTP_ERROR_SERVER;
549 if (header->name == NULL) return HTTP_ERROR_SERVER;
551 /* TODO: Quote, split long lines */
552 if (-1 == test_asprintf(&buffer, "%s: %s", header->name,
553 (header->value == NULL) ? "" : header->value))
554 return HTTP_ERROR_SERVER;
555 error = http_write_line(socket, buffer);
556 free(buffer);
558 return error;
562 /* Find Content-Length value in HTTP request headers and set it into @request.
563 * @return 0 in success. */
564 static int find_content_length(struct http_request *request) {
565 struct http_header *header;
566 if (request == NULL) return HTTP_ERROR_SERVER;
568 for (header = request->headers; header != NULL; header = header->next) {
569 if (header->name == NULL) continue;
570 if (!strcasecmp(header->name, "Content-Length")) break;
573 if (header != NULL && header->value != NULL) {
574 char *p;
575 long long int value = strtol(header->value, &p, 10);
576 if (*p != '\0')
577 return HTTP_ERROR_CLIENT;
578 if ((value == LLONG_MIN || value == LLONG_MAX) && errno == ERANGE)
579 return HTTP_ERROR_SERVER;
580 if (value < 0)
581 return HTTP_ERROR_CLIENT;
582 if (value > SIZE_MAX)
583 return HTTP_ERROR_SERVER;
584 request->body_length = value;
585 } else {
586 request->body_length = 0;
588 return HTTP_ERROR_SUCCESS;
592 /* Print binary stream to STDERR with some escapes */
593 static void dump_body(const void *data, size_t length) {
594 fprintf(stderr, "===BEGIN BODY===\n");
595 if (length > 0 && NULL != data) {
596 for (size_t i = 0; i < length; i++) {
597 if (isprint(((const unsigned char *)data)[i]))
598 fprintf(stderr, "%c", ((const unsigned char *)data)[i]);
599 else
600 fprintf(stderr, "\\x%02x", ((const unsigned char*)data)[i]);
602 fprintf(stderr, "\n");
604 fprintf(stderr, "===END BODY===\n");
608 /* Read a HTTP request from connected socket.
609 * @http_request is heap-allocated received HTTP request,
610 * or NULL in case of error.
611 * @return http_error code. */
612 http_error http_read_request(int socket, struct http_request **request) {
613 char *line = NULL;
614 char *buffer = NULL;
615 size_t buffer_size = 0, buffer_used = 0;
616 int error;
618 if (request == NULL) return HTTP_ERROR_SERVER;
620 *request = calloc(1, sizeof(**request));
621 if (*request == NULL) return HTTP_ERROR_SERVER;
623 /* Get request header */
624 if ((error = http_read_line(socket, &line, &buffer, &buffer_size,
625 &buffer_used)))
626 goto leave;
627 if ((error = http_parse_request_header(line, *request)))
628 goto leave;
630 /* Get other headers */
631 while (1) {
632 if ((error = http_read_line(socket, &line, &buffer, &buffer_size,
633 &buffer_used))) {
634 fprintf(stderr, "Error while reading HTTP request line\n");
635 goto leave;
638 /* Check for headers delimiter */
639 if (line == NULL || *line == '\0') {
640 break;
643 if ((error = http_parse_header(line, *request))) {
644 fprintf(stderr, "Error while parsing HTTP request line: <%s>\n",
645 line);
646 goto leave;
650 /* Get body */
651 if ((error = find_content_length(*request))) {
652 fprintf(stderr, "Could not determine length of body\n");
653 goto leave;
655 if ((error = http_read_bulk(socket,
656 &(*request)->body, (*request)->body_length,
657 &buffer, &buffer_size, &buffer_used))) {
658 fprintf(stderr, "Could not read request body\n");
659 goto leave;
661 fprintf(stderr, "Body of size %zu B has been received:\n",
662 (*request)->body_length);
663 dump_body((*request)->body, (*request)->body_length);
665 leave:
666 free(line);
667 free(buffer);
668 if (error) http_request_free(request);
669 return error;
673 /* Write a HTTP response to connected socket. Auto-add Content-Length header.
674 * @return 0 in case of success. */
675 int http_write_response(int socket, const struct http_response *response) {
676 char *buffer = NULL;
677 int error = -1;
679 if (response == NULL) return HTTP_ERROR_SERVER;
681 /* Status line */
682 error = http_write_response_status(socket, response);
683 if (error) return error;
685 /* Headers */
686 for (struct http_header *header = response->headers; header != NULL;
687 header = header->next) {
688 error = http_write_header(socket, header);
689 if (error) return error;
691 if (-1 == test_asprintf(&buffer, "Content-Length: %u",
692 response->body_length))
693 return HTTP_ERROR_SERVER;
694 error = http_write_line(socket, buffer);
695 if (error) return error;
697 /* Headers trailer */
698 error = http_write_line(socket, "");
699 if (error) return error;
701 /* Body */
702 if (response->body_length > 0) {
703 error = http_write_bulk(socket, response->body, response->body_length);
704 if (error) return error;
706 fprintf(stderr, "Body of size %zu B has been sent:\n",
707 response->body_length);
708 dump_body(response->body, response->body_length);
710 free(buffer);
711 return HTTP_ERROR_SUCCESS;
715 /* Build Set-Cookie header. In case of error, return NULL. Caller must free
716 * the header. */
717 static struct http_header *http_build_setcookie_header (
718 const char *cokie_name, const char *cookie_value,
719 const char *cookie_domain, const char *cookie_path) {
720 struct http_header *header = NULL;
721 char *domain_parameter = NULL;
722 char *path_parameter = NULL;
724 if (cokie_name == NULL) goto error;
726 header = calloc(1, sizeof(*header));
727 if (header == NULL) goto error;
729 header->name = strdup("Set-Cookie");
730 if (header->name == NULL) goto error;
732 if (cookie_domain != NULL)
733 if (-1 == test_asprintf(&domain_parameter, "; Domain=%s",
734 cookie_domain))
735 goto error;
737 if (cookie_path != NULL)
738 if (-1 == test_asprintf(&path_parameter, "; Path=%s",
739 cookie_path))
740 goto error;
742 if (-1 == test_asprintf(&header->value, "%s=%s%s%s",
743 cokie_name,
744 (cookie_value == NULL) ? "" : cookie_value,
745 (domain_parameter == NULL) ? "": domain_parameter,
746 (path_parameter == NULL) ? "": path_parameter))
747 goto error;
748 goto ok;
750 error:
751 http_header_free(&header);
753 free(domain_parameter);
754 free(path_parameter);
755 return header;
759 /* Send a 200 Ok response with a cookie */
760 int http_send_response_200_cookie(int client_socket,
761 const char *cokie_name, const char *cookie_value,
762 const char *cookie_domain, const char *cookie_path,
763 const void *body, size_t body_length, const char *type) {
764 int retval;
765 struct http_header *header_cookie = NULL;
766 struct http_header header_contenttype = {
767 .name = "Content-Type",
768 .value = (char *)type,
769 .next = NULL
771 struct http_response response = {
772 .status = 200,
773 .reason = "OK",
774 .headers = NULL,
775 .body_length = body_length,
776 .body = (void *)body
779 if (cokie_name != NULL) {
780 if (NULL == (header_cookie = http_build_setcookie_header(
781 cokie_name, cookie_value, cookie_domain, cookie_path)))
782 return http_send_response_500(client_socket,
783 "Could not build Set-Cookie header");
786 /* Link defined headers */
787 if (type != NULL) {
788 response.headers = &header_contenttype;
790 if (header_cookie != NULL) {
791 header_cookie->next = response.headers;
792 response.headers = header_cookie;
795 retval = http_write_response(client_socket, &response);
796 http_header_free(&header_cookie);
797 return retval;
801 /* Send a 200 Ok response */
802 int http_send_response_200(int client_socket,
803 const void *body, size_t body_length, const char *type) {
804 return http_send_response_200_cookie(client_socket,
805 NULL, NULL, NULL, NULL,
806 body, body_length, type);
810 /* Send a 302 Found response setting a cookie */
811 int http_send_response_302_cookie(int client_socket, const char *cokie_name,
812 const char *cookie_value, const char *cookie_domain,
813 const char *cookie_path, const char *location) {
814 int retval;
815 struct http_header *header_cookie = NULL;
816 struct http_header header_location = {
817 .name = "Location",
818 .value = (char *) location,
819 .next = NULL
821 struct http_response response = {
822 .status = 302,
823 .reason = "Found",
824 .headers = NULL,
825 .body_length = 0,
826 .body = NULL
829 if (cokie_name != NULL) {
830 if (NULL == (header_cookie = http_build_setcookie_header(
831 cokie_name, cookie_value, cookie_domain, cookie_path)))
832 return http_send_response_500(client_socket,
833 "Could not build Set-Cookie header");
836 /* Link defined headers */
837 if (location != NULL) {
838 response.headers = &header_location;
840 if (header_cookie != NULL) {
841 header_cookie->next = response.headers;
842 response.headers = header_cookie;
845 retval = http_write_response(client_socket, &response);
846 http_header_free(&header_cookie);
847 return retval;
851 /* Send a 302 Found response with totp authentication scheme header */
852 int http_send_response_302_totp(int client_socket,
853 const char *code, const char *text, const char *location) {
854 struct http_header header_code = {
855 .name = "X-Response-message-code",
856 .value = (char *) code,
857 .next = NULL
859 struct http_header header_text = {
860 .name = "X-Response-message-text",
861 .value = (char *) text,
862 .next = NULL
864 struct http_header header_location = {
865 .name = "Location",
866 .value = (char *) location,
867 .next = NULL
869 struct http_response response = {
870 .status = 302,
871 .reason = "Found",
872 .headers = NULL,
873 .body_length = 0,
874 .body = NULL
877 /* Link defined headers */
878 if (location != NULL) {
879 response.headers = &header_location;
881 if (text != NULL) {
882 header_text.next = response.headers;
883 response.headers = &header_text;
885 if (code != NULL) {
886 header_code.next = response.headers;
887 response.headers = &header_code;
890 return http_write_response(client_socket, &response);
894 /* Send a 400 Bad Request response.
895 * Use non-NULL @reason to override status message. */
896 int http_send_response_400(int client_socket, const char *reason) {
897 struct http_response response = {
898 .status = 400,
899 .reason = (reason == NULL) ? "Bad Request" : (char *) reason,
900 .headers = NULL,
901 .body_length = 0,
902 .body = NULL
905 return http_write_response(client_socket, &response);
909 /* Send a 401 Unauthorized response with Basic authentication scheme header */
910 int http_send_response_401_basic(int client_socket) {
911 struct http_header header = {
912 .name = "WWW-Authenticate",
913 .value = "Basic realm=\"SimulatedISDSServer\"",
914 .next = NULL
916 struct http_response response = {
917 .status = 401,
918 .reason = "Unauthorized",
919 .headers = &header,
920 .body_length = 0,
921 .body = NULL
924 return http_write_response(client_socket, &response);
928 /* Send a 401 Unauthorized response with OTP authentication scheme header for
929 * given @method. */
930 int http_send_response_401_otp(int client_socket,
931 const char *method, const char *code, const char *text) {
932 int retval;
933 struct http_header header = {
934 .name = "WWW-Authenticate",
935 .value = NULL,
936 .next = NULL
938 struct http_header header_code = {
939 .name = "X-Response-message-code",
940 .value = (char *) code,
941 .next = NULL
943 struct http_header header_text = {
944 .name = "X-Response-message-text",
945 .value = (char *) text,
946 .next = NULL
948 struct http_response response = {
949 .status = 401,
950 .reason = "Unauthorized",
951 .headers = &header,
952 .body_length = 0,
953 .body = NULL
956 if (-1 == test_asprintf(&header.value, "%s realm=\"SimulatedISDSServer\"",
957 method)) {
958 return http_send_response_500(client_socket,
959 "Could not build WWW-Authenticate header value");
962 /* Link defined headers */
963 if (code != NULL) header.next = &header_code;
964 if (text != NULL) {
965 if (code != NULL)
966 header_code.next = &header_text;
967 else
968 header.next = &header_text;
971 retval = http_write_response(client_socket, &response);
972 free(header.value);
973 return retval;
977 /* Send a 403 Forbidden response */
978 int http_send_response_403(int client_socket) {
979 struct http_response response = {
980 .status = 403,
981 .reason = "Forbidden",
982 .headers = NULL,
983 .body_length = 0,
984 .body = NULL
987 return http_write_response(client_socket, &response);
991 /* Send a 500 Internal Server Error response.
992 * Use non-NULL @reason to override status message. */
993 int http_send_response_500(int client_socket, const char *reason) {
994 struct http_response response = {
995 .status = 500,
996 .reason = (NULL == reason) ? "Internal Server Error" : (char *) reason,
997 .headers = NULL,
998 .body_length = 0,
999 .body = NULL
1002 return http_write_response(client_socket, &response);
1006 /* Send a 503 Service Temporarily Unavailable response */
1007 int http_send_response_503(int client_socket,
1008 const void *body, size_t body_length, const char *type) {
1009 struct http_header header = {
1010 .name = "Content-Type",
1011 .value = (char *)type
1013 struct http_response response = {
1014 .status = 503,
1015 .reason = "Service Temporarily Unavailable",
1016 .headers = (type == NULL) ? NULL : &header,
1017 .body_length = body_length,
1018 .body = (void *)body
1021 return http_write_response(client_socket, &response);
1025 /* Returns Authorization header in given request */
1026 static const struct http_header *find_authorization(
1027 const struct http_request *request) {
1028 const struct http_header *header;
1029 if (request == NULL) return NULL;
1030 for (header = request->headers; header != NULL; header = header->next) {
1031 if (header->name != NULL &&
1032 !strcasecmp(header->name, "Authorization"))
1033 break;
1035 return header;
1039 /* Return true if request carries Authorization header */
1040 int http_client_authenticates(const struct http_request *request) {
1041 if (find_authorization(request))
1042 return 1;
1043 else
1044 return 0;
1048 /* Return HTTP_ERROR_SUCCESS if request carries valid Basic credentials.
1049 * NULL @username or @password equales to empty string. */
1050 http_error http_authenticate_basic(const struct http_request *request,
1051 const char *username, const char *password) {
1052 const struct http_header *header;
1053 const char *basic_cookie_client;
1054 char *basic_cookie_plain = NULL, *basic_cookie_encoded = NULL;
1055 _Bool is_valid;
1057 header = find_authorization(request);
1058 if (header == NULL) return HTTP_ERROR_CLIENT;
1060 if (strncmp(header->value, "Basic ", 6)) return HTTP_ERROR_CLIENT;
1061 basic_cookie_client = header->value + 6;
1063 if (-1 == test_asprintf(&basic_cookie_plain, "%s:%s",
1064 (username == NULL) ? "" : username,
1065 (password == NULL) ? "" : password)) {
1066 return HTTP_ERROR_SERVER;
1069 basic_cookie_encoded = base64encode(basic_cookie_plain,
1070 strlen(basic_cookie_plain), 1);
1071 if (basic_cookie_encoded == NULL) {
1072 free(basic_cookie_plain);
1073 return HTTP_ERROR_SERVER;
1076 fprintf(stderr, "Authenticating basic: got=<%s>, expected=<%s> (%s)\n",
1077 basic_cookie_client, basic_cookie_encoded, basic_cookie_plain);
1078 free(basic_cookie_plain);
1080 is_valid = !strcmp(basic_cookie_encoded, basic_cookie_client);
1081 free(basic_cookie_encoded);
1083 return (is_valid) ? HTTP_ERROR_SUCCESS : HTTP_ERROR_CLIENT;
1087 /* Return HTTP_ERROR_SUCCESS if request carries valid OTP credentials.
1088 * NULL @username or @password or @otp equal to empty string. */
1089 http_error http_authenticate_otp(const struct http_request *request,
1090 const char *username, const char *password, const char *otp) {
1091 char *basic_password = NULL;
1092 http_error retval;
1094 /* Concatenate password and OTP code */
1095 if (-1 == test_asprintf(&basic_password, "%s%s",
1096 (password == NULL) ? "": password,
1097 (otp == NULL) ? "" : otp)) {
1098 return HTTP_ERROR_SERVER;
1101 /* Use Basic authentication */
1102 /* XXX: Specification does not define authorization method string */
1103 retval = http_authenticate_basic(request, username, basic_password);
1105 free(basic_password);
1106 return retval;
1110 /* Return cookie value by name or NULL if does not present. */
1111 const char *http_find_cookie(const struct http_request *request,
1112 const char *name) {
1113 const struct http_header *header;
1114 size_t length;
1115 const char *value = NULL;
1117 if (request == NULL || name == NULL) return NULL;
1118 length = strlen(name);
1120 for (header = request->headers; header != NULL; header = header->next) {
1121 if (header->name != NULL && !strcasecmp(header->name, "Cookie") &&
1122 header->value != NULL) {
1123 if (!strncmp(header->value, name, length) &&
1124 header->value[length] == '=') {
1125 /* Return last cookie with the name */
1126 value = header->value + length + 1;
1130 return value;
1134 /* Return Host header value or NULL if does not present. Returned string is
1135 * statically allocated. */
1136 const char *http_find_host(const struct http_request *request) {
1137 const struct http_header *header;
1138 const char *value = NULL;
1140 if (request == NULL) return NULL;
1142 for (header = request->headers; header != NULL; header = header->next) {
1143 if (header->name != NULL && !strcmp(header->name, "Host")) {
1144 value = header->value;
1147 return value;
1151 /* Free a HTTP header and set it to NULL */
1152 void http_header_free(struct http_header **header) {
1153 if (header == NULL || *header == NULL) return;
1154 free((*header)->name);
1155 free((*header)->value);
1156 free(*header);
1157 *header = NULL;
1161 /* Free linked list of HTTP headers and set it to NULL */
1162 void http_headers_free(struct http_header **headers) {
1163 struct http_header *header, *next;
1165 if (headers == NULL || *headers == NULL) return;
1167 for (header = *headers; header != NULL;) {
1168 next = header->next;
1169 http_header_free(&header);
1170 header = next;
1173 *headers = NULL;
1176 /* Free HTTP request and set it to NULL */
1177 void http_request_free(struct http_request **request) {
1178 if (request == NULL || *request == NULL) return;
1179 free((*request)->uri);
1180 http_headers_free(&((*request)->headers));
1181 free((*request)->body);
1182 free(*request);
1183 *request = NULL;
1186 /* Free HTTP response and set it to NULL */
1187 void http_response_free(struct http_response **response) {
1188 if (response == NULL || *response == NULL) return;
1189 free((*response)->reason);
1190 http_headers_free(&((*response)->headers));
1191 free((*response)->body);
1192 free(*response);
1193 *response = NULL;