test: server: Pass http_connection to HTTP funcation
[libisds.git] / test / simline / http.c
blob3f255a17d153a509d17917465d90149346932038
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-allocated 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 *line = NULL;
251 if (connection == NULL || connection->recv_callback == NULL)
252 return HTTP_ERROR_SERVER;
253 if (buffer == NULL || buffer_size == NULL || buffer_used == NULL)
254 return HTTP_ERROR_SERVER;
255 if (*buffer == NULL && *buffer_size > 0) return HTTP_ERROR_SERVER;
256 if (*buffer_size < *buffer_used) return HTTP_ERROR_SERVER;
258 #define BURST 1024
259 while (1) {
260 /* Check for EOL */
261 for (p = *buffer; p < *buffer + *buffer_used; p++)
263 if (*p != '\r')
264 continue;
265 if (!(p + 1 < *buffer + *buffer_used && p[1] == '\n'))
266 continue;
268 /* EOL found */
269 /* Crop by zero at EOL */
270 *p = '\0';
271 p += 2;
272 /* Copy read ahead data to new buffer and point line to original
273 * buffer. */
274 tmp = malloc(BURST);
275 if (tmp == NULL) return HTTP_ERROR_SERVER;
276 memcpy(tmp, p, *buffer + *buffer_used - p);
277 *line = *buffer;
278 *buffer_size = BURST;
279 *buffer_used = *buffer + *buffer_used - p;
280 *buffer = tmp;
281 /* And exit */
282 return HTTP_ERROR_SUCCESS;
285 if (*buffer_size == *buffer_used) {
286 /* Grow buffer */
287 tmp = realloc(*buffer, *buffer_size + BURST);
288 if (tmp == NULL) return HTTP_ERROR_SERVER;
289 *buffer = tmp;
290 *buffer_size += BURST;
293 /* Read data */
294 got = connection->recv_callback(connection, *buffer + *buffer_used,
295 *buffer_size - *buffer_used);
296 if (got == -1) return HTTP_ERROR_CLIENT;
298 /* Check for EOF */
299 if (got == 0) return HTTP_ERROR_CLIENT;
301 /* Move end of buffer */
302 *buffer_used += got;
304 #undef BURST
306 return HTTP_ERROR_SERVER;
310 /* Write a bulk data into HTTP socket.
311 * @connection is HTTP connection to write to.
312 * @data are bitstream to send to client.
313 * @length is size of @data in bytes.
314 * @return 0 in success. */
315 static int http_write_bulk(const struct http_connection *connection,
316 const void *data, size_t length) {
317 ssize_t written;
318 const void *end;
320 if (connection == NULL || connection->send_callback == NULL)
321 return HTTP_ERROR_SERVER;
322 if (data == NULL && length > 0) return HTTP_ERROR_SERVER;
324 for (end = data + length; data != end; data += written, length -= written) {
325 written = connection->send_callback(connection, data, length);
326 if (written == -1) return HTTP_ERROR_CLIENT;
329 return HTTP_ERROR_SUCCESS;
333 /* Write a line into HTTP socket.
334 * @connection is HTTP connection to write to.
335 * @line is NULL terminated string to send to client. HTTP EOL will be added.
336 * @return 0 in success. */
337 static int http_write_line(const struct http_connection *connection,
338 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(connection, line, strlen(line))))
346 return error;
348 /* Send EOL */
349 if ((error = http_write_bulk(connection, "\r\n", 2)))
350 return error;
352 return HTTP_ERROR_SUCCESS;
356 /* Read data of given length from HTTP socket.
357 * @connection is HTTP connection 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(const struct http_connection *connection,
367 void **data, size_t data_length,
368 char **buffer, size_t *buffer_size, size_t *buffer_used) {
369 ssize_t got;
370 char *tmp;
372 if (data == NULL) return HTTP_ERROR_SERVER;
373 *data = NULL;
375 if (connection == NULL || connection->recv_callback == NULL)
376 return HTTP_ERROR_SERVER;
377 if (buffer == NULL || buffer_size == NULL || buffer_used == NULL)
378 return HTTP_ERROR_SERVER;
379 if (*buffer == NULL && *buffer_size > 0) return HTTP_ERROR_SERVER;
380 if (*buffer_size < *buffer_used) return HTTP_ERROR_SERVER;
382 if (data_length <= 0) return HTTP_ERROR_SUCCESS;
384 #define BURST 1024
385 while (1) {
386 /* Check whether enought data have been read */
387 if (*buffer_used >= data_length) {
388 /* Copy read ahead data to new buffer and point data to original
389 * buffer. */
390 tmp = malloc(BURST);
391 if (tmp == NULL) return HTTP_ERROR_SERVER;
392 memcpy(tmp, *buffer + data_length, *buffer_used - data_length);
393 *data = *buffer;
394 *buffer_size = BURST;
395 *buffer_used = *buffer_used - data_length;
396 *buffer = tmp;
397 /* And exit */
398 return HTTP_ERROR_SUCCESS;
401 if (*buffer_size == *buffer_used) {
402 /* Grow buffer */
403 tmp = realloc(*buffer, *buffer_size + BURST);
404 if (tmp == NULL) return HTTP_ERROR_SERVER;
405 *buffer = tmp;
406 *buffer_size += BURST;
409 /* Read data */
410 got = connection->recv_callback(connection, *buffer + *buffer_used,
411 *buffer_size - *buffer_used);
412 if (got == -1) return HTTP_ERROR_CLIENT;
414 /* Check for EOF */
415 if (got == 0) return HTTP_ERROR_CLIENT;
417 /* Move end of buffer */
418 *buffer_used += got;
420 #undef BURST
422 return HTTP_ERROR_SERVER;
426 /* Parse HTTP request header.
427 * @request is pre-allocated HTTP request.
428 * @return 0 if success. */
429 static int http_parse_request_header(char *line,
430 struct http_request *request) {
431 char *p;
433 fprintf(stderr, "Request: <%s>\n", line);
435 /* Get method */
436 p = strchr(line, ' ');
437 if (p == NULL) return HTTP_ERROR_SERVER;
438 *p = '\0';
439 if (!strcmp(line, "GET"))
440 request->method = HTTP_METHOD_GET;
441 else if (!strcmp(line, "POST"))
442 request->method = HTTP_METHOD_POST;
443 else
444 request->method = HTTP_METHOD_UNKNOWN;
445 line = p + 1;
447 /* Get URI */
448 p = strchr(line, ' ');
449 if (p != NULL) *p = '\0';
450 request->uri = uri_decode(line);
451 if (request->uri == NULL) return HTTP_ERROR_SERVER;
453 /* Do not care about HTTP version */
455 fprintf(stderr, "Request-URI: <%s>\n", request->uri);
456 return HTTP_ERROR_SUCCESS;
460 /* Send HTTP response status line to client.
461 * @return 0 if success. */
462 static int http_write_response_status(const struct http_connection *connection,
463 const struct http_response *response) {
464 char *buffer = NULL;
465 int error;
467 if (response == NULL) return HTTP_ERROR_SERVER;
469 if (-1 == test_asprintf(&buffer, "HTTP/1.0 %u %s", response->status,
470 (response->reason == NULL) ? "" : response->reason))
471 return HTTP_ERROR_SERVER;
472 error = http_write_line(connection, buffer);
473 free(buffer);
475 return error;
479 /* Parse generic HTTP header.
480 * @request is pre-allocated HTTP request.
481 * @return 0 if success, negative value if internal error, positive value if
482 * header is not valid. */
483 static int http_parse_header(char *line, struct http_request *request) {
484 struct http_header *header;
486 if (line == NULL || request == NULL) return HTTP_ERROR_SERVER;
488 fprintf(stderr, "Header: <%s>\n", line);
490 /* Find last used header */
491 for (header = request->headers; header != NULL && header->next != NULL;
492 header = header->next);
494 if (*line == ' ' || *line == '\t') {
495 /* Line is continuation of last header */
496 if (header == NULL)
497 return HTTP_ERROR_CLIENT; /* No previous header to continue */
498 line++;
499 size_t old_length = strlen(header->value);
500 char *tmp = realloc(header->value,
501 sizeof(header->value[0]) * (old_length + strlen(line) + 1));
502 if (tmp == NULL) return HTTP_ERROR_SERVER;
503 header->value = tmp;
504 strcpy(&header->value[old_length], line);
505 } else {
506 /* New header */
507 struct http_header *new_header = calloc(sizeof(*new_header), 1);
508 if (new_header == NULL) return HTTP_ERROR_SERVER;
510 char *p = strstr(line, ": ");
511 if (p == NULL) return HTTP_ERROR_CLIENT;
513 size_t length = p - line;
514 new_header->name = malloc(sizeof(line[0]) * (length + 1));
515 if (new_header->name == NULL) {
516 http_header_free(&new_header);
517 return HTTP_ERROR_SERVER;
519 strncpy(new_header->name, line, length);
520 new_header->name[length] = '\0';
522 p += 2;
523 length = strlen(p);
524 new_header->value = malloc(sizeof(p[0]) * (length + 1));
525 if (new_header->value == NULL) {
526 http_header_free(&new_header);
527 return HTTP_ERROR_SERVER;
529 strcpy(new_header->value, p);
531 if (request->headers == NULL)
532 request->headers = new_header;
533 else
534 header->next = new_header;
538 /* FIXME: Decode. After parsing all headers as we could decode begining
539 * and then got encoded continuation. */
540 return HTTP_ERROR_SUCCESS;
544 /* Send HTTP header to client.
545 * @return 0 if success. */
546 static int http_write_header(const struct http_connection *connection,
547 const struct http_header *header) {
548 char *buffer = NULL;
549 int error;
551 if (header == NULL) return HTTP_ERROR_SERVER;
553 if (header->name == NULL) return HTTP_ERROR_SERVER;
555 /* TODO: Quote, split long lines */
556 if (-1 == test_asprintf(&buffer, "%s: %s", header->name,
557 (header->value == NULL) ? "" : header->value))
558 return HTTP_ERROR_SERVER;
559 error = http_write_line(connection, buffer);
560 free(buffer);
562 return error;
566 /* Find Content-Length value in HTTP request headers and set it into @request.
567 * @return 0 in success. */
568 static int find_content_length(struct http_request *request) {
569 struct http_header *header;
570 if (request == NULL) return HTTP_ERROR_SERVER;
572 for (header = request->headers; header != NULL; header = header->next) {
573 if (header->name == NULL) continue;
574 if (!strcasecmp(header->name, "Content-Length")) break;
577 if (header != NULL && header->value != NULL) {
578 char *p;
579 long long int value = strtol(header->value, &p, 10);
580 if (*p != '\0')
581 return HTTP_ERROR_CLIENT;
582 if ((value == LLONG_MIN || value == LLONG_MAX) && errno == ERANGE)
583 return HTTP_ERROR_SERVER;
584 if (value < 0)
585 return HTTP_ERROR_CLIENT;
586 if (value > SIZE_MAX)
587 return HTTP_ERROR_SERVER;
588 request->body_length = value;
589 } else {
590 request->body_length = 0;
592 return HTTP_ERROR_SUCCESS;
596 /* Print binary stream to STDERR with some escapes */
597 static void dump_body(const void *data, size_t length) {
598 fprintf(stderr, "===BEGIN BODY===\n");
599 if (length > 0 && NULL != data) {
600 for (size_t i = 0; i < length; i++) {
601 if (isprint(((const unsigned char *)data)[i]))
602 fprintf(stderr, "%c", ((const unsigned char *)data)[i]);
603 else
604 fprintf(stderr, "\\x%02x", ((const unsigned char*)data)[i]);
606 fprintf(stderr, "\n");
608 fprintf(stderr, "===END BODY===\n");
612 /* Read a HTTP request from connection.
613 * @http_request is heap-allocated received HTTP request,
614 * or NULL in case of error.
615 * @return http_error code. */
616 http_error http_read_request(const struct http_connection *connection,
617 struct http_request **request) {
618 char *line = NULL;
619 char *buffer = NULL;
620 size_t buffer_size = 0, buffer_used = 0;
621 int error;
623 if (request == NULL) return HTTP_ERROR_SERVER;
625 *request = calloc(1, sizeof(**request));
626 if (*request == NULL) return HTTP_ERROR_SERVER;
628 /* Get request header */
629 if ((error = http_read_line(connection, &line, &buffer, &buffer_size,
630 &buffer_used)))
631 goto leave;
632 if ((error = http_parse_request_header(line, *request)))
633 goto leave;
635 /* Get other headers */
636 while (1) {
637 if ((error = http_read_line(connection, &line, &buffer, &buffer_size,
638 &buffer_used))) {
639 fprintf(stderr, "Error while reading HTTP request line\n");
640 goto leave;
643 /* Check for headers delimiter */
644 if (line == NULL || *line == '\0') {
645 break;
648 if ((error = http_parse_header(line, *request))) {
649 fprintf(stderr, "Error while parsing HTTP request line: <%s>\n",
650 line);
651 goto leave;
655 /* Get body */
656 if ((error = find_content_length(*request))) {
657 fprintf(stderr, "Could not determine length of body\n");
658 goto leave;
660 if ((error = http_read_bulk(connection,
661 &(*request)->body, (*request)->body_length,
662 &buffer, &buffer_size, &buffer_used))) {
663 fprintf(stderr, "Could not read request body\n");
664 goto leave;
666 fprintf(stderr, "Body of size %zu B has been received:\n",
667 (*request)->body_length);
668 dump_body((*request)->body, (*request)->body_length);
670 leave:
671 free(line);
672 free(buffer);
673 if (error) http_request_free(request);
674 return error;
678 /* Write a HTTP response to connection. Auto-add Content-Length header.
679 * @return 0 in case of success. */
680 int http_write_response(const struct http_connection *connection,
681 const struct http_response *response) {
682 char *buffer = NULL;
683 int error = -1;
685 if (response == NULL) return HTTP_ERROR_SERVER;
687 /* Status line */
688 error = http_write_response_status(connection, response);
689 if (error) return error;
691 /* Headers */
692 for (struct http_header *header = response->headers; header != NULL;
693 header = header->next) {
694 error = http_write_header(connection, header);
695 if (error) return error;
697 if (-1 == test_asprintf(&buffer, "Content-Length: %u",
698 response->body_length))
699 return HTTP_ERROR_SERVER;
700 error = http_write_line(connection, buffer);
701 if (error) return error;
703 /* Headers trailer */
704 error = http_write_line(connection, "");
705 if (error) return error;
707 /* Body */
708 if (response->body_length > 0) {
709 error = http_write_bulk(connection, response->body,
710 response->body_length);
711 if (error) return error;
713 fprintf(stderr, "Body of size %zu B has been sent:\n",
714 response->body_length);
715 dump_body(response->body, response->body_length);
717 free(buffer);
718 return HTTP_ERROR_SUCCESS;
722 /* Build Set-Cookie header. In case of error, return NULL. Caller must free
723 * the header. */
724 static struct http_header *http_build_setcookie_header (
725 const char *cokie_name, const char *cookie_value,
726 const char *cookie_domain, const char *cookie_path) {
727 struct http_header *header = NULL;
728 char *domain_parameter = NULL;
729 char *path_parameter = NULL;
731 if (cokie_name == NULL) goto error;
733 header = calloc(1, sizeof(*header));
734 if (header == NULL) goto error;
736 header->name = strdup("Set-Cookie");
737 if (header->name == NULL) goto error;
739 if (cookie_domain != NULL)
740 if (-1 == test_asprintf(&domain_parameter, "; Domain=%s",
741 cookie_domain))
742 goto error;
744 if (cookie_path != NULL)
745 if (-1 == test_asprintf(&path_parameter, "; Path=%s",
746 cookie_path))
747 goto error;
749 if (-1 == test_asprintf(&header->value, "%s=%s%s%s",
750 cokie_name,
751 (cookie_value == NULL) ? "" : cookie_value,
752 (domain_parameter == NULL) ? "": domain_parameter,
753 (path_parameter == NULL) ? "": path_parameter))
754 goto error;
755 goto ok;
757 error:
758 http_header_free(&header);
760 free(domain_parameter);
761 free(path_parameter);
762 return header;
766 /* Send a 200 Ok response with a cookie */
767 int http_send_response_200_cookie(const struct http_connection *connection,
768 const char *cokie_name, const char *cookie_value,
769 const char *cookie_domain, const char *cookie_path,
770 const void *body, size_t body_length, const char *type) {
771 int retval;
772 struct http_header *header_cookie = NULL;
773 struct http_header header_contenttype = {
774 .name = "Content-Type",
775 .value = (char *)type,
776 .next = NULL
778 struct http_response response = {
779 .status = 200,
780 .reason = "OK",
781 .headers = NULL,
782 .body_length = body_length,
783 .body = (void *)body
786 if (cokie_name != NULL) {
787 if (NULL == (header_cookie = http_build_setcookie_header(
788 cokie_name, cookie_value, cookie_domain, cookie_path)))
789 return http_send_response_500(connection,
790 "Could not build Set-Cookie header");
793 /* Link defined headers */
794 if (type != NULL) {
795 response.headers = &header_contenttype;
797 if (header_cookie != NULL) {
798 header_cookie->next = response.headers;
799 response.headers = header_cookie;
802 retval = http_write_response(connection, &response);
803 http_header_free(&header_cookie);
804 return retval;
808 /* Send a 200 Ok response */
809 int http_send_response_200(const struct http_connection *connection,
810 const void *body, size_t body_length, const char *type) {
811 return http_send_response_200_cookie(connection,
812 NULL, NULL, NULL, NULL,
813 body, body_length, type);
817 /* Send a 302 Found response setting a cookie */
818 int http_send_response_302_cookie(const struct http_connection *connection,
819 const char *cokie_name, const char *cookie_value,
820 const char *cookie_domain, const char *cookie_path,
821 const char *location) {
822 int retval;
823 struct http_header *header_cookie = NULL;
824 struct http_header header_location = {
825 .name = "Location",
826 .value = (char *) location,
827 .next = NULL
829 struct http_response response = {
830 .status = 302,
831 .reason = "Found",
832 .headers = NULL,
833 .body_length = 0,
834 .body = NULL
837 if (cokie_name != NULL) {
838 if (NULL == (header_cookie = http_build_setcookie_header(
839 cokie_name, cookie_value, cookie_domain, cookie_path)))
840 return http_send_response_500(connection,
841 "Could not build Set-Cookie header");
844 /* Link defined headers */
845 if (location != NULL) {
846 response.headers = &header_location;
848 if (header_cookie != NULL) {
849 header_cookie->next = response.headers;
850 response.headers = header_cookie;
853 retval = http_write_response(connection, &response);
854 http_header_free(&header_cookie);
855 return retval;
859 /* Send a 302 Found response with totp authentication scheme header */
860 int http_send_response_302_totp(const struct http_connection *connection,
861 const char *code, const char *text, const char *location) {
862 struct http_header header_code = {
863 .name = "X-Response-message-code",
864 .value = (char *) code,
865 .next = NULL
867 struct http_header header_text = {
868 .name = "X-Response-message-text",
869 .value = (char *) text,
870 .next = NULL
872 struct http_header header_location = {
873 .name = "Location",
874 .value = (char *) location,
875 .next = NULL
877 struct http_response response = {
878 .status = 302,
879 .reason = "Found",
880 .headers = NULL,
881 .body_length = 0,
882 .body = NULL
885 /* Link defined headers */
886 if (location != NULL) {
887 response.headers = &header_location;
889 if (text != NULL) {
890 header_text.next = response.headers;
891 response.headers = &header_text;
893 if (code != NULL) {
894 header_code.next = response.headers;
895 response.headers = &header_code;
898 return http_write_response(connection, &response);
902 /* Send a 400 Bad Request response.
903 * Use non-NULL @reason to override status message. */
904 int http_send_response_400(const struct http_connection *connection,
905 const char *reason) {
906 struct http_response response = {
907 .status = 400,
908 .reason = (reason == NULL) ? "Bad Request" : (char *) reason,
909 .headers = NULL,
910 .body_length = 0,
911 .body = NULL
914 return http_write_response(connection, &response);
918 /* Send a 401 Unauthorized response with Basic authentication scheme header */
919 int http_send_response_401_basic(const struct http_connection *connection) {
920 struct http_header header = {
921 .name = "WWW-Authenticate",
922 .value = "Basic realm=\"SimulatedISDSServer\"",
923 .next = NULL
925 struct http_response response = {
926 .status = 401,
927 .reason = "Unauthorized",
928 .headers = &header,
929 .body_length = 0,
930 .body = NULL
933 return http_write_response(connection, &response);
937 /* Send a 401 Unauthorized response with OTP authentication scheme header for
938 * given @method. */
939 int http_send_response_401_otp(const struct http_connection *connection,
940 const char *method, const char *code, const char *text) {
941 int retval;
942 struct http_header header = {
943 .name = "WWW-Authenticate",
944 .value = NULL,
945 .next = NULL
947 struct http_header header_code = {
948 .name = "X-Response-message-code",
949 .value = (char *) code,
950 .next = NULL
952 struct http_header header_text = {
953 .name = "X-Response-message-text",
954 .value = (char *) text,
955 .next = NULL
957 struct http_response response = {
958 .status = 401,
959 .reason = "Unauthorized",
960 .headers = &header,
961 .body_length = 0,
962 .body = NULL
965 if (-1 == test_asprintf(&header.value, "%s realm=\"SimulatedISDSServer\"",
966 method)) {
967 return http_send_response_500(connection,
968 "Could not build WWW-Authenticate header value");
971 /* Link defined headers */
972 if (code != NULL) header.next = &header_code;
973 if (text != NULL) {
974 if (code != NULL)
975 header_code.next = &header_text;
976 else
977 header.next = &header_text;
980 retval = http_write_response(connection, &response);
981 free(header.value);
982 return retval;
986 /* Send a 403 Forbidden response */
987 int http_send_response_403(const struct http_connection *connection) {
988 struct http_response response = {
989 .status = 403,
990 .reason = "Forbidden",
991 .headers = NULL,
992 .body_length = 0,
993 .body = NULL
996 return http_write_response(connection, &response);
1000 /* Send a 500 Internal Server Error response.
1001 * Use non-NULL @reason to override status message. */
1002 int http_send_response_500(const struct http_connection *connection,
1003 const char *reason) {
1004 struct http_response response = {
1005 .status = 500,
1006 .reason = (NULL == reason) ? "Internal Server Error" : (char *) reason,
1007 .headers = NULL,
1008 .body_length = 0,
1009 .body = NULL
1012 return http_write_response(connection, &response);
1016 /* Send a 503 Service Temporarily Unavailable response */
1017 int http_send_response_503(const struct http_connection *connection,
1018 const void *body, size_t body_length, const char *type) {
1019 struct http_header header = {
1020 .name = "Content-Type",
1021 .value = (char *)type
1023 struct http_response response = {
1024 .status = 503,
1025 .reason = "Service Temporarily Unavailable",
1026 .headers = (type == NULL) ? NULL : &header,
1027 .body_length = body_length,
1028 .body = (void *)body
1031 return http_write_response(connection, &response);
1035 /* Returns Authorization header in given request */
1036 static const struct http_header *find_authorization(
1037 const struct http_request *request) {
1038 const struct http_header *header;
1039 if (request == NULL) return NULL;
1040 for (header = request->headers; header != NULL; header = header->next) {
1041 if (header->name != NULL &&
1042 !strcasecmp(header->name, "Authorization"))
1043 break;
1045 return header;
1049 /* Return true if request carries Authorization header */
1050 int http_client_authenticates(const struct http_request *request) {
1051 if (find_authorization(request))
1052 return 1;
1053 else
1054 return 0;
1058 /* Return HTTP_ERROR_SUCCESS if request carries valid Basic credentials.
1059 * NULL @username or @password equales to empty string. */
1060 http_error http_authenticate_basic(const struct http_request *request,
1061 const char *username, const char *password) {
1062 const struct http_header *header;
1063 const char *basic_cookie_client;
1064 char *basic_cookie_plain = NULL, *basic_cookie_encoded = NULL;
1065 _Bool is_valid;
1067 header = find_authorization(request);
1068 if (header == NULL) return HTTP_ERROR_CLIENT;
1070 if (strncmp(header->value, "Basic ", 6)) return HTTP_ERROR_CLIENT;
1071 basic_cookie_client = header->value + 6;
1073 if (-1 == test_asprintf(&basic_cookie_plain, "%s:%s",
1074 (username == NULL) ? "" : username,
1075 (password == NULL) ? "" : password)) {
1076 return HTTP_ERROR_SERVER;
1079 basic_cookie_encoded = base64encode(basic_cookie_plain,
1080 strlen(basic_cookie_plain), 1);
1081 if (basic_cookie_encoded == NULL) {
1082 free(basic_cookie_plain);
1083 return HTTP_ERROR_SERVER;
1086 fprintf(stderr, "Authenticating basic: got=<%s>, expected=<%s> (%s)\n",
1087 basic_cookie_client, basic_cookie_encoded, basic_cookie_plain);
1088 free(basic_cookie_plain);
1090 is_valid = !strcmp(basic_cookie_encoded, basic_cookie_client);
1091 free(basic_cookie_encoded);
1093 return (is_valid) ? HTTP_ERROR_SUCCESS : HTTP_ERROR_CLIENT;
1097 /* Return HTTP_ERROR_SUCCESS if request carries valid OTP credentials.
1098 * NULL @username or @password or @otp equal to empty string. */
1099 http_error http_authenticate_otp(const struct http_request *request,
1100 const char *username, const char *password, const char *otp) {
1101 char *basic_password = NULL;
1102 http_error retval;
1104 /* Concatenate password and OTP code */
1105 if (-1 == test_asprintf(&basic_password, "%s%s",
1106 (password == NULL) ? "": password,
1107 (otp == NULL) ? "" : otp)) {
1108 return HTTP_ERROR_SERVER;
1111 /* Use Basic authentication */
1112 /* XXX: Specification does not define authorization method string */
1113 retval = http_authenticate_basic(request, username, basic_password);
1115 free(basic_password);
1116 return retval;
1120 /* Return cookie value by name or NULL if does not present. */
1121 const char *http_find_cookie(const struct http_request *request,
1122 const char *name) {
1123 const struct http_header *header;
1124 size_t length;
1125 const char *value = NULL;
1127 if (request == NULL || name == NULL) return NULL;
1128 length = strlen(name);
1130 for (header = request->headers; header != NULL; header = header->next) {
1131 if (header->name != NULL && !strcasecmp(header->name, "Cookie") &&
1132 header->value != NULL) {
1133 if (!strncmp(header->value, name, length) &&
1134 header->value[length] == '=') {
1135 /* Return last cookie with the name */
1136 value = header->value + length + 1;
1140 return value;
1144 /* Return Host header value or NULL if does not present. Returned string is
1145 * statically allocated. */
1146 const char *http_find_host(const struct http_request *request) {
1147 const struct http_header *header;
1148 const char *value = NULL;
1150 if (request == NULL) return NULL;
1152 for (header = request->headers; header != NULL; header = header->next) {
1153 if (header->name != NULL && !strcmp(header->name, "Host")) {
1154 value = header->value;
1157 return value;
1161 /* Free a HTTP header and set it to NULL */
1162 void http_header_free(struct http_header **header) {
1163 if (header == NULL || *header == NULL) return;
1164 free((*header)->name);
1165 free((*header)->value);
1166 free(*header);
1167 *header = NULL;
1171 /* Free linked list of HTTP headers and set it to NULL */
1172 void http_headers_free(struct http_header **headers) {
1173 struct http_header *header, *next;
1175 if (headers == NULL || *headers == NULL) return;
1177 for (header = *headers; header != NULL;) {
1178 next = header->next;
1179 http_header_free(&header);
1180 header = next;
1183 *headers = NULL;
1186 /* Free HTTP request and set it to NULL */
1187 void http_request_free(struct http_request **request) {
1188 if (request == NULL || *request == NULL) return;
1189 free((*request)->uri);
1190 http_headers_free(&((*request)->headers));
1191 free((*request)->body);
1192 free(*request);
1193 *request = NULL;
1196 /* Free HTTP response and set it to NULL */
1197 void http_response_free(struct http_response **response) {
1198 if (response == NULL || *response == NULL) return;
1199 free((*response)->reason);
1200 http_headers_free(&((*response)->headers));
1201 free((*response)->body);
1202 free(*response);
1203 *response = NULL;