Skip to content

Commit

Permalink
connection: New api: serve_file
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Jul 2, 2020
1 parent 2c1b284 commit 2844706
Show file tree
Hide file tree
Showing 8 changed files with 405 additions and 13 deletions.
36 changes: 24 additions & 12 deletions example/example.c
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,27 @@

#include "uhttpd.h"

static bool serve_file = false;
static const char *docroot = ".";
static const char *index_page = "index.html";

static void on_request(struct uh_connection *conn)
{
int body_len;
const char *body = conn->get_body(conn, &body_len);

conn->send_head(conn, HTTP_STATUS_OK, -1, NULL);
conn->chunk_printf(conn, "I'm Libuhttpd: %s\n", UHTTPD_VERSION_STRING);
conn->chunk_printf(conn, "Method: %s\n", conn->get_method_str(conn));
conn->chunk_printf(conn, "Path: %s\n", conn->get_path(conn));
conn->chunk_printf(conn, "Query: %s\n", conn->get_query(conn));
conn->chunk_printf(conn, "User-Agent: %s\n", conn->get_header(conn, "User-Agent"));
conn->chunk_printf(conn, "Body: %.*s\n", body_len, body);
conn->chunk_end(conn);
if (!serve_file) {
int body_len;
const char *body = conn->get_body(conn, &body_len);

conn->send_head(conn, HTTP_STATUS_OK, -1, NULL);
conn->chunk_printf(conn, "I'm Libuhttpd: %s\n", UHTTPD_VERSION_STRING);
conn->chunk_printf(conn, "Method: %s\n", conn->get_method_str(conn));
conn->chunk_printf(conn, "Path: %s\n", conn->get_path(conn));
conn->chunk_printf(conn, "Query: %s\n", conn->get_query(conn));
conn->chunk_printf(conn, "User-Agent: %s\n", conn->get_header(conn, "User-Agent"));
conn->chunk_printf(conn, "Body: %.*s\n", body_len, body);
conn->chunk_end(conn);
} else {
conn->serve_file(conn, docroot, index_page);
}
}

static void signal_cb(struct ev_loop *loop, ev_signal *w, int revents)
Expand All @@ -58,6 +66,7 @@ static void usage(const char *prog)
fprintf(stderr, "Usage: %s [option]\n"
" -p port # Default port is 8080\n"
" -s # SSl on\n"
" -f # Serve file\n"
" -v # verbose\n", prog);
exit(1);
}
Expand All @@ -72,14 +81,17 @@ int main(int argc, char **argv)
int port = 8080;
int opt;

while ((opt = getopt(argc, argv, "p:sv")) != -1) {
while ((opt = getopt(argc, argv, "p:sfv")) != -1) {
switch (opt) {
case 'p':
port = atoi(optarg);
break;
case 's':
ssl = true;
break;
case 'f':
serve_file = true;
break;
case 'v':
verbose = true;
break;
Expand Down
2 changes: 1 addition & 1 deletion src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ if(HAVE_DLOPEN)
add_definitions(-DHAVE_DLOPEN)
endif()

set(SOURCE_FILES uhttpd.c log.c connection.c buffer/buffer.c http-parser/http_parser.c ssl.c)
set(SOURCE_FILES uhttpd.c log.c connection.c buffer/buffer.c http-parser/http_parser.c ssl.c file.c mimetypes.c)

option(BUILD_SHARED_LIBS "Build shared library" ON)
option(BUILD_STATIC_LIBS "Build static library" ON)
Expand Down
2 changes: 2 additions & 0 deletions src/connection.c
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
#include "connection.h"
#include "uhttpd.h"
#include "utils.h"
#include "file.h"
#include "ssl.h"


Expand Down Expand Up @@ -573,6 +574,7 @@ struct uh_connection *uh_new_connection(struct uh_server *srv, int sock, struct
conn->send_head = conn_send_head;
conn->error = conn_error;
conn->redirect = conn_redirect;
conn->serve_file = serve_file;

conn->chunk_send = conn_chunk_send;
conn->chunk_printf = conn_chunk_printf;
Expand Down
1 change: 1 addition & 0 deletions src/connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ struct uh_connection {
void (*send_head)(struct uh_connection *conn, int code, int content_length, const char *extra_headers);
void (*error)(struct uh_connection *conn, int code, const char *reason);
void (*redirect)(struct uh_connection *conn, int code, const char *location, ...);
void (*serve_file)(struct uh_connection *conn, const char *docroot, const char *index_page);
void (*chunk_send)(struct uh_connection *conn, const void *data, ssize_t len);
void (*chunk_printf)(struct uh_connection *conn, const char *format, ...);
void (*chunk_vprintf)(struct uh_connection *conn, const char *format, va_list arg);
Expand Down
194 changes: 194 additions & 0 deletions src/file.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
/*
* MIT License
*
* Copyright (c) 2019 Jianhui Zhao <zhaojh329@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

#define _DEFAULT_SOURCE
#define _XOPEN_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <inttypes.h>

#include "connection.h"
#include "mimetypes.h"


static const char *file_mktag(struct stat *s, char *buf, int len)
{
snprintf(buf, len, "\"%" PRIx64 "-%" PRIx64 "-%" PRIx64 "\"",
s->st_ino, s->st_size, (uint64_t)s->st_mtime);

return buf;
}

static char *unix2date(time_t ts, char *buf, int len)
{
struct tm *t = gmtime(&ts);

strftime(buf, len, "%a, %d %b %Y %H:%M:%S GMT", t);

return buf;
}

static time_t date2unix(const char *date)
{
struct tm t;

memset(&t, 0, sizeof(t));

if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
return timegm(&t);

return 0;
}

static void file_response_ok_hdrs(struct uh_connection *conn, struct stat *s)
{
char buf[128];

if (s) {
conn->printf(conn, "ETag: %s\r\n", file_mktag(s, buf, sizeof(buf)));
conn->printf(conn, "Last-Modified: %s\r\n", unix2date(s->st_mtime, buf, sizeof(buf)));

}
conn->printf(conn, "Date: %s\r\n", unix2date(time(NULL), buf, sizeof(buf)));
}

static void file_response_304(struct uh_connection *conn, struct stat *s)
{
conn->send_status_line(conn, HTTP_STATUS_NOT_MODIFIED, NULL);

file_response_ok_hdrs(conn, s);
}

static bool file_if_modified_since(struct uh_connection *conn, struct stat *s)
{
const char *hdr = conn->get_header(conn, "If-Modified-Since");
if (!hdr[0])
return true;

if (date2unix(hdr) >= s->st_mtime) {
file_response_304(conn, s);
return false;
}

return true;
}

static bool file_if_range(struct uh_connection *conn, struct stat *s)
{
const char *hdr = conn->get_header(conn, "If-Range");
if (hdr[0]) {
conn->error(conn, HTTP_STATUS_PRECONDITION_FAILED, NULL);
return false;
}

return true;
}

static bool file_if_unmodified_since(struct uh_connection *conn, struct stat *s)
{
const char *hdr = conn->get_header(conn, "If-Modified-Since");
if (hdr[0] && date2unix(hdr) <= s->st_mtime) {
conn->error(conn, HTTP_STATUS_PRECONDITION_FAILED, NULL);
return false;
}

return true;
}

void serve_file(struct uh_connection *conn, const char *docroot, const char *index_page)
{
const char *path = conn->get_path(conn);
static char fullpath[512];
struct stat st;

if (!docroot || !docroot[0])
docroot = ".";

if (!index_page || !index_page[0])
index_page = "index.html";

strcpy(fullpath, docroot);

if (!strcmp(path, "/")) {
strcat(fullpath, "/");
path = index_page;
}

strcat(fullpath, path);

if (stat(fullpath, &st) < 0) {
int code;

switch (errno) {
case EACCES:
code = HTTP_STATUS_FORBIDDEN;
break;
case ENOENT:
code = HTTP_STATUS_NOT_FOUND;
break;
default:
code = HTTP_STATUS_INTERNAL_SERVER_ERROR;
};

conn->error(conn, code, NULL);
return;
}

if (!S_ISLNK(st.st_mode) && !S_ISREG(st.st_mode)) {
conn->error(conn, 403, NULL);
return;
}

switch (conn->get_method(conn)) {
case HTTP_GET:
case HTTP_HEAD:
break;
default:
conn->error(conn, HTTP_STATUS_METHOD_NOT_ALLOWED, NULL);
return;
}

if (!file_if_modified_since(conn, &st) ||
!file_if_range(conn, &st) ||
!file_if_unmodified_since(conn, &st)) {
conn->printf(conn, "\r\n");
return;
}

conn->send_status_line(conn, HTTP_STATUS_OK, NULL);
file_response_ok_hdrs(conn, &st);

conn->printf(conn, "Content-Type: %s\r\n", file_mime_lookup(path));
conn->printf(conn, "Content-Length: %" PRIu64 "\r\n\r\n", st.st_size);

if (conn->get_method(conn) == HTTP_HEAD)
return;

conn->send_file(conn, fullpath);
}
32 changes: 32 additions & 0 deletions src/file.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* MIT License
*
* Copyright (c) 2019 Jianhui Zhao <zhaojh329@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

#ifndef _UH_FILE_H
#define _UH_FILE_H

#include "connection.h"

void serve_file(struct uh_connection *conn, const char *docroot, const char *index_page);

#endif
Loading

0 comments on commit 2844706

Please sign in to comment.