Difference between revisions of "Server.c"

From Organic Design wiki
(process() must work circularly...)
(siCmp() - comparing strings in circular buf)
Line 5: Line 5:
  
 
#define svrDELAY 0        // normal operation is 0 for no delay
 
#define svrDELAY 0        // normal operation is 0 for no delay
#define svrPAKSIZE 10      // keep packet-size small for non-multithreaded design
+
#define svrPAKSIZE 0x10    // keep packet-size 2^n and small for non-multithreaded design
#define svrBUFSIZE 100    // dictates max message size (make int*PAKSIZE)
+
#define svrBUFSIZE 0xff    // dictates max message size-1 (2^n-1 because used as & mask)
 
#define svrMAXCLIENTS 1000 // used by listen()
 
#define svrMAXCLIENTS 1000 // used by listen()
 
#ifndef __WIN32__
 
#ifndef __WIN32__
Line 18: Line 18:
 
unsigned long int sockopt_on;
 
unsigned long int sockopt_on;
 
int sock;
 
int sock;
 
// struct for a stream-node's state to point to
 
typedef struct siStruct {
 
int fd, iPtr, iMsg, iLen, oPtr;
 
char *iBuf, *oBuf;
 
} streamInfo;
 
  
 
// Function prototypes
 
// Function prototypes
Line 33: Line 27:
  
  
 +
// Struct for a stream-node's state to point to
 +
typedef struct siStruct {
 +
int fd, iPtr, iMsg, iLen, oPtr;
 +
char *iBuf, *oBuf;
 +
} streamInfo;
 +
 +
// iBuf is circular, so best to use a wrapping cmp instead of copying/moving characters
 +
// - returns true if string pointed to by str is same as that in iBuf at offset i
 +
int siCmp(char *str, int i, streamInfo *info) {
 +
char *buf = info->iBuf - 1;
 +
while(*str) if (*str++ != buf[i=++i&svrBUFSIZE]) return 0;
 +
return 1;
 +
}
 +
 +
// Initialise socket listening on specified port
 
int server_init() {
 
int server_init() {
  
Line 110: Line 119:
 
newsi->fd = fd;
 
newsi->fd = fd;
 
newsi->iBuf = malloc(svrBUFSIZE+1);
 
newsi->iBuf = malloc(svrBUFSIZE+1);
newsi->iBuf[svrBUFSIZE] = '\0';
+
newsi->oBuf = malloc(svrBUFSIZE+1);
newsi->oBuf = malloc(svrBUFSIZE);
 
 
newsi->iPtr = newsi->iMsg = newsi->oPtr = 0;
 
newsi->iPtr = newsi->iMsg = newsi->oPtr = 0;
 
node n = nodeGetValue(nodeCLIENTS,nodeLOOP);
 
node n = nodeGetValue(nodeCLIENTS,nodeLOOP);
Line 140: Line 148:
 
printf("i=%d\n",i);
 
printf("i=%d\n",i);
 
// Scan new packet for completed messages and process each
 
// Scan new packet for completed messages and process each
// NOTE: problem if \r\n\r\n crosses a packet-boundary
+
while (i--) if (siCmp("\r\n\r\n",iBuf+info->iPtr++,info)) {
while (i--) if (strncmp("\r\n\r\n",iBuf+info->iPtr++,4) == 0) {
 
 
process(info);
 
process(info);
info->iMsg = (3+info->iPtr)%svrBUFSIZE; // start of next msg
+
info->iMsg = (info->iPtr+3) & svrBUFSIZE; // start of next msg
 
}
 
}
 +
 
// Read next packet to same location if msg too big to preserve start
 
// Read next packet to same location if msg too big to preserve start
 
if (info->iPtr == info->iMsg) {
 
if (info->iPtr == info->iMsg) {
Line 150: Line 158:
 
info->iPtr -= svrPAKSIZE;
 
info->iPtr -= svrPAKSIZE;
 
}
 
}
info->iPtr %= svrBUFSIZE; // iBuf is circular
+
 +
info->iPtr &= svrBUFSIZE; // Wrap iBuf
 
}
 
}
 
else if (i == 0) {
 
else if (i == 0) {
Line 177: Line 186:
  
  
// Process message and clear it from the input buffer
+
// Process message in iBuf which should be a complete HTTP GET request
 
void process(streamInfo *info) {
 
void process(streamInfo *info) {
 
char *msg = info->iMsg;
 
char *msg = info->iMsg;
 
printf("\n\nCONTENT:\n%s\n\n",msg);
 
printf("\n\nCONTENT:\n%s\n\n",msg);
 
+
if (siCmp("GET /",msg,info)) {
// Handle GET requests
 
if (strncmp(msg,"GET /",5)==0) {
 
  
 
// Extract request path & query-string
 
// Extract request path & query-string
// NOTE: Has to work circularly, incl. strcmp
+
char *end = msg += 4;
 
+
while(*++end > ' ');
int end;
 
//for (end = 4+info->Msg
 
char *end = msg+=4;
 
while(*++end>' ');
 
 
*end = '\0';
 
*end = '\0';
 
printf("Request:\"%s\"\n",msg);
 
printf("Request:\"%s\"\n",msg);
  
 
// Exit if /stop requested
 
// Exit if /stop requested
if (strncmp(msg,"/stop",5)==0) {
+
if (siCmp("/stop",msg,info)) {
 
logAdd("/stop requested, stopping.");
 
logAdd("/stop requested, stopping.");
 
exit(EXIT_SUCCESS);
 
exit(EXIT_SUCCESS);
Line 205: Line 208:
 
}
 
}
 
else logAdd("Peerd only supports GET requests currently!");
 
else logAdd("Peerd only supports GET requests currently!");
info->iPtr = 0; // clear input buffer for this stream
 
 
}
 
}

Revision as of 23:36, 1 August 2006

// This article and all its includes are licenced under LGPL // GPL: http://www.gnu.org/copyleft/lesser.html // SRC: http://www.organicdesign.co.nz/server.c


  1. define svrDELAY 0 // normal operation is 0 for no delay
  2. define svrPAKSIZE 0x10 // keep packet-size 2^n and small for non-multithreaded design
  3. define svrBUFSIZE 0xff // dictates max message size-1 (2^n-1 because used as & mask)
  4. define svrMAXCLIENTS 1000 // used by listen()
  5. ifndef __WIN32__
  6. define WSAGetLastError() errno
  7. endif

// Socket structures and variables struct sockaddr_in addr; struct timeval to; fd_set fdset; unsigned long int sockopt_on; int sock;

// Function prototypes //void server(); // declared earlier in nodalHusk since called in root loop //void client(); int server_init(); int server_exit(); int nonblocking(int socket);


// Struct for a stream-node's state to point to typedef struct siStruct { int fd, iPtr, iMsg, iLen, oPtr; char *iBuf, *oBuf; } streamInfo;

// iBuf is circular, so best to use a wrapping cmp instead of copying/moving characters // - returns true if string pointed to by str is same as that in iBuf at offset i int siCmp(char *str, int i, streamInfo *info) { char *buf = info->iBuf - 1; while(*str) if (*str++ != buf[i=++i&svrBUFSIZE]) return 0; return 1; }

// Initialise socket listening on specified port int server_init() {

#if __WIN32__ WSADATA wsaData; if (WSAStartup(MAKEWORD(2,0),&wsaData)!=0) logErr("WSAStartup() failed!"); #endif

// Set up structures for socket & select sockopt_on = 1; int szAddr = sizeof(struct sockaddr_in); memset((char*)&addr, 0, szAddr); // zero the struct addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(INADDR_ANY); errno = 0;

// struct for a stream-node's state to point to typedef struct siStruct { int fd, inptr, outptr; char *inbuf, *outbuf; } streamInfo;

// Do the usual socket polava: create,options,bind,listen if ((sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP))<0) logErrNum("socket() failed returning %d",WSAGetLastError()); if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char*)&sockopt_on,sizeof(int))<0) logErr("setsockopt() failed!"); if (bind(nonblocking(sock),(struct sockaddr*)&addr,szAddr)<0) logErr("bind() failed!"); if (listen(sock,svrMAXCLIENTS)<0) logErr("listen() failed!"); if (errno) logAdd("Server failed to start!");

if (errno == 0) { char *msg = malloc(100); sprintf(msg,"Daemon \"%s\" started successfully and serving on port %d.",peer,port); logAdd(msg); free(msg); } return errno; }


// Perform any cleanup for socket int server_exit() { // todo: close streams and free buffers etc #if __WIN32__ WSACleanup(); #endif return WSAGetLastError(); }


// make the passed socket non-blocking so accept() returns straight away for multiplexed model // - if no incoming requests, returns EAGAIN or EWOULDBLOCK state int nonblocking(int socket) { #if __WIN32__ ioctlsocket(socket,FIONBIO,&sockopt_on); #else fcntl(socket,F_SETFL,fcntl(socket,F_GETFL)|O_NONBLOCK); #endif return socket; }


// Function called by each stream-node in network's reduction loop // - there is also a streams-container node containing zero or more stream nodes void server() { FD_ZERO(&fdset); FD_SET(sock,&fdset); to.tv_sec = to.tv_usec = svrDELAY; if (select(sock+1,&fdset,NULL,NULL,&to)>0) { // New connection request, accpet and create new stream-node int fd = nonblocking(accept(sock,NULL,NULL)); if (fd>0) { printf("New connection: Stream%d.\n",fd); streamInfo *newsi = malloc(sizeof(streamInfo)); newsi->fd = fd; newsi->iBuf = malloc(svrBUFSIZE+1); newsi->oBuf = malloc(svrBUFSIZE+1); newsi->iPtr = newsi->iMsg = newsi->oPtr = 0; node n = nodeGetValue(nodeCLIENTS,nodeLOOP); n = nodeLoopInsert(n,nodeNULL); nodeSetValue(nodeCLIENTS,nodeLOOP,n); nodeSetValue(n,nodeCODE,nodeTRUE); *nodeState(n,nodeNULL) = &client; *nodeState(n,nodeSTREAMINFO) = newsi; } else logErr("accept(): failed!"); } }


// Each of the stream nodes points to this function in its State void client() { // Get the info for this stream ready for reading/writing a packet if necessary streamInfo *info = *nodeState(this, nodeSTREAMINFO); char *iBuf = info->iBuf, *oBuf = info->oBuf; int i,fd = info->fd;

// If any data to recieve, read a packet FD_ZERO(&fdset); FD_SET(fd,&fdset); to.tv_sec = to.tv_usec = svrDELAY; if (select(fd+1,&fdset,NULL,NULL,&to)>0) { if ((i = recv(fd,iBuf+info->iPtr,svrPAKSIZE,0)) > 0) { printf("i=%d\n",i); // Scan new packet for completed messages and process each while (i--) if (siCmp("\r\n\r\n",iBuf+info->iPtr++,info)) { process(info); info->iMsg = (info->iPtr+3) & svrBUFSIZE; // start of next msg }

// Read next packet to same location if msg too big to preserve start if (info->iPtr == info->iMsg) { logErr("Buffer overrun, clipping."); info->iPtr -= svrPAKSIZE; }

info->iPtr &= svrBUFSIZE; // Wrap iBuf } else if (i == 0) { // zero bytes to read, do orderly termination printf("Stream%d closed.\n",fd); //nodeLoopRemove(this); // NOTE: reduction not handling PREV free(iBuf); free(oBuf); free(info); } else logErrNum("recv() failed returning %d",WSAGetLastError()); }

return; // Data to send? FD_ZERO(&fdset); FD_SET(fd,&fdset); to.tv_sec = to.tv_usec = svrDELAY; if (select(fd+1,NULL,&fdset,NULL,&to)>0) { // write a packet from outbuf //int len = svrPAKSIZE; // or less //if (send(fd,oBuf+oPtr,len,0)<0) logErr("send() failed!"); }

}


// Process message in iBuf which should be a complete HTTP GET request void process(streamInfo *info) { char *msg = info->iMsg; printf("\n\nCONTENT:\n%s\n\n",msg); if (siCmp("GET /",msg,info)) {

// Extract request path & query-string char *end = msg += 4; while(*++end > ' '); *end = '\0'; printf("Request:\"%s\"\n",msg);

// Exit if /stop requested if (siCmp("/stop",msg,info)) { logAdd("/stop requested, stopping."); exit(EXIT_SUCCESS); }

// Send test response back send(info->fd,"HTTP/1.1 200 OK\r\nDate: Mon, 31 Jul 2006 22:27:14 NZST\r\nContent-Type: text/html\r\nConnection: keep-alive\r\nContent-Length: 9\r\n\r\nStink eh?",134,0); } else logAdd("Peerd only supports GET requests currently!"); }