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-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
) {
248 if (line
== NULL
) return HTTP_ERROR_SERVER
;
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
;
261 for (p
= *buffer
; p
< *buffer
+ *buffer_used
; p
++)
265 if (!(p
+ 1 < *buffer
+ *buffer_used
&& p
[1] == '\n'))
269 /* Crop by zero at EOL */
272 /* Copy read ahead data to new buffer and point line to original
275 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
276 memcpy(tmp
, p
, *buffer
+ *buffer_used
- p
);
278 *buffer_size
= BURST
;
279 *buffer_used
= *buffer
+ *buffer_used
- p
;
282 return HTTP_ERROR_SUCCESS
;
285 if (*buffer_size
== *buffer_used
) {
287 tmp
= realloc(*buffer
, *buffer_size
+ BURST
);
288 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
290 *buffer_size
+= BURST
;
294 got
= connection
->recv_callback(connection
, *buffer
+ *buffer_used
,
295 *buffer_size
- *buffer_used
);
296 if (got
== -1) return HTTP_ERROR_CLIENT
;
299 if (got
== 0) return HTTP_ERROR_CLIENT
;
301 /* Move end of buffer */
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
) {
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
,
340 if (line
== NULL
) return HTTP_ERROR_SERVER
;
342 fprintf(stderr
, "Response: <%s>\n", line
);
345 if ((error
= http_write_bulk(connection
, line
, strlen(line
))))
349 if ((error
= http_write_bulk(connection
, "\r\n", 2)))
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
) {
372 if (data
== NULL
) return HTTP_ERROR_SERVER
;
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
;
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
391 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
392 memcpy(tmp
, *buffer
+ data_length
, *buffer_used
- data_length
);
394 *buffer_size
= BURST
;
395 *buffer_used
= *buffer_used
- data_length
;
398 return HTTP_ERROR_SUCCESS
;
401 if (*buffer_size
== *buffer_used
) {
403 tmp
= realloc(*buffer
, *buffer_size
+ BURST
);
404 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
406 *buffer_size
+= BURST
;
410 got
= connection
->recv_callback(connection
, *buffer
+ *buffer_used
,
411 *buffer_size
- *buffer_used
);
412 if (got
== -1) return HTTP_ERROR_CLIENT
;
415 if (got
== 0) return HTTP_ERROR_CLIENT
;
417 /* Move end of buffer */
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
) {
433 fprintf(stderr
, "Request: <%s>\n", line
);
436 p
= strchr(line
, ' ');
437 if (p
== NULL
) return HTTP_ERROR_SERVER
;
439 if (!strcmp(line
, "GET"))
440 request
->method
= HTTP_METHOD_GET
;
441 else if (!strcmp(line
, "POST"))
442 request
->method
= HTTP_METHOD_POST
;
444 request
->method
= HTTP_METHOD_UNKNOWN
;
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
) {
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
);
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 */
497 return HTTP_ERROR_CLIENT
; /* No previous header to continue */
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
;
504 strcpy(&header
->value
[old_length
], line
);
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';
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
;
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
) {
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
);
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
) {
579 long long int value
= strtol(header
->value
, &p
, 10);
581 return HTTP_ERROR_CLIENT
;
582 if ((value
== LLONG_MIN
|| value
== LLONG_MAX
) && errno
== ERANGE
)
583 return HTTP_ERROR_SERVER
;
585 return HTTP_ERROR_CLIENT
;
586 if (value
> SIZE_MAX
)
587 return HTTP_ERROR_SERVER
;
588 request
->body_length
= value
;
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
]);
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
) {
620 size_t buffer_size
= 0, buffer_used
= 0;
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
,
632 if ((error
= http_parse_request_header(line
, *request
)))
635 /* Get other headers */
637 if ((error
= http_read_line(connection
, &line
, &buffer
, &buffer_size
,
639 fprintf(stderr
, "Error while reading HTTP request line\n");
643 /* Check for headers delimiter */
644 if (line
== NULL
|| *line
== '\0') {
648 if ((error
= http_parse_header(line
, *request
))) {
649 fprintf(stderr
, "Error while parsing HTTP request line: <%s>\n",
656 if ((error
= find_content_length(*request
))) {
657 fprintf(stderr
, "Could not determine length of body\n");
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");
666 fprintf(stderr
, "Body of size %zu B has been received:\n",
667 (*request
)->body_length
);
668 dump_body((*request
)->body
, (*request
)->body_length
);
673 if (error
) http_request_free(request
);
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
) {
685 if (response
== NULL
) return HTTP_ERROR_SERVER
;
688 error
= http_write_response_status(connection
, response
);
689 if (error
) return error
;
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
;
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
);
718 return HTTP_ERROR_SUCCESS
;
722 /* Build Set-Cookie header. In case of error, return NULL. Caller must free
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",
744 if (cookie_path
!= NULL
)
745 if (-1 == test_asprintf(&path_parameter
, "; Path=%s",
749 if (-1 == test_asprintf(&header
->value
, "%s=%s%s%s",
751 (cookie_value
== NULL
) ? "" : cookie_value
,
752 (domain_parameter
== NULL
) ? "": domain_parameter
,
753 (path_parameter
== NULL
) ? "": path_parameter
))
758 http_header_free(&header
);
760 free(domain_parameter
);
761 free(path_parameter
);
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
) {
772 struct http_header
*header_cookie
= NULL
;
773 struct http_header header_contenttype
= {
774 .name
= "Content-Type",
775 .value
= (char *)type
,
778 struct http_response response
= {
782 .body_length
= body_length
,
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 */
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
);
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
) {
823 struct http_header
*header_cookie
= NULL
;
824 struct http_header header_location
= {
826 .value
= (char *) location
,
829 struct http_response response
= {
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
);
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
,
867 struct http_header header_text
= {
868 .name
= "X-Response-message-text",
869 .value
= (char *) text
,
872 struct http_header header_location
= {
874 .value
= (char *) location
,
877 struct http_response response
= {
885 /* Link defined headers */
886 if (location
!= NULL
) {
887 response
.headers
= &header_location
;
890 header_text
.next
= response
.headers
;
891 response
.headers
= &header_text
;
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
= {
908 .reason
= (reason
== NULL
) ? "Bad Request" : (char *) reason
,
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\"",
925 struct http_response response
= {
927 .reason
= "Unauthorized",
933 return http_write_response(connection
, &response
);
937 /* Send a 401 Unauthorized response with OTP authentication scheme header for
939 int http_send_response_401_otp(const struct http_connection
*connection
,
940 const char *method
, const char *code
, const char *text
) {
942 struct http_header header
= {
943 .name
= "WWW-Authenticate",
947 struct http_header header_code
= {
948 .name
= "X-Response-message-code",
949 .value
= (char *) code
,
952 struct http_header header_text
= {
953 .name
= "X-Response-message-text",
954 .value
= (char *) text
,
957 struct http_response response
= {
959 .reason
= "Unauthorized",
965 if (-1 == test_asprintf(&header
.value
, "%s realm=\"SimulatedISDSServer\"",
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
;
975 header_code
.next
= &header_text
;
977 header
.next
= &header_text
;
980 retval
= http_write_response(connection
, &response
);
986 /* Send a 403 Forbidden response */
987 int http_send_response_403(const struct http_connection
*connection
) {
988 struct http_response response
= {
990 .reason
= "Forbidden",
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
= {
1006 .reason
= (NULL
== reason
) ? "Internal Server Error" : (char *) reason
,
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
= {
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"))
1049 /* Return true if request carries Authorization header */
1050 int http_client_authenticates(const struct http_request
*request
) {
1051 if (find_authorization(request
))
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
;
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
;
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
);
1120 /* Return cookie value by name or NULL if does not present. */
1121 const char *http_find_cookie(const struct http_request
*request
,
1123 const struct http_header
*header
;
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;
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
;
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
);
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
);
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
);
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
);