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 #define SIMPLESTORE_PORT 9541
34 /* Maximum number of connections the server will queue waiting for us to call
36 #define TCP_BACKLOG 32
38 #define WHITESPACE " \t\r\n"
41 /* Maximum length of a command that we will accept. */
42 #define MAX_CMD_LEN 4096
44 #define MAX_OBJECT_SIZE (256 << 20)
46 enum command { GET, PUT, LIST, DELETE };
48 void write_data(int fd, const char *buf, size_t len)
51 ssize_t bytes = write(fd, buf, len);
62 /* SIGCHLD handler, used to clean up processes that handle the connections. */
63 static void sigchld_handler(int signal)
68 while ((pid = waitpid(WAIT_ANY, NULL, WNOHANG)) > 0) {
73 if (errno == ECHILD && reaped) {
74 /* Don't print an error for the caes that we successfully cleaned
75 * up after all children. */
82 /* Return a text representation of a socket address. Returns a pointer to a
83 * static buffer so it is non-reentrant. */
84 const char *sockname(struct sockaddr_in *addr, socklen_t len)
87 if (len < sizeof(struct sockaddr_in))
89 if (addr->sin_family != AF_INET)
92 uint32_t ip = ntohl(addr->sin_addr.s_addr);
93 sprintf(buf, "%d.%d.%d.%d:%d",
94 (int)((ip >> 24) & 0xff),
95 (int)((ip >> 16) & 0xff),
96 (int)((ip >> 8) & 0xff),
98 ntohs(addr->sin_port));
103 /* Convert a path from a client to the actual filename used. Returns a string
104 * that must be freed. */
105 char *normalize_path(const char *in)
107 char *out = malloc(2 * strlen(in) + 1);
109 for (i = 0, j = 0; in[i] != '\0'; i++) {
113 } else if (in[i] == '_') {
124 void cmd_get(int fd, char *path, size_t start, ssize_t len)
128 char *response = "-1\n";
129 int file = open(path, O_RDONLY);
131 write_data(fd, response, strlen(response));
136 if (fstat(file, &statbuf) < 0) {
137 write_data(fd, response, strlen(response));
141 size_t datalen = statbuf.st_size;
143 if (start >= datalen) {
146 lseek(file, start, SEEK_SET);
150 if (len > 0 && len < datalen) {
154 sprintf(buf, "%zd\n", datalen);
155 write_data(fd, buf, strlen(buf));
157 while (datalen > 0) {
158 size_t needed = datalen > sizeof(buf) ? sizeof(buf) : datalen;
159 ssize_t bytes = read(file, buf, needed);
160 if (bytes < 0 && errno == EINTR)
163 /* Error reading necessary data, but we already told the client the
164 * file size so pad the data to the client with null bytes. */
165 memset(buf, 0, needed);
168 write_data(fd, buf, bytes);
175 void cmd_put(int fd, char *path, char *buf,
176 size_t object_size, size_t buf_used)
178 while (buf_used < object_size) {
181 bytes = read(fd, buf + buf_used, object_size - buf_used);
192 assert(bytes <= object_size - buf_used);
198 /* printf("Got %zd bytes for object '%s'\n", buf_used, path); */
200 char *response = "-1\n";
201 int file = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0600);
203 write_data(file, buf, object_size);
208 write_data(fd, response, strlen(response));
211 /* The core handler for processing requests from the client. This can be
212 * single-threaded since each connection is handled in a separate process. */
213 void handle_connection(int fd)
215 char cmdbuf[MAX_CMD_LEN];
219 /* Keep reading data until reaching a newline, so that a complete
220 * command can be parsed. */
221 if (buflen == 0 || memchr(cmdbuf, '\n', buflen) == NULL) {
224 if (buflen == MAX_CMD_LEN) {
225 /* Command is too long and thus malformed; close the
230 bytes = read(fd, cmdbuf + buflen, MAX_CMD_LEN - buflen);
240 assert(bytes <= MAX_CMD_LEN - buflen);
246 size_t cmdlen = (char *)memchr(cmdbuf, '\n', buflen) - cmdbuf + 1;
247 cmdbuf[cmdlen - 1] = '\0';
250 char *args[MAX_ARGS];
251 int arg_int[MAX_ARGS];
252 for (token = strtok(cmdbuf, WHITESPACE), arg_count = 0;
254 token = strtok(NULL, WHITESPACE), arg_count++)
256 args[arg_count] = token;
257 arg_int[arg_count] = atoi(token);
263 char *path = normalize_path(args[1]);
265 if (strcmp(args[0], "GET") == 0 && arg_count == 4) {
267 } else if (strcmp(args[0], "PUT") == 0 && arg_count == 3) {
269 } else if (strcmp(args[0], "DELETE") == 0 && arg_count == 2) {
276 memmove(cmdbuf, cmdbuf + cmdlen, buflen - cmdlen);
281 cmd_get(fd, path, arg_int[2], arg_int[3]);
284 size_t object_size = arg_int[2];
285 if (object_size > MAX_OBJECT_SIZE)
287 char *data_buf = malloc(object_size);
288 if (data_buf == NULL)
290 size_t data_buflen = buflen > object_size ? object_size : buflen;
292 memcpy(data_buf, cmdbuf, data_buflen);
293 if (data_buflen < buflen) {
294 memmove(cmdbuf, cmdbuf + data_buflen, buflen - data_buflen);
299 cmd_put(fd, path, data_buf, object_size, data_buflen);
303 //cmd_delete(fd, path);
313 /* Create a listening TCP socket on a new address (we do not use a fixed port).
314 * Return the file descriptor of the listening socket. */
318 struct sockaddr_in server_addr;
319 socklen_t addr_len = sizeof(server_addr);
321 fd = socket(PF_INET, SOCK_STREAM, 0);
328 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
330 server_addr.sin_family = AF_INET;
331 server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
332 server_addr.sin_port = htons(SIMPLESTORE_PORT);
333 if (bind(fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
338 if (listen(fd, TCP_BACKLOG) < 0) {
343 if (getsockname(fd, (struct sockaddr *)&server_addr, &addr_len) < 0) {
344 perror("getsockname");
348 printf("Server listening on %s ...\n", sockname(&server_addr, addr_len));
354 /* Process-based server main loop. Wait for a connection, accept it, fork a
355 * child process to handle the connection, and repeat. Child processes are
356 * reaped in the SIGCHLD handler. */
357 void server_main(int listen_fd)
359 struct sigaction handler;
361 /* Install signal handler for SIGCHLD. */
362 handler.sa_handler = sigchld_handler;
363 sigemptyset(&handler.sa_mask);
364 handler.sa_flags = SA_RESTART;
365 if (sigaction(SIGCHLD, &handler, NULL) < 0) {
371 struct sockaddr_in client_addr;
372 socklen_t addr_len = sizeof(client_addr);
373 int client_fd = accept(listen_fd, (struct sockaddr *)&client_addr,
377 /* Very simple error handling. Exit if something goes wrong. Later,
378 * might want to look into not killing off current connections abruptly
379 * if we encounter an error in the accept(). */
388 printf("Accepted connection from %s ...\n",
389 sockname(&client_addr, addr_len));
395 } else if (pid == 0) {
396 handle_connection(client_fd);
397 printf("Closing connection %s ...\n",
398 sockname(&client_addr, addr_len));
407 /* Print a help message describing command-line options to stdout. */
408 static void usage(char *argv0)
410 printf("Usage: %s [options...]\n"
411 "A simple key-value storage server.\n", argv0);
414 int main(int argc, char *argv[])
418 int display_help = 0, cmdline_error = 0;
421 for (i = 1; i < argc; i++) {
422 if (strcmp(argv[i], "-help") == 0) {
424 } else if (strcmp(argv[i], "-document_root") == 0) {
428 "Error: Argument to -document_root expected.\n");
431 document_root = argv[i];
433 } else if (strcmp(argv[i], "-port") == 0) {
437 "Error: Expected port number after -port.\n");
440 server_port = atoi(argv[i]);
441 if (server_port < 1 || server_port > 65535) {
443 "Error: Port must be between 1 and 65535.\n");
447 } else if (strcmp(argv[i], "-mime_types") == 0) {
451 "Error: Argument to -mime_types expected.\n");
454 mime_types_file = argv[i];
456 } else if (strcmp(argv[i], "-log") == 0) {
460 "Error: Argument to -log expected.\n");
466 fprintf(stderr, "Error: Unrecognized option '%s'\n", argv[i]);
472 /* Display a help message if requested, or let the user know to look at the
473 * help message if there was an error parsing the command line. In either
474 * case, the server never starts. */
478 } else if (cmdline_error) {
479 fprintf(stderr, "Run '%s -help' for a summary of options.\n", argv[0]);