test: server: do socket I/O by call-backs
[libisds.git] / test / simline / http.c
blobd72b5472db9748a35720f3f86a27e2c598bafd36
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;
237 /* Read a line from HTTP socket.
238 * @socket is descriptor to read from.
239 * @line is auto-allocated just read line. Will be NULL if EOF has been
240 * reached or error occured.
241 * @buffer is automatically reallocated buffer for the socket. It can preserve
242 * prematurately read socket data.
243 * @buffer_size is allocated size of @buffer
244 * @buffer_length is size of head of the buffer that holds read data.
245 * @return 0 in success. */
246 static int http_read_line(int socket, char **line,
247 char **buffer, size_t *buffer_size, size_t *buffer_used) {
248 ssize_t got;
249 char *p, *tmp;
251 if (line == NULL) return HTTP_ERROR_SERVER;
252 *line = NULL;
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 = http_recv_callback(socket, *buffer + *buffer_used,
296 *buffer_size - *buffer_used, 0);
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 * @socket is descriptor 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(int socket, const void *data, size_t length) {
317 ssize_t written;
318 const void *end;
320 if (data == NULL && length > 0) return HTTP_ERROR_SERVER;
322 for (end = data + length; data != end; data += written, length -= written) {
323 written = http_send_callback(socket, data, length, MSG_NOSIGNAL);
324 if (written == -1) return HTTP_ERROR_CLIENT;
327 return HTTP_ERROR_SUCCESS;
331 /* Write a line into HTTP socket.
332 * @socket is descriptor to write to.
333 * @line is NULL terminated string to send to client. HTTP EOL will be added.
334 * @return 0 in success. */
335 static int http_write_line(int socket, const char *line) {
336 int error;
337 if (line == NULL) return HTTP_ERROR_SERVER;
339 fprintf(stderr, "Response: <%s>\n", line);
341 /* Send the line */
342 if ((error = http_write_bulk(socket, line, strlen(line))))
343 return error;
345 /* Send EOL */
346 if ((error = http_write_bulk(socket, "\r\n", 2)))
347 return error;
349 return HTTP_ERROR_SUCCESS;
353 /* Read data of given length from HTTP socket.
354 * @socket is descriptor to read from.
355 * @data is auto-allocated just read data bulk. Will be NULL if EOF has been
356 * reached or error occured.
357 * @data_length is size of bytes to read.
358 * @buffer is automatically reallocated buffer for the socket. It can preserve
359 * prematurately read socket data.
360 * @buffer_size is allocated size of @buffer
361 * @buffer_length is size of head of the buffer that holds read data.
362 * @return 0 in success. */
363 static int http_read_bulk(int socket, void **data, size_t data_length,
364 char **buffer, size_t *buffer_size, size_t *buffer_used) {
365 ssize_t got;
366 char *tmp;
368 if (data == NULL) return HTTP_ERROR_SERVER;
369 *data = NULL;
371 if (buffer == NULL || buffer_size == NULL || buffer_used == NULL)
372 return HTTP_ERROR_SERVER;
373 if (*buffer == NULL && *buffer_size > 0) return HTTP_ERROR_SERVER;
374 if (*buffer_size < *buffer_used) return HTTP_ERROR_SERVER;
376 if (data_length <= 0) return HTTP_ERROR_SUCCESS;
378 #define BURST 1024
379 while (1) {
380 /* Check whether enought data have been read */
381 if (*buffer_used >= data_length) {
382 /* Copy read ahead data to new buffer and point data to original
383 * buffer. */
384 tmp = malloc(BURST);
385 if (tmp == NULL) return HTTP_ERROR_SERVER;
386 memcpy(tmp, *buffer + data_length, *buffer_used - data_length);
387 *data = *buffer;
388 *buffer_size = BURST;
389 *buffer_used = *buffer_used - data_length;
390 *buffer = tmp;
391 /* And exit */
392 return HTTP_ERROR_SUCCESS;
395 if (*buffer_size == *buffer_used) {
396 /* Grow buffer */
397 tmp = realloc(*buffer, *buffer_size + BURST);
398 if (tmp == NULL) return HTTP_ERROR_SERVER;
399 *buffer = tmp;
400 *buffer_size += BURST;
403 /* Read data */
404 got = http_recv_callback(socket, *buffer + *buffer_used,
405 *buffer_size - *buffer_used, 0);
406 if (got == -1) return HTTP_ERROR_CLIENT;
408 /* Check for EOF */
409 if (got == 0) return HTTP_ERROR_CLIENT;
411 /* Move end of buffer */
412 *buffer_used += got;
414 #undef BURST
416 return HTTP_ERROR_SERVER;
420 /* Parse HTTP request header.
421 * @request is pre-allocated HTTP request.
422 * @return 0 if success. */
423 static int http_parse_request_header(char *line,
424 struct http_request *request) {
425 char *p;
427 fprintf(stderr, "Request: <%s>\n", line);
429 /* Get method */
430 p = strchr(line, ' ');
431 if (p == NULL) return HTTP_ERROR_SERVER;
432 *p = '\0';
433 if (!strcmp(line, "GET"))
434 request->method = HTTP_METHOD_GET;
435 else if (!strcmp(line, "POST"))
436 request->method = HTTP_METHOD_POST;
437 else
438 request->method = HTTP_METHOD_UNKNOWN;
439 line = p + 1;
441 /* Get URI */
442 p = strchr(line, ' ');
443 if (p != NULL) *p = '\0';
444 request->uri = uri_decode(line);
445 if (request->uri == NULL) return HTTP_ERROR_SERVER;
447 /* Do not care about HTTP version */
449 fprintf(stderr, "Request-URI: <%s>\n", request->uri);
450 return HTTP_ERROR_SUCCESS;
454 /* Send HTTP response status line to client.
455 * @return 0 if success. */
456 static int http_write_response_status(int socket,
457 const struct http_response *response) {
458 char *buffer = NULL;
459 int error;
461 if (response == NULL) return HTTP_ERROR_SERVER;
463 if (-1 == test_asprintf(&buffer, "HTTP/1.0 %u %s", response->status,
464 (response->reason == NULL) ? "" : response->reason))
465 return HTTP_ERROR_SERVER;
466 error = http_write_line(socket, buffer);
467 free(buffer);
469 return error;
473 /* Parse generic HTTP header.
474 * @request is pre-allocated HTTP request.
475 * @return 0 if success, negative value if internal error, positive value if
476 * header is not valid. */
477 static int http_parse_header(char *line, struct http_request *request) {
478 struct http_header *header;
480 if (line == NULL || request == NULL) return HTTP_ERROR_SERVER;
482 fprintf(stderr, "Header: <%s>\n", line);
484 /* Find last used header */
485 for (header = request->headers; header != NULL && header->next != NULL;
486 header = header->next);
488 if (*line == ' ' || *line == '\t') {
489 /* Line is continuation of last header */
490 if (header == NULL)
491 return HTTP_ERROR_CLIENT; /* No previous header to continue */
492 line++;
493 size_t old_length = strlen(header->value);
494 char *tmp = realloc(header->value,
495 sizeof(header->value[0]) * (old_length + strlen(line) + 1));
496 if (tmp == NULL) return HTTP_ERROR_SERVER;
497 header->value = tmp;
498 strcpy(&header->value[old_length], line);
499 } else {
500 /* New header */
501 struct http_header *new_header = calloc(sizeof(*new_header), 1);
502 if (new_header == NULL) return HTTP_ERROR_SERVER;
504 char *p = strstr(line, ": ");
505 if (p == NULL) return HTTP_ERROR_CLIENT;
507 size_t length = p - line;
508 new_header->name = malloc(sizeof(line[0]) * (length + 1));
509 if (new_header->name == NULL) {
510 http_header_free(&new_header);
511 return HTTP_ERROR_SERVER;
513 strncpy(new_header->name, line, length);
514 new_header->name[length] = '\0';
516 p += 2;
517 length = strlen(p);
518 new_header->value = malloc(sizeof(p[0]) * (length + 1));
519 if (new_header->value == NULL) {
520 http_header_free(&new_header);
521 return HTTP_ERROR_SERVER;
523 strcpy(new_header->value, p);
525 if (request->headers == NULL)
526 request->headers = new_header;
527 else
528 header->next = new_header;
532 /* FIXME: Decode. After parsing all headers as we could decode begining
533 * and then got encoded continuation. */
534 return HTTP_ERROR_SUCCESS;
538 /* Send HTTP header to client.
539 * @return 0 if success. */
540 static int http_write_header(int socket, const struct http_header *header) {
541 char *buffer = NULL;
542 int error;
544 if (header == NULL) return HTTP_ERROR_SERVER;
546 if (header->name == NULL) return HTTP_ERROR_SERVER;
548 /* TODO: Quote, split long lines */
549 if (-1 == test_asprintf(&buffer, "%s: %s", header->name,
550 (header->value == NULL) ? "" : header->value))
551 return HTTP_ERROR_SERVER;
552 error = http_write_line(socket, buffer);
553 free(buffer);
555 return error;
559 /* Find Content-Length value in HTTP request headers and set it into @request.
560 * @return 0 in success. */
561 static int find_content_length(struct http_request *request) {
562 struct http_header *header;
563 if (request == NULL) return HTTP_ERROR_SERVER;
565 for (header = request->headers; header != NULL; header = header->next) {
566 if (header->name == NULL) continue;
567 if (!strcasecmp(header->name, "Content-Length")) break;
570 if (header != NULL && header->value != NULL) {
571 char *p;
572 long long int value = strtol(header->value, &p, 10);
573 if (*p != '\0')
574 return HTTP_ERROR_CLIENT;
575 if ((value == LLONG_MIN || value == LLONG_MAX) && errno == ERANGE)
576 return HTTP_ERROR_SERVER;
577 if (value < 0)
578 return HTTP_ERROR_CLIENT;
579 if (value > SIZE_MAX)
580 return HTTP_ERROR_SERVER;
581 request->body_length = value;
582 } else {
583 request->body_length = 0;
585 return HTTP_ERROR_SUCCESS;
589 /* Print binary stream to STDERR with some escapes */
590 static void dump_body(const void *data, size_t length) {
591 fprintf(stderr, "===BEGIN BODY===\n");
592 if (length > 0 && NULL != data) {
593 for (size_t i = 0; i < length; i++) {
594 if (isprint(((const unsigned char *)data)[i]))
595 fprintf(stderr, "%c", ((const unsigned char *)data)[i]);
596 else
597 fprintf(stderr, "\\x%02x", ((const unsigned char*)data)[i]);
599 fprintf(stderr, "\n");
601 fprintf(stderr, "===END BODY===\n");
605 /* Read a HTTP request from connected socket.
606 * @http_request is heap-allocated received HTTP request,
607 * or NULL in case of error.
608 * @return http_error code. */
609 http_error http_read_request(int socket, struct http_request **request) {
610 char *line = NULL;
611 char *buffer = NULL;
612 size_t buffer_size = 0, buffer_used = 0;
613 int error;
615 if (request == NULL) return HTTP_ERROR_SERVER;
617 *request = calloc(1, sizeof(**request));
618 if (*request == NULL) return HTTP_ERROR_SERVER;
620 /* Get request header */
621 if ((error = http_read_line(socket, &line, &buffer, &buffer_size,
622 &buffer_used)))
623 goto leave;
624 if ((error = http_parse_request_header(line, *request)))
625 goto leave;
627 /* Get other headers */
628 while (1) {
629 if ((error = http_read_line(socket, &line, &buffer, &buffer_size,
630 &buffer_used))) {
631 fprintf(stderr, "Error while reading HTTP request line\n");
632 goto leave;
635 /* Check for headers delimiter */
636 if (line == NULL || *line == '\0') {
637 break;
640 if ((error = http_parse_header(line, *request))) {
641 fprintf(stderr, "Error while parsing HTTP request line: <%s>\n",
642 line);
643 goto leave;
647 /* Get body */
648 if ((error = find_content_length(*request))) {
649 fprintf(stderr, "Could not determine length of body\n");
650 goto leave;
652 if ((error = http_read_bulk(socket,
653 &(*request)->body, (*request)->body_length,
654 &buffer, &buffer_size, &buffer_used))) {
655 fprintf(stderr, "Could not read request body\n");
656 goto leave;
658 fprintf(stderr, "Body of size %zu B has been received:\n",
659 (*request)->body_length);
660 dump_body((*request)->body, (*request)->body_length);
662 leave:
663 free(line);
664 free(buffer);
665 if (error) http_request_free(request);
666 return error;
670 /* Write a HTTP response to connected socket. Auto-add Content-Length header.
671 * @return 0 in case of success. */
672 int http_write_response(int socket, const struct http_response *response) {
673 char *buffer = NULL;
674 int error = -1;
676 if (response == NULL) return HTTP_ERROR_SERVER;
678 /* Status line */
679 error = http_write_response_status(socket, response);
680 if (error) return error;
682 /* Headers */
683 for (struct http_header *header = response->headers; header != NULL;
684 header = header->next) {
685 error = http_write_header(socket, header);
686 if (error) return error;
688 if (-1 == test_asprintf(&buffer, "Content-Length: %u",
689 response->body_length))
690 return HTTP_ERROR_SERVER;
691 error = http_write_line(socket, buffer);
692 if (error) return error;
694 /* Headers trailer */
695 error = http_write_line(socket, "");
696 if (error) return error;
698 /* Body */
699 if (response->body_length > 0) {
700 error = http_write_bulk(socket, response->body, response->body_length);
701 if (error) return error;
703 fprintf(stderr, "Body of size %zu B has been sent:\n",
704 response->body_length);
705 dump_body(response->body, response->body_length);
707 free(buffer);
708 return HTTP_ERROR_SUCCESS;
712 /* Build Set-Cookie header. In case of error, return NULL. Caller must free
713 * the header. */
714 static struct http_header *http_build_setcookie_header (
715 const char *cokie_name, const char *cookie_value,
716 const char *cookie_domain, const char *cookie_path) {
717 struct http_header *header = NULL;
718 char *domain_parameter = NULL;
719 char *path_parameter = NULL;
721 if (cokie_name == NULL) goto error;
723 header = calloc(1, sizeof(*header));
724 if (header == NULL) goto error;
726 header->name = strdup("Set-Cookie");
727 if (header->name == NULL) goto error;
729 if (cookie_domain != NULL)
730 if (-1 == test_asprintf(&domain_parameter, "; Domain=%s",
731 cookie_domain))
732 goto error;
734 if (cookie_path != NULL)
735 if (-1 == test_asprintf(&path_parameter, "; Path=%s",
736 cookie_path))
737 goto error;
739 if (-1 == test_asprintf(&header->value, "%s=%s%s%s",
740 cokie_name,
741 (cookie_value == NULL) ? "" : cookie_value,
742 (domain_parameter == NULL) ? "": domain_parameter,
743 (path_parameter == NULL) ? "": path_parameter))
744 goto error;
745 goto ok;
747 error:
748 http_header_free(&header);
750 free(domain_parameter);
751 free(path_parameter);
752 return header;
756 /* Send a 200 Ok response with a cookie */
757 int http_send_response_200_cookie(int client_socket,
758 const char *cokie_name, const char *cookie_value,
759 const char *cookie_domain, const char *cookie_path,
760 const void *body, size_t body_length, const char *type) {
761 int retval;
762 struct http_header *header_cookie = NULL;
763 struct http_header header_contenttype = {
764 .name = "Content-Type",
765 .value = (char *)type,
766 .next = NULL
768 struct http_response response = {
769 .status = 200,
770 .reason = "OK",
771 .headers = NULL,
772 .body_length = body_length,
773 .body = (void *)body
776 if (cokie_name != NULL) {
777 if (NULL == (header_cookie = http_build_setcookie_header(
778 cokie_name, cookie_value, cookie_domain, cookie_path)))
779 return http_send_response_500(client_socket,
780 "Could not build Set-Cookie header");
783 /* Link defined headers */
784 if (type != NULL) {
785 response.headers = &header_contenttype;
787 if (header_cookie != NULL) {
788 header_cookie->next = response.headers;
789 response.headers = header_cookie;
792 retval = http_write_response(client_socket, &response);
793 http_header_free(&header_cookie);
794 return retval;
798 /* Send a 200 Ok response */
799 int http_send_response_200(int client_socket,
800 const void *body, size_t body_length, const char *type) {
801 return http_send_response_200_cookie(client_socket,
802 NULL, NULL, NULL, NULL,
803 body, body_length, type);
807 /* Send a 302 Found response setting a cookie */
808 int http_send_response_302_cookie(int client_socket, const char *cokie_name,
809 const char *cookie_value, const char *cookie_domain,
810 const char *cookie_path, const char *location) {
811 int retval;
812 struct http_header *header_cookie = NULL;
813 struct http_header header_location = {
814 .name = "Location",
815 .value = (char *) location,
816 .next = NULL
818 struct http_response response = {
819 .status = 302,
820 .reason = "Found",
821 .headers = NULL,
822 .body_length = 0,
823 .body = NULL
826 if (cokie_name != NULL) {
827 if (NULL == (header_cookie = http_build_setcookie_header(
828 cokie_name, cookie_value, cookie_domain, cookie_path)))
829 return http_send_response_500(client_socket,
830 "Could not build Set-Cookie header");
833 /* Link defined headers */
834 if (location != NULL) {
835 response.headers = &header_location;
837 if (header_cookie != NULL) {
838 header_cookie->next = response.headers;
839 response.headers = header_cookie;
842 retval = http_write_response(client_socket, &response);
843 http_header_free(&header_cookie);
844 return retval;
848 /* Send a 302 Found response with totp authentication scheme header */
849 int http_send_response_302_totp(int client_socket,
850 const char *code, const char *text, const char *location) {
851 struct http_header header_code = {
852 .name = "X-Response-message-code",
853 .value = (char *) code,
854 .next = NULL
856 struct http_header header_text = {
857 .name = "X-Response-message-text",
858 .value = (char *) text,
859 .next = NULL
861 struct http_header header_location = {
862 .name = "Location",
863 .value = (char *) location,
864 .next = NULL
866 struct http_response response = {
867 .status = 302,
868 .reason = "Found",
869 .headers = NULL,
870 .body_length = 0,
871 .body = NULL
874 /* Link defined headers */
875 if (location != NULL) {
876 response.headers = &header_location;
878 if (text != NULL) {
879 header_text.next = response.headers;
880 response.headers = &header_text;
882 if (code != NULL) {
883 header_code.next = response.headers;
884 response.headers = &header_code;
887 return http_write_response(client_socket, &response);
891 /* Send a 400 Bad Request response.
892 * Use non-NULL @reason to override status message. */
893 int http_send_response_400(int client_socket, const char *reason) {
894 struct http_response response = {
895 .status = 400,
896 .reason = (reason == NULL) ? "Bad Request" : (char *) reason,
897 .headers = NULL,
898 .body_length = 0,
899 .body = NULL
902 return http_write_response(client_socket, &response);
906 /* Send a 401 Unauthorized response with Basic authentication scheme header */
907 int http_send_response_401_basic(int client_socket) {
908 struct http_header header = {
909 .name = "WWW-Authenticate",
910 .value = "Basic realm=\"SimulatedISDSServer\"",
911 .next = NULL
913 struct http_response response = {
914 .status = 401,
915 .reason = "Unauthorized",
916 .headers = &header,
917 .body_length = 0,
918 .body = NULL
921 return http_write_response(client_socket, &response);
925 /* Send a 401 Unauthorized response with OTP authentication scheme header for
926 * given @method. */
927 int http_send_response_401_otp(int client_socket,
928 const char *method, const char *code, const char *text) {
929 int retval;
930 struct http_header header = {
931 .name = "WWW-Authenticate",
932 .value = NULL,
933 .next = NULL
935 struct http_header header_code = {
936 .name = "X-Response-message-code",
937 .value = (char *) code,
938 .next = NULL
940 struct http_header header_text = {
941 .name = "X-Response-message-text",
942 .value = (char *) text,
943 .next = NULL
945 struct http_response response = {
946 .status = 401,
947 .reason = "Unauthorized",
948 .headers = &header,
949 .body_length = 0,
950 .body = NULL
953 if (-1 == test_asprintf(&header.value, "%s realm=\"SimulatedISDSServer\"",
954 method)) {
955 return http_send_response_500(client_socket,
956 "Could not build WWW-Authenticate header value");
959 /* Link defined headers */
960 if (code != NULL) header.next = &header_code;
961 if (text != NULL) {
962 if (code != NULL)
963 header_code.next = &header_text;
964 else
965 header.next = &header_text;
968 retval = http_write_response(client_socket, &response);
969 free(header.value);
970 return retval;
974 /* Send a 403 Forbidden response */
975 int http_send_response_403(int client_socket) {
976 struct http_response response = {
977 .status = 403,
978 .reason = "Forbidden",
979 .headers = NULL,
980 .body_length = 0,
981 .body = NULL
984 return http_write_response(client_socket, &response);
988 /* Send a 500 Internal Server Error response.
989 * Use non-NULL @reason to override status message. */
990 int http_send_response_500(int client_socket, const char *reason) {
991 struct http_response response = {
992 .status = 500,
993 .reason = (NULL == reason) ? "Internal Server Error" : (char *) reason,
994 .headers = NULL,
995 .body_length = 0,
996 .body = NULL
999 return http_write_response(client_socket, &response);
1003 /* Send a 503 Service Temporarily Unavailable response */
1004 int http_send_response_503(int client_socket,
1005 const void *body, size_t body_length, const char *type) {
1006 struct http_header header = {
1007 .name = "Content-Type",
1008 .value = (char *)type
1010 struct http_response response = {
1011 .status = 503,
1012 .reason = "Service Temporarily Unavailable",
1013 .headers = (type == NULL) ? NULL : &header,
1014 .body_length = body_length,
1015 .body = (void *)body
1018 return http_write_response(client_socket, &response);
1022 /* Returns Authorization header in given request */
1023 static const struct http_header *find_authorization(
1024 const struct http_request *request) {
1025 const struct http_header *header;
1026 if (request == NULL) return NULL;
1027 for (header = request->headers; header != NULL; header = header->next) {
1028 if (header->name != NULL &&
1029 !strcasecmp(header->name, "Authorization"))
1030 break;
1032 return header;
1036 /* Return true if request carries Authorization header */
1037 int http_client_authenticates(const struct http_request *request) {
1038 if (find_authorization(request))
1039 return 1;
1040 else
1041 return 0;
1045 /* Return HTTP_ERROR_SUCCESS if request carries valid Basic credentials.
1046 * NULL @username or @password equales to empty string. */
1047 http_error http_authenticate_basic(const struct http_request *request,
1048 const char *username, const char *password) {
1049 const struct http_header *header;
1050 const char *basic_cookie_client;
1051 char *basic_cookie_plain = NULL, *basic_cookie_encoded = NULL;
1052 _Bool is_valid;
1054 header = find_authorization(request);
1055 if (header == NULL) return HTTP_ERROR_CLIENT;
1057 if (strncmp(header->value, "Basic ", 6)) return HTTP_ERROR_CLIENT;
1058 basic_cookie_client = header->value + 6;
1060 if (-1 == test_asprintf(&basic_cookie_plain, "%s:%s",
1061 (username == NULL) ? "" : username,
1062 (password == NULL) ? "" : password)) {
1063 return HTTP_ERROR_SERVER;
1066 basic_cookie_encoded = base64encode(basic_cookie_plain,
1067 strlen(basic_cookie_plain), 1);
1068 if (basic_cookie_encoded == NULL) {
1069 free(basic_cookie_plain);
1070 return HTTP_ERROR_SERVER;
1073 fprintf(stderr, "Authenticating basic: got=<%s>, expected=<%s> (%s)\n",
1074 basic_cookie_client, basic_cookie_encoded, basic_cookie_plain);
1075 free(basic_cookie_plain);
1077 is_valid = !strcmp(basic_cookie_encoded, basic_cookie_client);
1078 free(basic_cookie_encoded);
1080 return (is_valid) ? HTTP_ERROR_SUCCESS : HTTP_ERROR_CLIENT;
1084 /* Return HTTP_ERROR_SUCCESS if request carries valid OTP credentials.
1085 * NULL @username or @password or @otp equal to empty string. */
1086 http_error http_authenticate_otp(const struct http_request *request,
1087 const char *username, const char *password, const char *otp) {
1088 char *basic_password = NULL;
1089 http_error retval;
1091 /* Concatenate password and OTP code */
1092 if (-1 == test_asprintf(&basic_password, "%s%s",
1093 (password == NULL) ? "": password,
1094 (otp == NULL) ? "" : otp)) {
1095 return HTTP_ERROR_SERVER;
1098 /* Use Basic authentication */
1099 /* XXX: Specification does not define authorization method string */
1100 retval = http_authenticate_basic(request, username, basic_password);
1102 free(basic_password);
1103 return retval;
1107 /* Return cookie value by name or NULL if does not present. */
1108 const char *http_find_cookie(const struct http_request *request,
1109 const char *name) {
1110 const struct http_header *header;
1111 size_t length;
1112 const char *value = NULL;
1114 if (request == NULL || name == NULL) return NULL;
1115 length = strlen(name);
1117 for (header = request->headers; header != NULL; header = header->next) {
1118 if (header->name != NULL && !strcasecmp(header->name, "Cookie") &&
1119 header->value != NULL) {
1120 if (!strncmp(header->value, name, length) &&
1121 header->value[length] == '=') {
1122 /* Return last cookie with the name */
1123 value = header->value + length + 1;
1127 return value;
1131 /* Return Host header value or NULL if does not present. Returned string is
1132 * statically allocated. */
1133 const char *http_find_host(const struct http_request *request) {
1134 const struct http_header *header;
1135 const char *value = NULL;
1137 if (request == NULL) return NULL;
1139 for (header = request->headers; header != NULL; header = header->next) {
1140 if (header->name != NULL && !strcmp(header->name, "Host")) {
1141 value = header->value;
1144 return value;
1148 /* Free a HTTP header and set it to NULL */
1149 void http_header_free(struct http_header **header) {
1150 if (header == NULL || *header == NULL) return;
1151 free((*header)->name);
1152 free((*header)->value);
1153 free(*header);
1154 *header = NULL;
1158 /* Free linked list of HTTP headers and set it to NULL */
1159 void http_headers_free(struct http_header **headers) {
1160 struct http_header *header, *next;
1162 if (headers == NULL || *headers == NULL) return;
1164 for (header = *headers; header != NULL;) {
1165 next = header->next;
1166 http_header_free(&header);
1167 header = next;
1170 *headers = NULL;
1173 /* Free HTTP request and set it to NULL */
1174 void http_request_free(struct http_request **request) {
1175 if (request == NULL || *request == NULL) return;
1176 free((*request)->uri);
1177 http_headers_free(&((*request)->headers));
1178 free((*request)->body);
1179 free(*request);
1180 *request = NULL;
1183 /* Free HTTP response and set it to NULL */
1184 void http_response_free(struct http_response **response) {
1185 if (response == NULL || *response == NULL) return;
1186 free((*response)->reason);
1187 http_headers_free(&((*response)->headers));
1188 free((*response)->body);
1189 free(*response);
1190 *response = NULL;