Created
November 12, 2012 11:21
-
-
Save maknoll/4058808 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.c | |
// kun | |
// | |
// Created by Martin Knoll on 17.10.12. | |
// Copyright (c) 2012 Martin Knoll. All rights reserved. | |
// | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <err.h> | |
#include <sys/socket.h> | |
#include <netdb.h> | |
#include <string.h> | |
#include <fcntl.h> | |
#include <signal.h> | |
#include "parser.h" | |
#define BUFFERSIZE 1452 | |
int socket_bind_listen(char *port) | |
{ | |
struct addrinfo hints, *info; | |
memset(&hints, 0, sizeof(hints)); | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_flags = AI_PASSIVE; | |
int error = getaddrinfo(NULL, port, &hints, &info); | |
if (error) | |
{ | |
errx(1, "%s", gai_strerror(error)); | |
} | |
int sock = socket(info->ai_family, info->ai_socktype, 0); | |
if (bind(sock, info->ai_addr, info->ai_addrlen)) | |
return -1; | |
listen(sock, 4); | |
freeaddrinfo(info); | |
return sock; | |
} | |
int request_handler(int client) { | |
char buffer[BUFFERSIZE]; | |
long bytes_read; | |
bytes_read = read(client, &buffer, BUFFERSIZE); | |
request_t req; | |
char * input = buffer; | |
parse(&input, &req); | |
printf("%s\n", req.method); | |
printf("%s\n", req.resource); | |
printf("%s\n", req.version); | |
char path[128] = "."; | |
strcat(path, req.resource); | |
int file = open(path, O_RDONLY); | |
if (file < 0) { | |
perror("open"); | |
return EXIT_FAILURE; | |
} | |
long long len = 0; | |
int send = sendfile(file, client, 0, &len, NULL, 0); | |
if (send < 0) { | |
perror("sendfile"); | |
return EXIT_FAILURE; | |
} | |
close(file); | |
close(client); | |
return EXIT_SUCCESS; | |
} | |
int main(int argc, const char * argv[]) | |
{ | |
struct sigaction act; | |
memset(&act, 0, sizeof(struct sigaction)); | |
act.sa_handler = SIG_IGN; | |
sigaction(SIGCHLD, &act, NULL); | |
int sock = socket_bind_listen("8080"); | |
if (sock <= 0) | |
{ | |
perror("socket_bind_listen"); | |
return -1; | |
} | |
for (int client; 1; client = accept(sock, NULL, NULL)) { | |
if (client < 0) { | |
perror("client"); | |
return EXIT_FAILURE; | |
} | |
pid_t pid = fork(); | |
if (pid < 0) { | |
return EXIT_FAILURE; | |
} | |
if (0 == pid) { | |
close(sock); | |
return request_handler(client); | |
} | |
close(client); | |
} | |
close(sock); | |
return EXIT_FAILURE; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment