2 #define _XOPEN_SOURCE 500 /* For strdup() */
6 #include "../test-tools.h"
11 #include <stdio.h> /* fprintf() */
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.
28 step_A
, step_B
, step_C
32 base64_encodestep step
;
34 int stepcount
; /* number of encoded octet triplets on a line,
35 or -1 to for end-less line */
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
;
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
;
66 result
= state_in
->result
;
68 switch (state_in
->step
) {
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;
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;
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) {
106 state_in
->stepcount
= 0;
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
) {
123 *codechar
++ = base64_encode_value(state_in
->result
);
128 *codechar
++ = base64_encode_value(state_in
->result
);
134 if (state_in
->stepcount
>= 0)
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
,
152 base64_encodestate state
;
154 char *buffer
, *new_buffer
;
157 if (length
) return NULL
;
158 /* Empty input is valid input */
162 base64_init_encodestate(&state
, one_line
);
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
,
172 code_length
+= base64_encode_blockend(((int8_t*)buffer
) + code_length
,
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
;
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')
191 if (digit
>= 'a' && digit
<= 'f')
192 return digit
- 'a' + 10;
193 if (digit
>= 'A' && digit
<= 'F')
194 return digit
- 'A' + 10;
199 /* Decode URI-coded string.
200 * @return allocated decoded string or NULL in case of error. */
201 static char *uri_decode(const char *coded
) {
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
++) {
211 digit1
= hex2i(coded
[1]);
216 digit2
= hex2i(coded
[2]);
221 *plain
= (digit1
<< 4) + digit2
;
233 /* Read a line from HTTP socket.
234 * @connection is HTTP connection to read from.
235 * @line is auto-reallocated just read line. Will be NULL if EOF has been
236 * reached or error occured.
237 * @buffer is automatically reallocated buffer for the socket. It can preserve
238 * prematurately read socket data.
239 * @buffer_size is allocated size of @buffer
240 * @buffer_length is size of head of the buffer that holds read data.
241 * @return 0 in success. */
242 static int http_read_line(const struct http_connection
*connection
,
243 char **line
, char **buffer
, size_t *buffer_size
,
244 size_t *buffer_used
) {
248 if (line
== NULL
) return HTTP_ERROR_SERVER
;
252 if (connection
== NULL
|| connection
->recv_callback
== NULL
)
253 return HTTP_ERROR_SERVER
;
254 if (buffer
== NULL
|| buffer_size
== NULL
|| buffer_used
== NULL
)
255 return HTTP_ERROR_SERVER
;
256 if (*buffer
== NULL
&& *buffer_size
> 0) return HTTP_ERROR_SERVER
;
257 if (*buffer_size
< *buffer_used
) return HTTP_ERROR_SERVER
;
262 for (p
= *buffer
; p
< *buffer
+ *buffer_used
; p
++)
266 if (!(p
+ 1 < *buffer
+ *buffer_used
&& p
[1] == '\n'))
270 /* Crop by zero at EOL */
273 /* Copy read ahead data to new buffer and point line to original
276 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
277 memcpy(tmp
, p
, *buffer
+ *buffer_used
- p
);
279 *buffer_size
= BURST
;
280 *buffer_used
= *buffer
+ *buffer_used
- p
;
283 return HTTP_ERROR_SUCCESS
;
286 if (*buffer_size
== *buffer_used
) {
288 tmp
= realloc(*buffer
, *buffer_size
+ BURST
);
289 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
291 *buffer_size
+= BURST
;
295 got
= connection
->recv_callback(connection
, *buffer
+ *buffer_used
,
296 *buffer_size
- *buffer_used
);
297 if (got
== -1) return HTTP_ERROR_CLIENT
;
300 if (got
== 0) return HTTP_ERROR_CLIENT
;
302 /* Move end of buffer */
307 return HTTP_ERROR_SERVER
;
311 /* Write a bulk data into HTTP socket.
312 * @connection is HTTP connection to write to.
313 * @data are bitstream to send to client.
314 * @length is size of @data in bytes.
315 * @return 0 in success. */
316 static int http_write_bulk(const struct http_connection
*connection
,
317 const void *data
, size_t length
) {
321 if (connection
== NULL
|| connection
->send_callback
== NULL
)
322 return HTTP_ERROR_SERVER
;
323 if (data
== NULL
&& length
> 0) return HTTP_ERROR_SERVER
;
325 for (end
= data
+ length
; data
!= end
; data
+= written
, length
-= written
) {
326 written
= connection
->send_callback(connection
, data
, length
);
327 if (written
== -1) return HTTP_ERROR_CLIENT
;
330 return HTTP_ERROR_SUCCESS
;
334 /* Write a line into HTTP socket.
335 * @connection is HTTP connection to write to.
336 * @line is NULL terminated string to send to client. HTTP EOL will be added.
337 * @return 0 in success. */
338 static int http_write_line(const struct http_connection
*connection
,
341 if (line
== NULL
) return HTTP_ERROR_SERVER
;
343 fprintf(stderr
, "Response: <%s>\n", line
);
346 if ((error
= http_write_bulk(connection
, line
, strlen(line
))))
350 if ((error
= http_write_bulk(connection
, "\r\n", 2)))
353 return HTTP_ERROR_SUCCESS
;
357 /* Read data of given length from HTTP socket.
358 * @connection is HTTP connection to read from.
359 * @data is auto-allocated just read data bulk. Will be NULL if EOF has been
360 * reached or error occured.
361 * @data_length is size of bytes to read.
362 * @buffer is automatically reallocated buffer for the socket. It can preserve
363 * prematurately read socket data.
364 * @buffer_size is allocated size of @buffer
365 * @buffer_length is size of head of the buffer that holds read data.
366 * @return 0 in success. */
367 static int http_read_bulk(const struct http_connection
*connection
,
368 void **data
, size_t data_length
,
369 char **buffer
, size_t *buffer_size
, size_t *buffer_used
) {
373 if (data
== NULL
) return HTTP_ERROR_SERVER
;
376 if (connection
== NULL
|| connection
->recv_callback
== NULL
)
377 return HTTP_ERROR_SERVER
;
378 if (buffer
== NULL
|| buffer_size
== NULL
|| buffer_used
== NULL
)
379 return HTTP_ERROR_SERVER
;
380 if (*buffer
== NULL
&& *buffer_size
> 0) return HTTP_ERROR_SERVER
;
381 if (*buffer_size
< *buffer_used
) return HTTP_ERROR_SERVER
;
383 if (data_length
<= 0) return HTTP_ERROR_SUCCESS
;
387 /* Check whether enought data have been read */
388 if (*buffer_used
>= data_length
) {
389 /* Copy read ahead data to new buffer and point data to original
392 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
393 memcpy(tmp
, *buffer
+ data_length
, *buffer_used
- data_length
);
395 *buffer_size
= BURST
;
396 *buffer_used
= *buffer_used
- data_length
;
399 return HTTP_ERROR_SUCCESS
;
402 if (*buffer_size
== *buffer_used
) {
404 tmp
= realloc(*buffer
, *buffer_size
+ BURST
);
405 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
407 *buffer_size
+= BURST
;
411 got
= connection
->recv_callback(connection
, *buffer
+ *buffer_used
,
412 *buffer_size
- *buffer_used
);
413 if (got
== -1) return HTTP_ERROR_CLIENT
;
416 if (got
== 0) return HTTP_ERROR_CLIENT
;
418 /* Move end of buffer */
423 return HTTP_ERROR_SERVER
;
427 /* Parse HTTP request header.
428 * @request is pre-allocated HTTP request.
429 * @return 0 if success. */
430 static int http_parse_request_header(char *line
,
431 struct http_request
*request
) {
434 fprintf(stderr
, "Request: <%s>\n", line
);
437 p
= strchr(line
, ' ');
438 if (p
== NULL
) return HTTP_ERROR_SERVER
;
440 if (!strcmp(line
, "GET"))
441 request
->method
= HTTP_METHOD_GET
;
442 else if (!strcmp(line
, "POST"))
443 request
->method
= HTTP_METHOD_POST
;
445 request
->method
= HTTP_METHOD_UNKNOWN
;
449 p
= strchr(line
, ' ');
450 if (p
!= NULL
) *p
= '\0';
451 request
->uri
= uri_decode(line
);
452 if (request
->uri
== NULL
) return HTTP_ERROR_SERVER
;
454 /* Do not care about HTTP version */
456 fprintf(stderr
, "Request-URI: <%s>\n", request
->uri
);
457 return HTTP_ERROR_SUCCESS
;
461 /* Send HTTP response status line to client.
462 * @return 0 if success. */
463 static int http_write_response_status(const struct http_connection
*connection
,
464 const struct http_response
*response
) {
468 if (response
== NULL
) return HTTP_ERROR_SERVER
;
470 if (-1 == test_asprintf(&buffer
, "HTTP/1.0 %u %s", response
->status
,
471 (response
->reason
== NULL
) ? "" : response
->reason
))
472 return HTTP_ERROR_SERVER
;
473 error
= http_write_line(connection
, buffer
);
480 /* Parse generic HTTP header.
481 * @request is pre-allocated HTTP request.
482 * @return 0 if success, negative value if internal error, positive value if
483 * header is not valid. */
484 static int http_parse_header(char *line
, struct http_request
*request
) {
485 struct http_header
*header
;
487 if (line
== NULL
|| request
== NULL
) return HTTP_ERROR_SERVER
;
489 fprintf(stderr
, "Header: <%s>\n", line
);
491 /* Find last used header */
492 for (header
= request
->headers
; header
!= NULL
&& header
->next
!= NULL
;
493 header
= header
->next
);
495 if (*line
== ' ' || *line
== '\t') {
496 /* Line is continuation of last header */
498 return HTTP_ERROR_CLIENT
; /* No previous header to continue */
500 size_t old_length
= strlen(header
->value
);
501 char *tmp
= realloc(header
->value
,
502 sizeof(header
->value
[0]) * (old_length
+ strlen(line
) + 1));
503 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
505 strcpy(&header
->value
[old_length
], line
);
508 struct http_header
*new_header
= calloc(sizeof(*new_header
), 1);
509 if (new_header
== NULL
) return HTTP_ERROR_SERVER
;
511 char *p
= strstr(line
, ": ");
512 if (p
== NULL
) return HTTP_ERROR_CLIENT
;
514 size_t length
= p
- line
;
515 new_header
->name
= malloc(sizeof(line
[0]) * (length
+ 1));
516 if (new_header
->name
== NULL
) {
517 http_header_free(&new_header
);
518 return HTTP_ERROR_SERVER
;
520 strncpy(new_header
->name
, line
, length
);
521 new_header
->name
[length
] = '\0';
525 new_header
->value
= malloc(sizeof(p
[0]) * (length
+ 1));
526 if (new_header
->value
== NULL
) {
527 http_header_free(&new_header
);
528 return HTTP_ERROR_SERVER
;
530 strcpy(new_header
->value
, p
);
532 if (request
->headers
== NULL
)
533 request
->headers
= new_header
;
535 header
->next
= new_header
;
539 /* FIXME: Decode. After parsing all headers as we could decode begining
540 * and then got encoded continuation. */
541 return HTTP_ERROR_SUCCESS
;
545 /* Send HTTP header to client.
546 * @return 0 if success. */
547 static int http_write_header(const struct http_connection
*connection
,
548 const struct http_header
*header
) {
552 if (header
== NULL
) return HTTP_ERROR_SERVER
;
554 if (header
->name
== NULL
) return HTTP_ERROR_SERVER
;
556 /* TODO: Quote, split long lines */
557 if (-1 == test_asprintf(&buffer
, "%s: %s", header
->name
,
558 (header
->value
== NULL
) ? "" : header
->value
))
559 return HTTP_ERROR_SERVER
;
560 error
= http_write_line(connection
, buffer
);
567 /* Find Content-Length value in HTTP request headers and set it into @request.
568 * @return 0 in success. */
569 static int find_content_length(struct http_request
*request
) {
570 struct http_header
*header
;
571 if (request
== NULL
) return HTTP_ERROR_SERVER
;
573 for (header
= request
->headers
; header
!= NULL
; header
= header
->next
) {
574 if (header
->name
== NULL
) continue;
575 if (!strcasecmp(header
->name
, "Content-Length")) break;
578 if (header
!= NULL
&& header
->value
!= NULL
) {
580 long long int value
= strtol(header
->value
, &p
, 10);
582 return HTTP_ERROR_CLIENT
;
583 if ((value
== LLONG_MIN
|| value
== LLONG_MAX
) && errno
== ERANGE
)
584 return HTTP_ERROR_SERVER
;
586 return HTTP_ERROR_CLIENT
;
587 if (value
> SIZE_MAX
)
588 return HTTP_ERROR_SERVER
;
589 request
->body_length
= value
;
591 request
->body_length
= 0;
593 return HTTP_ERROR_SUCCESS
;
597 /* Print binary stream to STDERR with some escapes */
598 static void dump_body(const void *data
, size_t length
) {
599 fprintf(stderr
, "===BEGIN BODY===\n");
600 if (length
> 0 && NULL
!= data
) {
601 for (size_t i
= 0; i
< length
; i
++) {
602 if (isprint(((const unsigned char *)data
)[i
]))
603 fprintf(stderr
, "%c", ((const unsigned char *)data
)[i
]);
605 fprintf(stderr
, "\\x%02x", ((const unsigned char*)data
)[i
]);
607 fprintf(stderr
, "\n");
609 fprintf(stderr
, "===END BODY===\n");
613 /* Read a HTTP request from connection.
614 * @http_request is heap-allocated received HTTP request,
615 * or NULL in case of error.
616 * @return http_error code. */
617 http_error
http_read_request(const struct http_connection
*connection
,
618 struct http_request
**request
) {
621 size_t buffer_size
= 0, buffer_used
= 0;
624 if (request
== NULL
) return HTTP_ERROR_SERVER
;
626 *request
= calloc(1, sizeof(**request
));
627 if (*request
== NULL
) return HTTP_ERROR_SERVER
;
629 /* Get request header */
630 if ((error
= http_read_line(connection
, &line
, &buffer
, &buffer_size
,
633 if ((error
= http_parse_request_header(line
, *request
)))
636 /* Get other headers */
638 if ((error
= http_read_line(connection
, &line
, &buffer
, &buffer_size
,
640 fprintf(stderr
, "Error while reading HTTP request line\n");
644 /* Check for headers delimiter */
645 if (line
== NULL
|| *line
== '\0') {
649 if ((error
= http_parse_header(line
, *request
))) {
650 fprintf(stderr
, "Error while parsing HTTP request line: <%s>\n",
657 if ((error
= find_content_length(*request
))) {
658 fprintf(stderr
, "Could not determine length of body\n");
661 if ((error
= http_read_bulk(connection
,
662 &(*request
)->body
, (*request
)->body_length
,
663 &buffer
, &buffer_size
, &buffer_used
))) {
664 fprintf(stderr
, "Could not read request body\n");
667 fprintf(stderr
, "Body of size %zu B has been received:\n",
668 (*request
)->body_length
);
669 dump_body((*request
)->body
, (*request
)->body_length
);
674 if (error
) http_request_free(request
);
679 /* Write a HTTP response to connection. Auto-add Content-Length header.
680 * @return 0 in case of success. */
681 int http_write_response(const struct http_connection
*connection
,
682 const struct http_response
*response
) {
686 if (response
== NULL
) return HTTP_ERROR_SERVER
;
689 error
= http_write_response_status(connection
, response
);
690 if (error
) return error
;
693 for (struct http_header
*header
= response
->headers
; header
!= NULL
;
694 header
= header
->next
) {
695 error
= http_write_header(connection
, header
);
696 if (error
) return error
;
698 if (-1 == test_asprintf(&buffer
, "Content-Length: %u",
699 response
->body_length
))
700 return HTTP_ERROR_SERVER
;
701 error
= http_write_line(connection
, buffer
);
702 if (error
) return error
;
704 /* Headers trailer */
705 error
= http_write_line(connection
, "");
706 if (error
) return error
;
709 if (response
->body_length
> 0) {
710 error
= http_write_bulk(connection
, response
->body
,
711 response
->body_length
);
712 if (error
) return error
;
714 fprintf(stderr
, "Body of size %zu B has been sent:\n",
715 response
->body_length
);
716 dump_body(response
->body
, response
->body_length
);
719 return HTTP_ERROR_SUCCESS
;
723 /* Build Set-Cookie header. In case of error, return NULL. Caller must free
725 static struct http_header
*http_build_setcookie_header (
726 const char *cokie_name
, const char *cookie_value
,
727 const char *cookie_domain
, const char *cookie_path
) {
728 struct http_header
*header
= NULL
;
729 char *domain_parameter
= NULL
;
730 char *path_parameter
= NULL
;
732 if (cokie_name
== NULL
) goto error
;
734 header
= calloc(1, sizeof(*header
));
735 if (header
== NULL
) goto error
;
737 header
->name
= strdup("Set-Cookie");
738 if (header
->name
== NULL
) goto error
;
740 if (cookie_domain
!= NULL
)
741 if (-1 == test_asprintf(&domain_parameter
, "; Domain=%s",
745 if (cookie_path
!= NULL
)
746 if (-1 == test_asprintf(&path_parameter
, "; Path=%s",
750 if (-1 == test_asprintf(&header
->value
, "%s=%s%s%s",
752 (cookie_value
== NULL
) ? "" : cookie_value
,
753 (domain_parameter
== NULL
) ? "": domain_parameter
,
754 (path_parameter
== NULL
) ? "": path_parameter
))
759 http_header_free(&header
);
761 free(domain_parameter
);
762 free(path_parameter
);
767 /* Send a 200 Ok response with a cookie */
768 int http_send_response_200_cookie(const struct http_connection
*connection
,
769 const char *cokie_name
, const char *cookie_value
,
770 const char *cookie_domain
, const char *cookie_path
,
771 const void *body
, size_t body_length
, const char *type
) {
773 struct http_header
*header_cookie
= NULL
;
774 struct http_header header_contenttype
= {
775 .name
= "Content-Type",
776 .value
= (char *)type
,
779 struct http_response response
= {
783 .body_length
= body_length
,
787 if (cokie_name
!= NULL
) {
788 if (NULL
== (header_cookie
= http_build_setcookie_header(
789 cokie_name
, cookie_value
, cookie_domain
, cookie_path
)))
790 return http_send_response_500(connection
,
791 "Could not build Set-Cookie header");
794 /* Link defined headers */
796 response
.headers
= &header_contenttype
;
798 if (header_cookie
!= NULL
) {
799 header_cookie
->next
= response
.headers
;
800 response
.headers
= header_cookie
;
803 retval
= http_write_response(connection
, &response
);
804 http_header_free(&header_cookie
);
809 /* Send a 200 Ok response */
810 int http_send_response_200(const struct http_connection
*connection
,
811 const void *body
, size_t body_length
, const char *type
) {
812 return http_send_response_200_cookie(connection
,
813 NULL
, NULL
, NULL
, NULL
,
814 body
, body_length
, type
);
818 /* Send a 302 Found response setting a cookie */
819 int http_send_response_302_cookie(const struct http_connection
*connection
,
820 const char *cokie_name
, const char *cookie_value
,
821 const char *cookie_domain
, const char *cookie_path
,
822 const char *location
) {
824 struct http_header
*header_cookie
= NULL
;
825 struct http_header header_location
= {
827 .value
= (char *) location
,
830 struct http_response response
= {
838 if (cokie_name
!= NULL
) {
839 if (NULL
== (header_cookie
= http_build_setcookie_header(
840 cokie_name
, cookie_value
, cookie_domain
, cookie_path
)))
841 return http_send_response_500(connection
,
842 "Could not build Set-Cookie header");
845 /* Link defined headers */
846 if (location
!= NULL
) {
847 response
.headers
= &header_location
;
849 if (header_cookie
!= NULL
) {
850 header_cookie
->next
= response
.headers
;
851 response
.headers
= header_cookie
;
854 retval
= http_write_response(connection
, &response
);
855 http_header_free(&header_cookie
);
860 /* Send a 302 Found response with totp authentication scheme header */
861 int http_send_response_302_totp(const struct http_connection
*connection
,
862 const char *code
, const char *text
, const char *location
) {
863 struct http_header header_code
= {
864 .name
= "X-Response-message-code",
865 .value
= (char *) code
,
868 struct http_header header_text
= {
869 .name
= "X-Response-message-text",
870 .value
= (char *) text
,
873 struct http_header header_location
= {
875 .value
= (char *) location
,
878 struct http_response response
= {
886 /* Link defined headers */
887 if (location
!= NULL
) {
888 response
.headers
= &header_location
;
891 header_text
.next
= response
.headers
;
892 response
.headers
= &header_text
;
895 header_code
.next
= response
.headers
;
896 response
.headers
= &header_code
;
899 return http_write_response(connection
, &response
);
903 /* Send a 400 Bad Request response.
904 * Use non-NULL @reason to override status message. */
905 int http_send_response_400(const struct http_connection
*connection
,
906 const char *reason
) {
907 struct http_response response
= {
909 .reason
= (reason
== NULL
) ? "Bad Request" : (char *) reason
,
915 return http_write_response(connection
, &response
);
919 /* Send a 401 Unauthorized response with Basic authentication scheme header */
920 int http_send_response_401_basic(const struct http_connection
*connection
) {
921 struct http_header header
= {
922 .name
= "WWW-Authenticate",
923 .value
= "Basic realm=\"SimulatedISDSServer\"",
926 struct http_response response
= {
928 .reason
= "Unauthorized",
934 return http_write_response(connection
, &response
);
938 /* Send a 401 Unauthorized response with OTP authentication scheme header for
940 int http_send_response_401_otp(const struct http_connection
*connection
,
941 const char *method
, const char *code
, const char *text
) {
943 struct http_header header
= {
944 .name
= "WWW-Authenticate",
948 struct http_header header_code
= {
949 .name
= "X-Response-message-code",
950 .value
= (char *) code
,
953 struct http_header header_text
= {
954 .name
= "X-Response-message-text",
955 .value
= (char *) text
,
958 struct http_response response
= {
960 .reason
= "Unauthorized",
966 if (-1 == test_asprintf(&header
.value
, "%s realm=\"SimulatedISDSServer\"",
968 return http_send_response_500(connection
,
969 "Could not build WWW-Authenticate header value");
972 /* Link defined headers */
973 if (code
!= NULL
) header
.next
= &header_code
;
976 header_code
.next
= &header_text
;
978 header
.next
= &header_text
;
981 retval
= http_write_response(connection
, &response
);
987 /* Send a 403 Forbidden response */
988 int http_send_response_403(const struct http_connection
*connection
) {
989 struct http_response response
= {
991 .reason
= "Forbidden",
997 return http_write_response(connection
, &response
);
1001 /* Send a 500 Internal Server Error response.
1002 * Use non-NULL @reason to override status message. */
1003 int http_send_response_500(const struct http_connection
*connection
,
1004 const char *reason
) {
1005 struct http_response response
= {
1007 .reason
= (NULL
== reason
) ? "Internal Server Error" : (char *) reason
,
1013 return http_write_response(connection
, &response
);
1017 /* Send a 503 Service Temporarily Unavailable response */
1018 int http_send_response_503(const struct http_connection
*connection
,
1019 const void *body
, size_t body_length
, const char *type
) {
1020 struct http_header header
= {
1021 .name
= "Content-Type",
1022 .value
= (char *)type
1024 struct http_response response
= {
1026 .reason
= "Service Temporarily Unavailable",
1027 .headers
= (type
== NULL
) ? NULL
: &header
,
1028 .body_length
= body_length
,
1029 .body
= (void *)body
1032 return http_write_response(connection
, &response
);
1036 /* Returns Authorization header in given request */
1037 static const struct http_header
*find_authorization(
1038 const struct http_request
*request
) {
1039 const struct http_header
*header
;
1040 if (request
== NULL
) return NULL
;
1041 for (header
= request
->headers
; header
!= NULL
; header
= header
->next
) {
1042 if (header
->name
!= NULL
&&
1043 !strcasecmp(header
->name
, "Authorization"))
1050 /* Return true if request carries Authorization header */
1051 int http_client_authenticates(const struct http_request
*request
) {
1052 if (find_authorization(request
))
1059 /* Return HTTP_ERROR_SUCCESS if request carries valid Basic credentials.
1060 * NULL @username or @password equales to empty string. */
1061 http_error
http_authenticate_basic(const struct http_request
*request
,
1062 const char *username
, const char *password
) {
1063 const struct http_header
*header
;
1064 const char *basic_cookie_client
;
1065 char *basic_cookie_plain
= NULL
, *basic_cookie_encoded
= NULL
;
1068 header
= find_authorization(request
);
1069 if (header
== NULL
) return HTTP_ERROR_CLIENT
;
1071 if (strncmp(header
->value
, "Basic ", 6)) return HTTP_ERROR_CLIENT
;
1072 basic_cookie_client
= header
->value
+ 6;
1074 if (-1 == test_asprintf(&basic_cookie_plain
, "%s:%s",
1075 (username
== NULL
) ? "" : username
,
1076 (password
== NULL
) ? "" : password
)) {
1077 return HTTP_ERROR_SERVER
;
1080 basic_cookie_encoded
= base64encode(basic_cookie_plain
,
1081 strlen(basic_cookie_plain
), 1);
1082 if (basic_cookie_encoded
== NULL
) {
1083 free(basic_cookie_plain
);
1084 return HTTP_ERROR_SERVER
;
1087 fprintf(stderr
, "Authenticating basic: got=<%s>, expected=<%s> (%s)\n",
1088 basic_cookie_client
, basic_cookie_encoded
, basic_cookie_plain
);
1089 free(basic_cookie_plain
);
1091 is_valid
= !strcmp(basic_cookie_encoded
, basic_cookie_client
);
1092 free(basic_cookie_encoded
);
1094 return (is_valid
) ? HTTP_ERROR_SUCCESS
: HTTP_ERROR_CLIENT
;
1098 /* Return HTTP_ERROR_SUCCESS if request carries valid OTP credentials.
1099 * NULL @username or @password or @otp equal to empty string. */
1100 http_error
http_authenticate_otp(const struct http_request
*request
,
1101 const char *username
, const char *password
, const char *otp
) {
1102 char *basic_password
= NULL
;
1105 /* Concatenate password and OTP code */
1106 if (-1 == test_asprintf(&basic_password
, "%s%s",
1107 (password
== NULL
) ? "": password
,
1108 (otp
== NULL
) ? "" : otp
)) {
1109 return HTTP_ERROR_SERVER
;
1112 /* Use Basic authentication */
1113 /* XXX: Specification does not define authorization method string */
1114 retval
= http_authenticate_basic(request
, username
, basic_password
);
1116 free(basic_password
);
1121 /* Return cookie value by name or NULL if does not present. */
1122 const char *http_find_cookie(const struct http_request
*request
,
1124 const struct http_header
*header
;
1126 const char *value
= NULL
;
1128 if (request
== NULL
|| name
== NULL
) return NULL
;
1129 length
= strlen(name
);
1131 for (header
= request
->headers
; header
!= NULL
; header
= header
->next
) {
1132 if (header
->name
!= NULL
&& !strcasecmp(header
->name
, "Cookie") &&
1133 header
->value
!= NULL
) {
1134 if (!strncmp(header
->value
, name
, length
) &&
1135 header
->value
[length
] == '=') {
1136 /* Return last cookie with the name */
1137 value
= header
->value
+ length
+ 1;
1145 /* Return Host header value or NULL if does not present. Returned string is
1146 * statically allocated. */
1147 const char *http_find_host(const struct http_request
*request
) {
1148 const struct http_header
*header
;
1149 const char *value
= NULL
;
1151 if (request
== NULL
) return NULL
;
1153 for (header
= request
->headers
; header
!= NULL
; header
= header
->next
) {
1154 if (header
->name
!= NULL
&& !strcmp(header
->name
, "Host")) {
1155 value
= header
->value
;
1162 /* Free a HTTP header and set it to NULL */
1163 void http_header_free(struct http_header
**header
) {
1164 if (header
== NULL
|| *header
== NULL
) return;
1165 free((*header
)->name
);
1166 free((*header
)->value
);
1172 /* Free linked list of HTTP headers and set it to NULL */
1173 void http_headers_free(struct http_header
**headers
) {
1174 struct http_header
*header
, *next
;
1176 if (headers
== NULL
|| *headers
== NULL
) return;
1178 for (header
= *headers
; header
!= NULL
;) {
1179 next
= header
->next
;
1180 http_header_free(&header
);
1187 /* Free HTTP request and set it to NULL */
1188 void http_request_free(struct http_request
**request
) {
1189 if (request
== NULL
|| *request
== NULL
) return;
1190 free((*request
)->uri
);
1191 http_headers_free(&((*request
)->headers
));
1192 free((*request
)->body
);
1197 /* Free HTTP response and set it to NULL */
1198 void http_response_free(struct http_response
**response
) {
1199 if (response
== NULL
|| *response
== NULL
) return;
1200 free((*response
)->reason
);
1201 http_headers_free(&((*response
)->headers
));
1202 free((*response
)->body
);