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 filelen = statbuf.st_size;
140 sprintf(buf, "%zd\n", filelen);
141 write_data(fd, buf, strlen(buf));
143 while (filelen > 0) {
144 size_t needed = filelen > sizeof(buf) ? sizeof(buf) : filelen;
145 ssize_t bytes = read(file, buf, needed);
146 if (bytes < 0 && errno == EINTR)
149 /* Error reading necessary data, but we already told the client the
150 * file size so pad the data to the client with null bytes. */
151 memset(buf, 0, needed);
154 write_data(fd, buf, bytes);
161 void cmd_put(int fd, char *path, char *buf,
162 size_t object_size, size_t buf_used)
164 while (buf_used < object_size) {
167 bytes = read(fd, buf + buf_used, object_size - buf_used);
178 assert(bytes <= object_size - buf_used);
184 printf("Got %zd bytes for object '%s'\n", buf_used, path);
186 char *response = "-1\n";
187 int file = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0600);
189 write_data(file, buf, object_size);
194 write_data(fd, response, strlen(response));
197 /* The core handler for processing requests from the client. This can be
198 * single-threaded since each connection is handled in a separate process. */
199 void handle_connection(int fd)
201 char cmdbuf[MAX_CMD_LEN];
205 /* Keep reading data until reaching a newline, so that a complete
206 * command can be parsed. */
207 if (buflen == 0 || memchr(cmdbuf, '\n', buflen) == NULL) {
210 if (buflen == MAX_CMD_LEN) {
211 /* Command is too long and thus malformed; close the
216 bytes = read(fd, cmdbuf + buflen, MAX_CMD_LEN - buflen);
226 assert(bytes <= MAX_CMD_LEN - buflen);
232 size_t cmdlen = (char *)memchr(cmdbuf, '\n', buflen) - cmdbuf + 1;
233 cmdbuf[cmdlen - 1] = '\0';
236 char *args[MAX_ARGS];
237 int arg_int[MAX_ARGS];
238 for (token = strtok(cmdbuf, WHITESPACE), arg_count = 0;
240 token = strtok(NULL, WHITESPACE), arg_count++)
242 args[arg_count] = token;
243 arg_int[arg_count] = atoi(token);
249 char *path = normalize_path(args[1]);
251 if (strcmp(args[0], "GET") == 0 && arg_count == 4) {
253 } else if (strcmp(args[0], "PUT") == 0 && arg_count == 3) {
255 } else if (strcmp(args[0], "DELETE") == 0 && arg_count == 2) {
262 memmove(cmdbuf, cmdbuf + cmdlen, buflen - cmdlen);
267 cmd_get(fd, path, arg_int[2], arg_int[3]);
270 size_t object_size = arg_int[2];
271 if (object_size > MAX_OBJECT_SIZE)
273 char *data_buf = malloc(object_size);
274 if (data_buf == NULL)
276 size_t data_buflen = buflen > object_size ? object_size : buflen;
278 memcpy(data_buf, cmdbuf, data_buflen);
279 if (data_buflen < buflen) {
280 memmove(cmdbuf, cmdbuf + data_buflen, buflen - data_buflen);
285 cmd_put(fd, path, data_buf, object_size, data_buflen);
289 //cmd_delete(fd, path);
299 /* Create a listening TCP socket on a new address (we do not use a fixed port).
300 * Return the file descriptor of the listening socket. */
304 struct sockaddr_in server_addr;
305 socklen_t addr_len = sizeof(server_addr);
307 fd = socket(PF_INET, SOCK_STREAM, 0);
313 if (listen(fd, TCP_BACKLOG) < 0) {
318 if (getsockname(fd, (struct sockaddr *)&server_addr, &addr_len) < 0) {
319 perror("getsockname");
323 printf("Server listening on %s ...\n", sockname(&server_addr, addr_len));
329 /* Process-based server main loop. Wait for a connection, accept it, fork a
330 * child process to handle the connection, and repeat. Child processes are
331 * reaped in the SIGCHLD handler. */
332 void server_main(int listen_fd)
334 struct sigaction handler;
336 /* Install signal handler for SIGCHLD. */
337 handler.sa_handler = sigchld_handler;
338 sigemptyset(&handler.sa_mask);
339 handler.sa_flags = SA_RESTART;
340 if (sigaction(SIGCHLD, &handler, NULL) < 0) {
346 struct sockaddr_in client_addr;
347 socklen_t addr_len = sizeof(client_addr);
348 int client_fd = accept(listen_fd, (struct sockaddr *)&client_addr,
352 /* Very simple error handling. Exit if something goes wrong. Later,
353 * might want to look into not killing off current connections abruptly
354 * if we encounter an error in the accept(). */
363 printf("Accepted connection from %s ...\n",
364 sockname(&client_addr, addr_len));
370 } else if (pid == 0) {
371 handle_connection(client_fd);
372 printf("Closing connection %s ...\n",
373 sockname(&client_addr, addr_len));
382 /* Print a help message describing command-line options to stdout. */
383 static void usage(char *argv0)
385 printf("Usage: %s [options...]\n"
386 "A simple key-value storage server.\n", argv0);
389 int main(int argc, char *argv[])
393 int display_help = 0, cmdline_error = 0;
396 for (i = 1; i < argc; i++) {
397 if (strcmp(argv[i], "-help") == 0) {
399 } else if (strcmp(argv[i], "-document_root") == 0) {
403 "Error: Argument to -document_root expected.\n");
406 document_root = argv[i];
408 } else if (strcmp(argv[i], "-port") == 0) {
412 "Error: Expected port number after -port.\n");
415 server_port = atoi(argv[i]);
416 if (server_port < 1 || server_port > 65535) {
418 "Error: Port must be between 1 and 65535.\n");
422 } else if (strcmp(argv[i], "-mime_types") == 0) {
426 "Error: Argument to -mime_types expected.\n");
429 mime_types_file = argv[i];
431 } else if (strcmp(argv[i], "-log") == 0) {
435 "Error: Argument to -log expected.\n");
441 fprintf(stderr, "Error: Unrecognized option '%s'\n", argv[i]);
447 /* Display a help message if requested, or let the user know to look at the
448 * help message if there was an error parsing the command line. In either
449 * case, the server never starts. */
453 } else if (cmdline_error) {
454 fprintf(stderr, "Run '%s -help' for a summary of options.\n", argv[0]);