run.c 2.57 KB
#include <poll.h> /* for poll system call and related */
#include <string.h>     /* for memset and stuff */
#include <stdlib.h>     /* for exit */
#include <errno.h>      /* for errno */
#include <unistd.h>
#include <ctype.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "server.h"
#include "socket.h"
#include "logger.h"
#include "signalHandling.h"
#include "interface/class.h"
#include "interface/stream_reader.h"
#include "interface/stream_writer.h"
#include "interface/logger.h"

#undef  MAX
#define MAX(x,y) ((x) > (y) ? (x) : (y))

#include "poll.c"
#include "handle_accept.c"
#include "read.c"

void
serverRun(Server this)
{
    loggerLog(this->logger, LOGGER_INFO, "service started");

	/**
	 * @TODO: actually this is the main loop of my server. When
	 * stuff becomes more complicated it might be feasabible to
	 * split stuff into separate processes. This will definetly
	 * involve some IPC and syncing. Right now as this is actually
	 * only a simple HTTP server implementation we go on with
	 * this single process.
	 * What we can first do to get some processing between read/write
	 * cicles is to use the poll timeout.
	 */
    while (!doShutdown) /* until error or signal  */
    {
		int          events;
		unsigned int i;

		events = serverPoll(this);
		if (doShutdown) break;

		for (i=0; i < this->nfds; i++) {
			int fd = (this->fds)[i].fd;
			int naccs = 10, nreads = 10, nwrites = 10;

			if (0 >= events) break;

			if (0 != ((this->fds)[i].revents & POLLIN) && 0 < nreads) {
				events--;

				/**
				 * handle accept
				 */
				if (this->sock->handle == (this->fds)[i].fd) {
					while(-1 != serverHandleAccept(this) && 0 < naccs) {
						naccs--;

						switch(errno) {
							case EAGAIN:
								loggerLog(this->logger,
										LOGGER_DEBUG,
										"server accept blocks");
								break;

							default:
								loggerLog(this->logger,
										LOGGER_DEBUG,
										"server accept error");
								break;
						}
					}
				}

				/**
				 * handle reads 
				 */
				else {
					nreads--;

					switch (serverRead(this, i)) {
						case -2:
						case -1:
							serverCloseConn(this, i);
							break;

						case 0:
							break;

						default:
							(this->fds)[i].events |= POLLOUT;
					}
				}
			}

			/**
			 * handle writes
			 */
			if (0 != ((this->fds)[i].revents & POLLOUT) && 0 < nwrites) {
				events--;
				nwrites--;

				if (0 >= streamWriterWrite((this->conns)[fd].worker, fd)) {
					serverCloseConn(this, i);
				}

				(this->fds)[i].events &= ~POLLOUT;
			}
		}
    }
}

// vim: set ts=4 sw=4: