1 /* A very simple AWS-like server, without any authentication. This is meant
2 * performance testing in a local environment. The server offers weak
3 * guarantees on data durability--data is stored directly to the file system
4 * without synchronization, so data might be lost in a crash. This should
5 * offer good performance though for benchmarking.
7 * Protocol: Each request is a whitespace-separated (typically, a single space)
8 * list of parameters terminated by a newline character. The response is a
9 * line containing a response code and a body length (again white-separated and
10 * newline-terminated) followed by the response body. Requests:
11 * GET filename offset length
26 #include <netinet/in.h>
27 #include <sys/socket.h>
29 #include <sys/types.h>
32 /* Maximum number of connections the server will queue waiting for us to call
34 #define TCP_BACKLOG 32
36 #define WHITESPACE " \t\r\n"
39 /* Maximum length of a command that we will accept. */
40 #define MAX_CMD_LEN 4096
42 #define MAX_OBJECT_SIZE (256 << 20)
44 enum command { GET, PUT, LIST, DELETE };
46 void write_data(int fd, const char *buf, size_t len)
49 ssize_t bytes = write(fd, buf, len);
60 /* SIGCHLD handler, used to clean up processes that handle the connections. */
61 static void sigchld_handler(int signal)
66 while ((pid = waitpid(WAIT_ANY, NULL, WNOHANG)) > 0) {
71 if (errno == ECHILD && reaped) {
72 /* Don't print an error for the caes that we successfully cleaned
73 * up after all children. */
80 /* Return a text representation of a socket address. Returns a pointer to a
81 * static buffer so it is non-reentrant. */
82 const char *sockname(struct sockaddr_in *addr, socklen_t len)
85 if (len < sizeof(struct sockaddr_in))
87 if (addr->sin_family != AF_INET)
90 uint32_t ip = ntohl(addr->sin_addr.s_addr);
91 sprintf(buf, "%d.%d.%d.%d:%d",
92 (int)((ip >> 24) & 0xff),
93 (int)((ip >> 16) & 0xff),
94 (int)((ip >> 8) & 0xff),
96 ntohs(addr->sin_port));
101 /* Convert a path from a client to the actual filename used. Returns a string
102 * that must be freed. */
103 char *normalize_path(const char *in)
105 char *out = malloc(2 * strlen(in) + 1);
107 for (i = 0, j = 0; in[i] != '\0'; i++) {
111 } else if (in[i] == '_') {
122 void cmd_get(int fd, char *path, size_t start, ssize_t len)
126 char *response = "-1\n";
127 int file = open(path, O_RDONLY);
129 write_data(fd, response, strlen(response));
134 if (fstat(file, &statbuf) < 0) {
135 write_data(fd, response, strlen(response));
139 size_t datalen = statbuf.st_size;
141 if (start >= datalen) {
144 lseek(file, start, SEEK_SET);
148 if (len > 0 && len < datalen) {
152 sprintf(buf, "%zd\n", datalen);
153 write_data(fd, buf, strlen(buf));
155 while (datalen > 0) {
156 size_t needed = datalen > sizeof(buf) ? sizeof(buf) : datalen;
157 ssize_t bytes = read(file, buf, needed);
158 if (bytes < 0 && errno == EINTR)
161 /* Error reading necessary data, but we already told the client the
162 * file size so pad the data to the client with null bytes. */
163 memset(buf, 0, needed);
166 write_data(fd, buf, bytes);
173 void cmd_put(int fd, char *path, char *buf,
174 size_t object_size, size_t buf_used)
176 while (buf_used < object_size) {
179 bytes = read(fd, buf + buf_used, object_size - buf_used);
190 assert(bytes <= object_size - buf_used);
196 printf("Got %zd bytes for object '%s'\n", buf_used, path);
198 char *response = "-1\n";
199 int file = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0600);
201 write_data(file, buf, object_size);
206 write_data(fd, response, strlen(response));
209 /* The core handler for processing requests from the client. This can be
210 * single-threaded since each connection is handled in a separate process. */
211 void handle_connection(int fd)
213 char cmdbuf[MAX_CMD_LEN];
217 /* Keep reading data until reaching a newline, so that a complete
218 * command can be parsed. */
219 if (buflen == 0 || memchr(cmdbuf, '\n', buflen) == NULL) {
222 if (buflen == MAX_CMD_LEN) {
223 /* Command is too long and thus malformed; close the
228 bytes = read(fd, cmdbuf + buflen, MAX_CMD_LEN - buflen);
238 assert(bytes <= MAX_CMD_LEN - buflen);
244 size_t cmdlen = (char *)memchr(cmdbuf, '\n', buflen) - cmdbuf + 1;
245 cmdbuf[cmdlen - 1] = '\0';
248 char *args[MAX_ARGS];
249 int arg_int[MAX_ARGS];
250 for (token = strtok(cmdbuf, WHITESPACE), arg_count = 0;
252 token = strtok(NULL, WHITESPACE), arg_count++)
254 args[arg_count] = token;
255 arg_int[arg_count] = atoi(token);
261 char *path = normalize_path(args[1]);
263 if (strcmp(args[0], "GET") == 0 && arg_count == 4) {
265 } else if (strcmp(args[0], "PUT") == 0 && arg_count == 3) {
267 } else if (strcmp(args[0], "DELETE") == 0 && arg_count == 2) {
274 memmove(cmdbuf, cmdbuf + cmdlen, buflen - cmdlen);
279 cmd_get(fd, path, arg_int[2], arg_int[3]);
282 size_t object_size = arg_int[2];
283 if (object_size > MAX_OBJECT_SIZE)
285 char *data_buf = malloc(object_size);
286 if (data_buf == NULL)
288 size_t data_buflen = buflen > object_size ? object_size : buflen;
290 memcpy(data_buf, cmdbuf, data_buflen);
291 if (data_buflen < buflen) {
292 memmove(cmdbuf, cmdbuf + data_buflen, buflen - data_buflen);
297 cmd_put(fd, path, data_buf, object_size, data_buflen);
301 //cmd_delete(fd, path);
311 /* Create a listening TCP socket on a new address (we do not use a fixed port).
312 * Return the file descriptor of the listening socket. */
316 struct sockaddr_in server_addr;
317 socklen_t addr_len = sizeof(server_addr);
319 fd = socket(PF_INET, SOCK_STREAM, 0);
325 if (listen(fd, TCP_BACKLOG) < 0) {
330 if (getsockname(fd, (struct sockaddr *)&server_addr, &addr_len) < 0) {
331 perror("getsockname");
335 printf("Server listening on %s ...\n", sockname(&server_addr, addr_len));
341 /* Process-based server main loop. Wait for a connection, accept it, fork a
342 * child process to handle the connection, and repeat. Child processes are
343 * reaped in the SIGCHLD handler. */
344 void server_main(int listen_fd)
346 struct sigaction handler;
348 /* Install signal handler for SIGCHLD. */
349 handler.sa_handler = sigchld_handler;
350 sigemptyset(&handler.sa_mask);
351 handler.sa_flags = SA_RESTART;
352 if (sigaction(SIGCHLD, &handler, NULL) < 0) {
358 struct sockaddr_in client_addr;
359 socklen_t addr_len = sizeof(client_addr);
360 int client_fd = accept(listen_fd, (struct sockaddr *)&client_addr,
364 /* Very simple error handling. Exit if something goes wrong. Later,
365 * might want to look into not killing off current connections abruptly
366 * if we encounter an error in the accept(). */
375 printf("Accepted connection from %s ...\n",
376 sockname(&client_addr, addr_len));
382 } else if (pid == 0) {
383 handle_connection(client_fd);
384 printf("Closing connection %s ...\n",
385 sockname(&client_addr, addr_len));
394 /* Print a help message describing command-line options to stdout. */
395 static void usage(char *argv0)
397 printf("Usage: %s [options...]\n"
398 "A simple key-value storage server.\n", argv0);
401 int main(int argc, char *argv[])
405 int display_help = 0, cmdline_error = 0;
408 for (i = 1; i < argc; i++) {
409 if (strcmp(argv[i], "-help") == 0) {
411 } else if (strcmp(argv[i], "-document_root") == 0) {
415 "Error: Argument to -document_root expected.\n");
418 document_root = argv[i];
420 } else if (strcmp(argv[i], "-port") == 0) {
424 "Error: Expected port number after -port.\n");
427 server_port = atoi(argv[i]);
428 if (server_port < 1 || server_port > 65535) {
430 "Error: Port must be between 1 and 65535.\n");
434 } else if (strcmp(argv[i], "-mime_types") == 0) {
438 "Error: Argument to -mime_types expected.\n");
441 mime_types_file = argv[i];
443 } else if (strcmp(argv[i], "-log") == 0) {
447 "Error: Argument to -log expected.\n");
453 fprintf(stderr, "Error: Unrecognized option '%s'\n", argv[i]);
459 /* Display a help message if requested, or let the user know to look at the
460 * help message if there was an error parsing the command line. In either
461 * case, the server never starts. */
465 } else if (cmdline_error) {
466 fprintf(stderr, "Run '%s -help' for a summary of options.\n", argv[0]);