add signal management
[webserver.git] / server.c
1 /* depend: */
2 /* cflags: */
3 /* linker: color.o debug.o */
4
5 #include <assert.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #ifdef _WIN32 /* Windows */
9 #include <winsock2.h>
10 #include <ws2tcpip.h>
11 #else /* Posix */
12 #include <errno.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <netinet/ip.h>
16 #include <netinet/tcp.h>
17 //#include <sys/types.h>
18 //#include <sys/socket.h>
19 #endif
20
21 #include "debug.h"
22
23 #include "server.h"
24
25 /* types */
26
27 #ifdef _WIN32 /* Windows */
28 typedef SOCKET socket_t;
29 #define PF_INET AF_INET
30 #define ERRNO (WSAGetLastError ())
31 #else /* Posix */
32 typedef int socket_t;
33 #define closesocket close
34 #define ERRNO errno
35 #define SOCKET_ERROR -1
36 #endif
37
38 /* constants */
39
40 #define BUFFER_SIZE 4096
41
42 /* macros */
43
44 /* gobal variables */
45
46 /* open listening socket */
47
48 socket_t open_listening_socket (int port)
49 {
50 #ifdef _WIN32 /* Windows */
51 WSADATA WSAData;
52 WSAStartup (MAKEWORD(2,0), &WSAData);
53 assert (INVALID_SOCKET == (socket_t)-1);
54 assert (SOCKET_ERROR == -1);
55 #endif
56
57 VERBOSE (DEBUG, fprintf (stdout, "Opening socket\n"));
58 socket_t sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
59 if (sock == INVALID_SOCKET) {
60 return -1;
61 }
62
63 struct sockaddr_in addr = {0};
64 addr.sin_family = PF_INET;
65 addr.sin_port = htons (port);
66 addr.sin_addr.s_addr = htonl (INADDR_ANY);
67
68 VERBOSE (DEBUG, fprintf (stdout, "Binding socket\n"));
69 int rc = bind (sock, (struct sockaddr *)&addr, sizeof (addr));
70 if (rc == SOCKET_ERROR) {
71 VERBOSE (ERROR, fprintf (stderr, "error: %d\n", ERRNO));
72 rc = closesocket (sock);
73 if (rc == SOCKET_ERROR) {
74 VERBOSE (ERROR, fprintf (stderr, "error: %d\n", ERRNO));
75 }
76 return -1;
77 }
78
79 VERBOSE (DEBUG, fprintf (stdout, "Configuring socket\n"));
80 #ifndef _WIN32 /* Posix */
81 fcntl (sock, F_SETFL, O_NONBLOCK);
82 #endif
83 int val = 1;
84 rc = setsockopt (sock, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof (val));
85 if (rc < 0) {
86 VERBOSE (ERROR, fprintf (stderr, "%s\n", "setsockopt/TCP_NODELAY"));
87 closesocket (sock);
88 if (rc == SOCKET_ERROR) {
89 VERBOSE (ERROR, fprintf (stderr, "error: %d\n", ERRNO));
90 }
91 return -1;
92 }
93
94 return sock;
95 }
96
97 /* close listening socket */
98 void close_listening_socket (socket_t sock)
99 {
100 int rc = closesocket (sock);
101 if (rc == SOCKET_ERROR) {
102 VERBOSE (ERROR, fprintf (stderr, "error: %d\n", ERRNO));
103 }
104 #ifdef _WIN32 /* Windows */
105 WSACleanup ();
106 #endif
107 }
108
109 /* vim: set ts=4 sw=4 et: */
110
111 /* vim: set ts=4 sw=4 et: */