|
Server 0.0.1
HTTP/REST server implementation
|
00001 00023 #include <fcntl.h> 00024 #include <unistd.h> 00025 #include <stdlib.h> 00026 00027 #include <openssl/ssl.h> 00028 #include <openssl/err.h> 00029 00030 #include "class.h" 00031 #include "server.h" 00032 #include "socket.h" 00033 #include "logger.h" 00034 00035 #include "utils/memory.h" 00036 00037 00038 void serverCloseConn(Server, unsigned int); 00039 00040 00041 static 00042 int 00043 serverCtor(void * _this, va_list * params) 00044 { 00045 Server this = _this; 00046 in_port_t port; 00047 unsigned int backlog; 00048 int flags; 00049 00050 this->max_fds = sysconf(_SC_OPEN_MAX); 00051 if (this->max_fds <= 10) { // reserve 10 handles for internal use. 00055 return -1; 00056 } 00057 this->max_fds -= 10; 00058 00059 this->logger = va_arg(* params, Logger); 00060 this->worker = va_arg(* params, void *); 00061 port = va_arg(* params, int); 00062 backlog = va_arg(* params, unsigned int); 00063 00064 this->fds = calloc(sizeof(struct pollfd), this->max_fds); 00065 this->conns = calloc(sizeof(struct conns), this->max_fds); 00066 00067 this->sock = new(Sock, this->logger, port); 00068 flags = fcntl(this->sock->handle, F_GETFL, 0); 00069 fcntl(this->sock->handle, F_SETFL, flags | O_NONBLOCK); 00070 00071 this->sockSSL = new(Sock, this->logger, port+1); 00072 flags = fcntl(this->sockSSL->handle, F_GETFL, 0); 00073 fcntl(this->sockSSL->handle, F_SETFL, flags | O_NONBLOCK); 00074 00075 SSL_library_init(); 00076 SSL_load_error_strings(); 00077 this->ctx = SSL_CTX_new(SSLv23_server_method()); 00078 SSL_CTX_use_certificate_file( 00079 this->ctx, 00080 "./certs/server.crt", 00081 SSL_FILETYPE_PEM); 00082 00083 SSL_CTX_use_RSAPrivateKey_file( 00084 this->ctx, 00085 "./certs/server.key", 00086 SSL_FILETYPE_PEM); 00087 00088 socketListen(this->sock, backlog); 00089 socketListen(this->sockSSL, backlog); 00090 00091 (this->fds)[0].fd = this->sock->handle; 00092 (this->fds)[0].events = POLLIN; 00093 (this->fds)[1].fd = this->sockSSL->handle; 00094 (this->fds)[1].events = POLLIN; 00095 this->nfds = 2; 00096 00097 return 0; 00098 } 00099 00100 static 00101 void 00102 serverDtor(void * _this) 00103 { 00104 Server this = _this; 00105 int i; 00106 00107 for (i=0; i<this->nfds; i++) { 00108 if (this->sock->handle != (this->fds)[i].fd && 00109 this->sockSSL->handle != (this->fds)[i].fd) { 00110 serverCloseConn(this, i); 00111 } 00112 } 00113 00114 FREE(this->fds); 00115 FREE(this->conns); 00116 00117 delete(this->sock); 00118 delete(this->sockSSL); 00119 00120 SSL_CTX_free(this->ctx); 00121 ERR_free_strings(); 00122 } 00123 00124 INIT_IFACE(Class, serverCtor, serverDtor, NULL); 00125 CREATE_CLASS(Server, NULL, IFACE(Class)); 00126 00127 // vim: set ts=4 sw=4: