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
;
236 void *http_recv_context
= NULL
;
237 void *http_send_context
= NULL
;
239 /* Read a line from HTTP socket.
240 * @socket is descriptor to read from.
241 * @line is auto-allocated just read line. Will be NULL if EOF has been
242 * reached or error occured.
243 * @buffer is automatically reallocated buffer for the socket. It can preserve
244 * prematurately read socket data.
245 * @buffer_size is allocated size of @buffer
246 * @buffer_length is size of head of the buffer that holds read data.
247 * @return 0 in success. */
248 static int http_read_line(int socket
, char **line
,
249 char **buffer
, size_t *buffer_size
, size_t *buffer_used
) {
253 if (line
== NULL
) return HTTP_ERROR_SERVER
;
256 if (buffer
== NULL
|| buffer_size
== NULL
|| buffer_used
== NULL
)
257 return HTTP_ERROR_SERVER
;
258 if (*buffer
== NULL
&& *buffer_size
> 0) return HTTP_ERROR_SERVER
;
259 if (*buffer_size
< *buffer_used
) return HTTP_ERROR_SERVER
;
264 for (p
= *buffer
; p
< *buffer
+ *buffer_used
; p
++)
268 if (!(p
+ 1 < *buffer
+ *buffer_used
&& p
[1] == '\n'))
272 /* Crop by zero at EOL */
275 /* Copy read ahead data to new buffer and point line to original
278 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
279 memcpy(tmp
, p
, *buffer
+ *buffer_used
- p
);
281 *buffer_size
= BURST
;
282 *buffer_used
= *buffer
+ *buffer_used
- p
;
285 return HTTP_ERROR_SUCCESS
;
288 if (*buffer_size
== *buffer_used
) {
290 tmp
= realloc(*buffer
, *buffer_size
+ BURST
);
291 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
293 *buffer_size
+= BURST
;
297 got
= http_recv_callback(http_recv_context
, *buffer
+ *buffer_used
,
298 *buffer_size
- *buffer_used
, 0);
299 if (got
== -1) return HTTP_ERROR_CLIENT
;
302 if (got
== 0) return HTTP_ERROR_CLIENT
;
304 /* Move end of buffer */
309 return HTTP_ERROR_SERVER
;
313 /* Write a bulk data into HTTP socket.
314 * @socket is descriptor to write to.
315 * @data are bitstream to send to client.
316 * @length is size of @data in bytes.
317 * @return 0 in success. */
318 static int http_write_bulk(int socket
, const void *data
, size_t length
) {
322 if (data
== NULL
&& length
> 0) return HTTP_ERROR_SERVER
;
324 for (end
= data
+ length
; data
!= end
; data
+= written
, length
-= written
) {
325 written
= http_send_callback(http_send_context
, data
, length
,
327 if (written
== -1) return HTTP_ERROR_CLIENT
;
330 return HTTP_ERROR_SUCCESS
;
334 /* Write a line into HTTP socket.
335 * @socket is descriptor 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(int socket
, const char *line
) {
340 if (line
== NULL
) return HTTP_ERROR_SERVER
;
342 fprintf(stderr
, "Response: <%s>\n", line
);
345 if ((error
= http_write_bulk(socket
, line
, strlen(line
))))
349 if ((error
= http_write_bulk(socket
, "\r\n", 2)))
352 return HTTP_ERROR_SUCCESS
;
356 /* Read data of given length from HTTP socket.
357 * @socket is descriptor 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(int socket
, void **data
, size_t data_length
,
367 char **buffer
, size_t *buffer_size
, size_t *buffer_used
) {
371 if (data
== NULL
) return HTTP_ERROR_SERVER
;
374 if (buffer
== NULL
|| buffer_size
== NULL
|| buffer_used
== NULL
)
375 return HTTP_ERROR_SERVER
;
376 if (*buffer
== NULL
&& *buffer_size
> 0) return HTTP_ERROR_SERVER
;
377 if (*buffer_size
< *buffer_used
) return HTTP_ERROR_SERVER
;
379 if (data_length
<= 0) return HTTP_ERROR_SUCCESS
;
383 /* Check whether enought data have been read */
384 if (*buffer_used
>= data_length
) {
385 /* Copy read ahead data to new buffer and point data to original
388 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
389 memcpy(tmp
, *buffer
+ data_length
, *buffer_used
- data_length
);
391 *buffer_size
= BURST
;
392 *buffer_used
= *buffer_used
- data_length
;
395 return HTTP_ERROR_SUCCESS
;
398 if (*buffer_size
== *buffer_used
) {
400 tmp
= realloc(*buffer
, *buffer_size
+ BURST
);
401 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
403 *buffer_size
+= BURST
;
407 got
= http_recv_callback(http_recv_context
, *buffer
+ *buffer_used
,
408 *buffer_size
- *buffer_used
, 0);
409 if (got
== -1) return HTTP_ERROR_CLIENT
;
412 if (got
== 0) return HTTP_ERROR_CLIENT
;
414 /* Move end of buffer */
419 return HTTP_ERROR_SERVER
;
423 /* Parse HTTP request header.
424 * @request is pre-allocated HTTP request.
425 * @return 0 if success. */
426 static int http_parse_request_header(char *line
,
427 struct http_request
*request
) {
430 fprintf(stderr
, "Request: <%s>\n", line
);
433 p
= strchr(line
, ' ');
434 if (p
== NULL
) return HTTP_ERROR_SERVER
;
436 if (!strcmp(line
, "GET"))
437 request
->method
= HTTP_METHOD_GET
;
438 else if (!strcmp(line
, "POST"))
439 request
->method
= HTTP_METHOD_POST
;
441 request
->method
= HTTP_METHOD_UNKNOWN
;
445 p
= strchr(line
, ' ');
446 if (p
!= NULL
) *p
= '\0';
447 request
->uri
= uri_decode(line
);
448 if (request
->uri
== NULL
) return HTTP_ERROR_SERVER
;
450 /* Do not care about HTTP version */
452 fprintf(stderr
, "Request-URI: <%s>\n", request
->uri
);
453 return HTTP_ERROR_SUCCESS
;
457 /* Send HTTP response status line to client.
458 * @return 0 if success. */
459 static int http_write_response_status(int socket
,
460 const struct http_response
*response
) {
464 if (response
== NULL
) return HTTP_ERROR_SERVER
;
466 if (-1 == test_asprintf(&buffer
, "HTTP/1.0 %u %s", response
->status
,
467 (response
->reason
== NULL
) ? "" : response
->reason
))
468 return HTTP_ERROR_SERVER
;
469 error
= http_write_line(socket
, buffer
);
476 /* Parse generic HTTP header.
477 * @request is pre-allocated HTTP request.
478 * @return 0 if success, negative value if internal error, positive value if
479 * header is not valid. */
480 static int http_parse_header(char *line
, struct http_request
*request
) {
481 struct http_header
*header
;
483 if (line
== NULL
|| request
== NULL
) return HTTP_ERROR_SERVER
;
485 fprintf(stderr
, "Header: <%s>\n", line
);
487 /* Find last used header */
488 for (header
= request
->headers
; header
!= NULL
&& header
->next
!= NULL
;
489 header
= header
->next
);
491 if (*line
== ' ' || *line
== '\t') {
492 /* Line is continuation of last header */
494 return HTTP_ERROR_CLIENT
; /* No previous header to continue */
496 size_t old_length
= strlen(header
->value
);
497 char *tmp
= realloc(header
->value
,
498 sizeof(header
->value
[0]) * (old_length
+ strlen(line
) + 1));
499 if (tmp
== NULL
) return HTTP_ERROR_SERVER
;
501 strcpy(&header
->value
[old_length
], line
);
504 struct http_header
*new_header
= calloc(sizeof(*new_header
), 1);
505 if (new_header
== NULL
) return HTTP_ERROR_SERVER
;
507 char *p
= strstr(line
, ": ");
508 if (p
== NULL
) return HTTP_ERROR_CLIENT
;
510 size_t length
= p
- line
;
511 new_header
->name
= malloc(sizeof(line
[0]) * (length
+ 1));
512 if (new_header
->name
== NULL
) {
513 http_header_free(&new_header
);
514 return HTTP_ERROR_SERVER
;
516 strncpy(new_header
->name
, line
, length
);
517 new_header
->name
[length
] = '\0';
521 new_header
->value
= malloc(sizeof(p
[0]) * (length
+ 1));
522 if (new_header
->value
== NULL
) {
523 http_header_free(&new_header
);
524 return HTTP_ERROR_SERVER
;
526 strcpy(new_header
->value
, p
);
528 if (request
->headers
== NULL
)
529 request
->headers
= new_header
;
531 header
->next
= new_header
;
535 /* FIXME: Decode. After parsing all headers as we could decode begining
536 * and then got encoded continuation. */
537 return HTTP_ERROR_SUCCESS
;
541 /* Send HTTP header to client.
542 * @return 0 if success. */
543 static int http_write_header(int socket
, const struct http_header
*header
) {
547 if (header
== NULL
) return HTTP_ERROR_SERVER
;
549 if (header
->name
== NULL
) return HTTP_ERROR_SERVER
;
551 /* TODO: Quote, split long lines */
552 if (-1 == test_asprintf(&buffer
, "%s: %s", header
->name
,
553 (header
->value
== NULL
) ? "" : header
->value
))
554 return HTTP_ERROR_SERVER
;
555 error
= http_write_line(socket
, buffer
);
562 /* Find Content-Length value in HTTP request headers and set it into @request.
563 * @return 0 in success. */
564 static int find_content_length(struct http_request
*request
) {
565 struct http_header
*header
;
566 if (request
== NULL
) return HTTP_ERROR_SERVER
;
568 for (header
= request
->headers
; header
!= NULL
; header
= header
->next
) {
569 if (header
->name
== NULL
) continue;
570 if (!strcasecmp(header
->name
, "Content-Length")) break;
573 if (header
!= NULL
&& header
->value
!= NULL
) {
575 long long int value
= strtol(header
->value
, &p
, 10);
577 return HTTP_ERROR_CLIENT
;
578 if ((value
== LLONG_MIN
|| value
== LLONG_MAX
) && errno
== ERANGE
)
579 return HTTP_ERROR_SERVER
;
581 return HTTP_ERROR_CLIENT
;
582 if (value
> SIZE_MAX
)
583 return HTTP_ERROR_SERVER
;
584 request
->body_length
= value
;
586 request
->body_length
= 0;
588 return HTTP_ERROR_SUCCESS
;
592 /* Print binary stream to STDERR with some escapes */
593 static void dump_body(const void *data
, size_t length
) {
594 fprintf(stderr
, "===BEGIN BODY===\n");
595 if (length
> 0 && NULL
!= data
) {
596 for (size_t i
= 0; i
< length
; i
++) {
597 if (isprint(((const unsigned char *)data
)[i
]))
598 fprintf(stderr
, "%c", ((const unsigned char *)data
)[i
]);
600 fprintf(stderr
, "\\x%02x", ((const unsigned char*)data
)[i
]);
602 fprintf(stderr
, "\n");
604 fprintf(stderr
, "===END BODY===\n");
608 /* Read a HTTP request from connected socket.
609 * @http_request is heap-allocated received HTTP request,
610 * or NULL in case of error.
611 * @return http_error code. */
612 http_error
http_read_request(int socket
, struct http_request
**request
) {
615 size_t buffer_size
= 0, buffer_used
= 0;
618 if (request
== NULL
) return HTTP_ERROR_SERVER
;
620 *request
= calloc(1, sizeof(**request
));
621 if (*request
== NULL
) return HTTP_ERROR_SERVER
;
623 /* Get request header */
624 if ((error
= http_read_line(socket
, &line
, &buffer
, &buffer_size
,
627 if ((error
= http_parse_request_header(line
, *request
)))
630 /* Get other headers */
632 if ((error
= http_read_line(socket
, &line
, &buffer
, &buffer_size
,
634 fprintf(stderr
, "Error while reading HTTP request line\n");
638 /* Check for headers delimiter */
639 if (line
== NULL
|| *line
== '\0') {
643 if ((error
= http_parse_header(line
, *request
))) {
644 fprintf(stderr
, "Error while parsing HTTP request line: <%s>\n",
651 if ((error
= find_content_length(*request
))) {
652 fprintf(stderr
, "Could not determine length of body\n");
655 if ((error
= http_read_bulk(socket
,
656 &(*request
)->body
, (*request
)->body_length
,
657 &buffer
, &buffer_size
, &buffer_used
))) {
658 fprintf(stderr
, "Could not read request body\n");
661 fprintf(stderr
, "Body of size %zu B has been received:\n",
662 (*request
)->body_length
);
663 dump_body((*request
)->body
, (*request
)->body_length
);
668 if (error
) http_request_free(request
);
673 /* Write a HTTP response to connected socket. Auto-add Content-Length header.
674 * @return 0 in case of success. */
675 int http_write_response(int socket
, const struct http_response
*response
) {
679 if (response
== NULL
) return HTTP_ERROR_SERVER
;
682 error
= http_write_response_status(socket
, response
);
683 if (error
) return error
;
686 for (struct http_header
*header
= response
->headers
; header
!= NULL
;
687 header
= header
->next
) {
688 error
= http_write_header(socket
, header
);
689 if (error
) return error
;
691 if (-1 == test_asprintf(&buffer
, "Content-Length: %u",
692 response
->body_length
))
693 return HTTP_ERROR_SERVER
;
694 error
= http_write_line(socket
, buffer
);
695 if (error
) return error
;
697 /* Headers trailer */
698 error
= http_write_line(socket
, "");
699 if (error
) return error
;
702 if (response
->body_length
> 0) {
703 error
= http_write_bulk(socket
, response
->body
, response
->body_length
);
704 if (error
) return error
;
706 fprintf(stderr
, "Body of size %zu B has been sent:\n",
707 response
->body_length
);
708 dump_body(response
->body
, response
->body_length
);
711 return HTTP_ERROR_SUCCESS
;
715 /* Build Set-Cookie header. In case of error, return NULL. Caller must free
717 static struct http_header
*http_build_setcookie_header (
718 const char *cokie_name
, const char *cookie_value
,
719 const char *cookie_domain
, const char *cookie_path
) {
720 struct http_header
*header
= NULL
;
721 char *domain_parameter
= NULL
;
722 char *path_parameter
= NULL
;
724 if (cokie_name
== NULL
) goto error
;
726 header
= calloc(1, sizeof(*header
));
727 if (header
== NULL
) goto error
;
729 header
->name
= strdup("Set-Cookie");
730 if (header
->name
== NULL
) goto error
;
732 if (cookie_domain
!= NULL
)
733 if (-1 == test_asprintf(&domain_parameter
, "; Domain=%s",
737 if (cookie_path
!= NULL
)
738 if (-1 == test_asprintf(&path_parameter
, "; Path=%s",
742 if (-1 == test_asprintf(&header
->value
, "%s=%s%s%s",
744 (cookie_value
== NULL
) ? "" : cookie_value
,
745 (domain_parameter
== NULL
) ? "": domain_parameter
,
746 (path_parameter
== NULL
) ? "": path_parameter
))
751 http_header_free(&header
);
753 free(domain_parameter
);
754 free(path_parameter
);
759 /* Send a 200 Ok response with a cookie */
760 int http_send_response_200_cookie(int client_socket
,
761 const char *cokie_name
, const char *cookie_value
,
762 const char *cookie_domain
, const char *cookie_path
,
763 const void *body
, size_t body_length
, const char *type
) {
765 struct http_header
*header_cookie
= NULL
;
766 struct http_header header_contenttype
= {
767 .name
= "Content-Type",
768 .value
= (char *)type
,
771 struct http_response response
= {
775 .body_length
= body_length
,
779 if (cokie_name
!= NULL
) {
780 if (NULL
== (header_cookie
= http_build_setcookie_header(
781 cokie_name
, cookie_value
, cookie_domain
, cookie_path
)))
782 return http_send_response_500(client_socket
,
783 "Could not build Set-Cookie header");
786 /* Link defined headers */
788 response
.headers
= &header_contenttype
;
790 if (header_cookie
!= NULL
) {
791 header_cookie
->next
= response
.headers
;
792 response
.headers
= header_cookie
;
795 retval
= http_write_response(client_socket
, &response
);
796 http_header_free(&header_cookie
);
801 /* Send a 200 Ok response */
802 int http_send_response_200(int client_socket
,
803 const void *body
, size_t body_length
, const char *type
) {
804 return http_send_response_200_cookie(client_socket
,
805 NULL
, NULL
, NULL
, NULL
,
806 body
, body_length
, type
);
810 /* Send a 302 Found response setting a cookie */
811 int http_send_response_302_cookie(int client_socket
, const char *cokie_name
,
812 const char *cookie_value
, const char *cookie_domain
,
813 const char *cookie_path
, const char *location
) {
815 struct http_header
*header_cookie
= NULL
;
816 struct http_header header_location
= {
818 .value
= (char *) location
,
821 struct http_response response
= {
829 if (cokie_name
!= NULL
) {
830 if (NULL
== (header_cookie
= http_build_setcookie_header(
831 cokie_name
, cookie_value
, cookie_domain
, cookie_path
)))
832 return http_send_response_500(client_socket
,
833 "Could not build Set-Cookie header");
836 /* Link defined headers */
837 if (location
!= NULL
) {
838 response
.headers
= &header_location
;
840 if (header_cookie
!= NULL
) {
841 header_cookie
->next
= response
.headers
;
842 response
.headers
= header_cookie
;
845 retval
= http_write_response(client_socket
, &response
);
846 http_header_free(&header_cookie
);
851 /* Send a 302 Found response with totp authentication scheme header */
852 int http_send_response_302_totp(int client_socket
,
853 const char *code
, const char *text
, const char *location
) {
854 struct http_header header_code
= {
855 .name
= "X-Response-message-code",
856 .value
= (char *) code
,
859 struct http_header header_text
= {
860 .name
= "X-Response-message-text",
861 .value
= (char *) text
,
864 struct http_header header_location
= {
866 .value
= (char *) location
,
869 struct http_response response
= {
877 /* Link defined headers */
878 if (location
!= NULL
) {
879 response
.headers
= &header_location
;
882 header_text
.next
= response
.headers
;
883 response
.headers
= &header_text
;
886 header_code
.next
= response
.headers
;
887 response
.headers
= &header_code
;
890 return http_write_response(client_socket
, &response
);
894 /* Send a 400 Bad Request response.
895 * Use non-NULL @reason to override status message. */
896 int http_send_response_400(int client_socket
, const char *reason
) {
897 struct http_response response
= {
899 .reason
= (reason
== NULL
) ? "Bad Request" : (char *) reason
,
905 return http_write_response(client_socket
, &response
);
909 /* Send a 401 Unauthorized response with Basic authentication scheme header */
910 int http_send_response_401_basic(int client_socket
) {
911 struct http_header header
= {
912 .name
= "WWW-Authenticate",
913 .value
= "Basic realm=\"SimulatedISDSServer\"",
916 struct http_response response
= {
918 .reason
= "Unauthorized",
924 return http_write_response(client_socket
, &response
);
928 /* Send a 401 Unauthorized response with OTP authentication scheme header for
930 int http_send_response_401_otp(int client_socket
,
931 const char *method
, const char *code
, const char *text
) {
933 struct http_header header
= {
934 .name
= "WWW-Authenticate",
938 struct http_header header_code
= {
939 .name
= "X-Response-message-code",
940 .value
= (char *) code
,
943 struct http_header header_text
= {
944 .name
= "X-Response-message-text",
945 .value
= (char *) text
,
948 struct http_response response
= {
950 .reason
= "Unauthorized",
956 if (-1 == test_asprintf(&header
.value
, "%s realm=\"SimulatedISDSServer\"",
958 return http_send_response_500(client_socket
,
959 "Could not build WWW-Authenticate header value");
962 /* Link defined headers */
963 if (code
!= NULL
) header
.next
= &header_code
;
966 header_code
.next
= &header_text
;
968 header
.next
= &header_text
;
971 retval
= http_write_response(client_socket
, &response
);
977 /* Send a 403 Forbidden response */
978 int http_send_response_403(int client_socket
) {
979 struct http_response response
= {
981 .reason
= "Forbidden",
987 return http_write_response(client_socket
, &response
);
991 /* Send a 500 Internal Server Error response.
992 * Use non-NULL @reason to override status message. */
993 int http_send_response_500(int client_socket
, const char *reason
) {
994 struct http_response response
= {
996 .reason
= (NULL
== reason
) ? "Internal Server Error" : (char *) reason
,
1002 return http_write_response(client_socket
, &response
);
1006 /* Send a 503 Service Temporarily Unavailable response */
1007 int http_send_response_503(int client_socket
,
1008 const void *body
, size_t body_length
, const char *type
) {
1009 struct http_header header
= {
1010 .name
= "Content-Type",
1011 .value
= (char *)type
1013 struct http_response response
= {
1015 .reason
= "Service Temporarily Unavailable",
1016 .headers
= (type
== NULL
) ? NULL
: &header
,
1017 .body_length
= body_length
,
1018 .body
= (void *)body
1021 return http_write_response(client_socket
, &response
);
1025 /* Returns Authorization header in given request */
1026 static const struct http_header
*find_authorization(
1027 const struct http_request
*request
) {
1028 const struct http_header
*header
;
1029 if (request
== NULL
) return NULL
;
1030 for (header
= request
->headers
; header
!= NULL
; header
= header
->next
) {
1031 if (header
->name
!= NULL
&&
1032 !strcasecmp(header
->name
, "Authorization"))
1039 /* Return true if request carries Authorization header */
1040 int http_client_authenticates(const struct http_request
*request
) {
1041 if (find_authorization(request
))
1048 /* Return HTTP_ERROR_SUCCESS if request carries valid Basic credentials.
1049 * NULL @username or @password equales to empty string. */
1050 http_error
http_authenticate_basic(const struct http_request
*request
,
1051 const char *username
, const char *password
) {
1052 const struct http_header
*header
;
1053 const char *basic_cookie_client
;
1054 char *basic_cookie_plain
= NULL
, *basic_cookie_encoded
= NULL
;
1057 header
= find_authorization(request
);
1058 if (header
== NULL
) return HTTP_ERROR_CLIENT
;
1060 if (strncmp(header
->value
, "Basic ", 6)) return HTTP_ERROR_CLIENT
;
1061 basic_cookie_client
= header
->value
+ 6;
1063 if (-1 == test_asprintf(&basic_cookie_plain
, "%s:%s",
1064 (username
== NULL
) ? "" : username
,
1065 (password
== NULL
) ? "" : password
)) {
1066 return HTTP_ERROR_SERVER
;
1069 basic_cookie_encoded
= base64encode(basic_cookie_plain
,
1070 strlen(basic_cookie_plain
), 1);
1071 if (basic_cookie_encoded
== NULL
) {
1072 free(basic_cookie_plain
);
1073 return HTTP_ERROR_SERVER
;
1076 fprintf(stderr
, "Authenticating basic: got=<%s>, expected=<%s> (%s)\n",
1077 basic_cookie_client
, basic_cookie_encoded
, basic_cookie_plain
);
1078 free(basic_cookie_plain
);
1080 is_valid
= !strcmp(basic_cookie_encoded
, basic_cookie_client
);
1081 free(basic_cookie_encoded
);
1083 return (is_valid
) ? HTTP_ERROR_SUCCESS
: HTTP_ERROR_CLIENT
;
1087 /* Return HTTP_ERROR_SUCCESS if request carries valid OTP credentials.
1088 * NULL @username or @password or @otp equal to empty string. */
1089 http_error
http_authenticate_otp(const struct http_request
*request
,
1090 const char *username
, const char *password
, const char *otp
) {
1091 char *basic_password
= NULL
;
1094 /* Concatenate password and OTP code */
1095 if (-1 == test_asprintf(&basic_password
, "%s%s",
1096 (password
== NULL
) ? "": password
,
1097 (otp
== NULL
) ? "" : otp
)) {
1098 return HTTP_ERROR_SERVER
;
1101 /* Use Basic authentication */
1102 /* XXX: Specification does not define authorization method string */
1103 retval
= http_authenticate_basic(request
, username
, basic_password
);
1105 free(basic_password
);
1110 /* Return cookie value by name or NULL if does not present. */
1111 const char *http_find_cookie(const struct http_request
*request
,
1113 const struct http_header
*header
;
1115 const char *value
= NULL
;
1117 if (request
== NULL
|| name
== NULL
) return NULL
;
1118 length
= strlen(name
);
1120 for (header
= request
->headers
; header
!= NULL
; header
= header
->next
) {
1121 if (header
->name
!= NULL
&& !strcasecmp(header
->name
, "Cookie") &&
1122 header
->value
!= NULL
) {
1123 if (!strncmp(header
->value
, name
, length
) &&
1124 header
->value
[length
] == '=') {
1125 /* Return last cookie with the name */
1126 value
= header
->value
+ length
+ 1;
1134 /* Return Host header value or NULL if does not present. Returned string is
1135 * statically allocated. */
1136 const char *http_find_host(const struct http_request
*request
) {
1137 const struct http_header
*header
;
1138 const char *value
= NULL
;
1140 if (request
== NULL
) return NULL
;
1142 for (header
= request
->headers
; header
!= NULL
; header
= header
->next
) {
1143 if (header
->name
!= NULL
&& !strcmp(header
->name
, "Host")) {
1144 value
= header
->value
;
1151 /* Free a HTTP header and set it to NULL */
1152 void http_header_free(struct http_header
**header
) {
1153 if (header
== NULL
|| *header
== NULL
) return;
1154 free((*header
)->name
);
1155 free((*header
)->value
);
1161 /* Free linked list of HTTP headers and set it to NULL */
1162 void http_headers_free(struct http_header
**headers
) {
1163 struct http_header
*header
, *next
;
1165 if (headers
== NULL
|| *headers
== NULL
) return;
1167 for (header
= *headers
; header
!= NULL
;) {
1168 next
= header
->next
;
1169 http_header_free(&header
);
1176 /* Free HTTP request and set it to NULL */
1177 void http_request_free(struct http_request
**request
) {
1178 if (request
== NULL
|| *request
== NULL
) return;
1179 free((*request
)->uri
);
1180 http_headers_free(&((*request
)->headers
));
1181 free((*request
)->body
);
1186 /* Free HTTP response and set it to NULL */
1187 void http_response_free(struct http_response
**response
) {
1188 if (response
== NULL
|| *response
== NULL
) return;
1189 free((*response
)->reason
);
1190 http_headers_free(&((*response
)->headers
));
1191 free((*response
)->body
);