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 /* 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
) {
251 if (line
== NULL
) 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
= http_recv_callback(socket
, *buffer
+ *buffer_used
,
296 *buffer_size
- *buffer_used
, 0);
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 * @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
) {
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
) {
337 if (line
== NULL
) return HTTP_ERROR_SERVER
;
339 fprintf(stderr
, "Response: <%s>\n", line
);
342 if ((error
= http_write_bulk(socket
, line
, strlen(line
))))
346 if ((error
= http_write_bulk(socket
, "\r\n", 2)))
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
) {
368 if (data
== NULL
) return HTTP_ERROR_SERVER
;
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
;
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
385 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
386 memcpy(tmp
, *buffer
+ data_length
, *buffer_used
- data_length
);
388 *buffer_size
= BURST
;
389 *buffer_used
= *buffer_used
- data_length
;
392 return HTTP_ERROR_SUCCESS
;
395 if (*buffer_size
== *buffer_used
) {
397 tmp
= realloc(*buffer
, *buffer_size
+ BURST
);
398 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
400 *buffer_size
+= BURST
;
404 got
= http_recv_callback(socket
, *buffer
+ *buffer_used
,
405 *buffer_size
- *buffer_used
, 0);
406 if (got
== -1) return HTTP_ERROR_CLIENT
;
409 if (got
== 0) return HTTP_ERROR_CLIENT
;
411 /* Move end of buffer */
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
) {
427 fprintf(stderr
, "Request: <%s>\n", line
);
430 p
= strchr(line
, ' ');
431 if (p
== NULL
) return HTTP_ERROR_SERVER
;
433 if (!strcmp(line
, "GET"))
434 request
->method
= HTTP_METHOD_GET
;
435 else if (!strcmp(line
, "POST"))
436 request
->method
= HTTP_METHOD_POST
;
438 request
->method
= HTTP_METHOD_UNKNOWN
;
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
) {
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
);
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 */
491 return HTTP_ERROR_CLIENT
; /* No previous header to continue */
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
;
498 strcpy(&header
->value
[old_length
], line
);
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';
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
;
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
) {
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
);
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
) {
572 long long int value
= strtol(header
->value
, &p
, 10);
574 return HTTP_ERROR_CLIENT
;
575 if ((value
== LLONG_MIN
|| value
== LLONG_MAX
) && errno
== ERANGE
)
576 return HTTP_ERROR_SERVER
;
578 return HTTP_ERROR_CLIENT
;
579 if (value
> SIZE_MAX
)
580 return HTTP_ERROR_SERVER
;
581 request
->body_length
= value
;
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
]);
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
) {
612 size_t buffer_size
= 0, buffer_used
= 0;
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
,
624 if ((error
= http_parse_request_header(line
, *request
)))
627 /* Get other headers */
629 if ((error
= http_read_line(socket
, &line
, &buffer
, &buffer_size
,
631 fprintf(stderr
, "Error while reading HTTP request line\n");
635 /* Check for headers delimiter */
636 if (line
== NULL
|| *line
== '\0') {
640 if ((error
= http_parse_header(line
, *request
))) {
641 fprintf(stderr
, "Error while parsing HTTP request line: <%s>\n",
648 if ((error
= find_content_length(*request
))) {
649 fprintf(stderr
, "Could not determine length of body\n");
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");
658 fprintf(stderr
, "Body of size %zu B has been received:\n",
659 (*request
)->body_length
);
660 dump_body((*request
)->body
, (*request
)->body_length
);
665 if (error
) http_request_free(request
);
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
) {
676 if (response
== NULL
) return HTTP_ERROR_SERVER
;
679 error
= http_write_response_status(socket
, response
);
680 if (error
) return error
;
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
;
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
);
708 return HTTP_ERROR_SUCCESS
;
712 /* Build Set-Cookie header. In case of error, return NULL. Caller must free
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",
734 if (cookie_path
!= NULL
)
735 if (-1 == test_asprintf(&path_parameter
, "; Path=%s",
739 if (-1 == test_asprintf(&header
->value
, "%s=%s%s%s",
741 (cookie_value
== NULL
) ? "" : cookie_value
,
742 (domain_parameter
== NULL
) ? "": domain_parameter
,
743 (path_parameter
== NULL
) ? "": path_parameter
))
748 http_header_free(&header
);
750 free(domain_parameter
);
751 free(path_parameter
);
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
) {
762 struct http_header
*header_cookie
= NULL
;
763 struct http_header header_contenttype
= {
764 .name
= "Content-Type",
765 .value
= (char *)type
,
768 struct http_response response
= {
772 .body_length
= body_length
,
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 */
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
);
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
) {
812 struct http_header
*header_cookie
= NULL
;
813 struct http_header header_location
= {
815 .value
= (char *) location
,
818 struct http_response response
= {
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
);
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
,
856 struct http_header header_text
= {
857 .name
= "X-Response-message-text",
858 .value
= (char *) text
,
861 struct http_header header_location
= {
863 .value
= (char *) location
,
866 struct http_response response
= {
874 /* Link defined headers */
875 if (location
!= NULL
) {
876 response
.headers
= &header_location
;
879 header_text
.next
= response
.headers
;
880 response
.headers
= &header_text
;
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
= {
896 .reason
= (reason
== NULL
) ? "Bad Request" : (char *) reason
,
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\"",
913 struct http_response response
= {
915 .reason
= "Unauthorized",
921 return http_write_response(client_socket
, &response
);
925 /* Send a 401 Unauthorized response with OTP authentication scheme header for
927 int http_send_response_401_otp(int client_socket
,
928 const char *method
, const char *code
, const char *text
) {
930 struct http_header header
= {
931 .name
= "WWW-Authenticate",
935 struct http_header header_code
= {
936 .name
= "X-Response-message-code",
937 .value
= (char *) code
,
940 struct http_header header_text
= {
941 .name
= "X-Response-message-text",
942 .value
= (char *) text
,
945 struct http_response response
= {
947 .reason
= "Unauthorized",
953 if (-1 == test_asprintf(&header
.value
, "%s realm=\"SimulatedISDSServer\"",
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
;
963 header_code
.next
= &header_text
;
965 header
.next
= &header_text
;
968 retval
= http_write_response(client_socket
, &response
);
974 /* Send a 403 Forbidden response */
975 int http_send_response_403(int client_socket
) {
976 struct http_response response
= {
978 .reason
= "Forbidden",
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
= {
993 .reason
= (NULL
== reason
) ? "Internal Server Error" : (char *) reason
,
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
= {
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"))
1036 /* Return true if request carries Authorization header */
1037 int http_client_authenticates(const struct http_request
*request
) {
1038 if (find_authorization(request
))
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
;
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
;
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
);
1107 /* Return cookie value by name or NULL if does not present. */
1108 const char *http_find_cookie(const struct http_request
*request
,
1110 const struct http_header
*header
;
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;
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
;
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
);
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
);
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
);
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
);