buggy code
[webserver.git] / webserver.c
index 825b847f728e9f3aec82dc5db4e352559404ee3e..9861836fc5abcdcff7b1649f27cc8003e93ae2b5 100644 (file)
@@ -105,9 +105,50 @@ int main (int argc, char *argv[])
         VERBOSE (ERROR, fprintf (stderr, "Can't open listening socket\n"));
         return 1;
     }
-
     VERBOSE (INFO, fprintf (stdout, "Listening socket on port %d\n", port));
-    sleep (20);
+
+    /* main loop */
+    while (1) {
+        int connection = accept_incoming_connection (sock);
+        if ((connection < 0) && (errno == EAGAIN)) {
+            accept_nonblock_ok = 1;
+        }
+        if (connection < 0) {
+            sleep (1);
+            continue;
+        }
+
+        VERBOSE (DEBUG, fprintf (stdout, "Server connected, waiting for data\n"));
+
+        while (1) {
+            unsigned char data[BUFFER_SIZE] = {0};
+            int len = 0;
+
+            len = receive_data (connection, data, size (data));
+            if (len == 0) {
+                // nonblocking connection
+                sleep (1);
+                continue;
+            }
+            if (len < 0) {
+                VERBOSE (WARNING, fprintf (stdout, "Connection closed by peer\n"));
+                close_connection (connection);
+                break;
+            }
+
+            // processing
+            
+            len = send_data (connection, data, size (data));
+            if (len < 0) {
+                VERBOSE (WARNING, fprintf (stdout, "Connection closed by peer\n"));
+                close_connection (connection);
+                break;
+            }
+
+            /* sleep so that we go trhough remaining data in receive buffer */
+            usleep (1e5);
+        }
+    }
 
     VERBOSE (DEBUG, fprintf (stdout, "Closing socket\n"));
     close_listening_socket (sock);