Exemple #1
0
/*
	Server side.  Accept a new socket connection off our listen socket.  
	This code is not specific to SSL.
*/
SOCKET socketAccept(SOCKET listenfd, int *err)
{
	struct sockaddr_in	addr;
	SOCKET				fd;
	int					len;
/*
	Wait(blocking)/poll(non-blocking) for an incoming connection
*/
	len = sizeof(addr);
	if ((fd = accept(listenfd, (struct sockaddr *)&addr, &len)) 
			== INVALID_SOCKET) {
		*err = getSocketError();
		if (*err != WOULD_BLOCK) {
			fprintf(stderr, "Error %d accepting new socket\n", *err);
		}
		return INVALID_SOCKET;
	}
/*
	fd is the newly accepted socket. Disable Nagle on this socket.
	Set blocking mode as default
*/
/*	fprintf(stdout, "Connection received from %d.%d.%d.%d\n", 
		addr.sin_addr.S_un.S_un_b.s_b1,
		addr.sin_addr.S_un.S_un_b.s_b2,
		addr.sin_addr.S_un.S_un_b.s_b3,
		addr.sin_addr.S_un.S_un_b.s_b4);
*/

	nvram_set("ssl_client_ip",inet_ntoa(addr.sin_addr));
	setSocketNodelay(fd);
	setSocketBlock(fd);
	return fd;
}
SOCKET socketConnect(char *ip, short port, int *err)
{
  struct sockaddr_in addr;
  SOCKET fd;
  int	rc;
  
  struct hostent *hp;
  
  if(!(hp = gethostbyname(ip))) {
    fprintf(stderr, "Host not found %s\n",ip);
    return INVALID_SOCKET;
  }
  
  memset(&addr,0,sizeof(addr));
  addr.sin_addr=*(struct in_addr *)hp->h_addr_list[0];
  addr.sin_family=AF_INET;
  addr.sin_port=htons(port);
  
  if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { 
    fprintf(stderr, "Error creating socket\n");
    *err = getSocketError();
    return INVALID_SOCKET;
  }

  fcntl(fd, F_SETFD, FD_CLOEXEC);
  rc = 1;
  setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&rc, sizeof(rc));
  setSocketNodelay(fd);
  setSocketBlock(fd);
  
  rc = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
#if WIN
  if (rc != 0) 
#else
  if (rc < 0) 
#endif
  {
    *err = getSocketError();
    perror("connect");
    return INVALID_SOCKET;
  }

  return fd;
}
SOCKET socketAccept(SOCKET listenfd, int *err)
{
  struct sockaddr_in	addr;
  SOCKET	fd;
  int	len;

  len = sizeof(addr);
  if ((fd = accept(listenfd, (struct sockaddr *)&addr, &len)) 
      == INVALID_SOCKET) {
    *err = getSocketError();
    if (*err != WOULD_BLOCK) {
      fprintf(stderr, "Error %d accepting new socket\n", *err);
    }
    return INVALID_SOCKET;
  }
  setSocketNodelay(fd);
  setSocketBlock(fd);
  return fd;
}
Exemple #4
0
int main(int argc, char **argv)
#endif
{
	sslConn_t		*cp;
	sslKeys_t		*keys;
	SOCKET			listenfd, fd;
	WSADATA			wsaData;
	unsigned char	buf[1024];
	unsigned char	*response, *c;
	int				responseHdrLen, acceptAgain, flags;
	int				bytes, status, quit, again, rc, err;
#if USE_MEM_CERTS
	unsigned char	*servBin, *servKeyBin, *caBin; 
	int				servBinLen, caBinLen, servKeyBinLen;
#endif

	cp = NULL;
/*
	Initialize Windows sockets (no-op on other platforms)
*/
	WSAStartup(MAKEWORD(1,1), &wsaData);
/*
	Initialize the MatrixSSL Library, and read in the public key (certificate)
	and private key.
*/
	if (matrixSslOpen() < 0) {
		fprintf(stderr, "matrixSslOpen failed, exiting...");
	}

#if USE_MEM_CERTS
/*
	Example of DER binary certs for matrixSslReadKeysMem
*/
	getFileBin("certSrv.der", &servBin, &servBinLen);
	getFileBin("privkeySrv.der", &servKeyBin, &servKeyBinLen);
	getFileBin("CACertCln.der", &caBin, &caBinLen);

	matrixSslReadKeysMem(&keys, servBin, servBinLen,
		servKeyBin, servKeyBinLen, caBin, caBinLen); 

	free(servBin);
	free(servKeyBin);
	free(caBin);
#else 
/*
	Standard PEM files
*/
	if (matrixSslReadKeys(&keys, certfile, keyfile, NULL, NULL) < 0)  {
		fprintf(stderr, "Error reading or parsing %s or %s.\n", 
			certfile, keyfile);
		goto promptAndExit;
	}
#endif /* USE_MEM_CERTS */
	fprintf(stdout, 
		"Run httpsClient or type https://127.0.0.1:%d into your local Web browser.\n",
		HTTPS_PORT);
/*
	Create the listen socket
*/
	if ((listenfd = socketListen(HTTPS_PORT, &err)) == INVALID_SOCKET) {
		fprintf(stderr, "Cannot listen on port %d\n", HTTPS_PORT);
		goto promptAndExit;
	}
/*
	Set blocking or not on the listen socket
*/
	setSocketBlock(listenfd);
/*
	Loop control initalization
*/
	quit = 0;
	again = 0;
	flags = 0;

	acceptAgain = 1;
/*
	Main connection loop
*/
	while (!quit) {

		if (acceptAgain) {
/*
			sslAccept creates a new server session
*/
			/* TODO - deadlock on blocking socket accept.  Should disable blocking here */
			if ((fd = socketAccept(listenfd, &err)) == INVALID_SOCKET) {
				fprintf(stdout, "Error accepting connection: %d\n", err);
				continue;
			}
			if ((rc = sslAccept(&cp, fd, keys, NULL, flags)) != 0) {
				socketShutdown(fd);
				continue;
			}

			flags = 0;
			acceptAgain = 0;
		}
/*
		Read response
		< 0 return indicates an error.
		0 return indicates an EOF or CLOSE_NOTIFY in this situation
		> 0 indicates that some bytes were read.  Keep reading until we see
		the /r/n/r/n from the GET request.  We don't actually parse the request,
		we just echo it back.
*/
		c = buf;
readMore:
		if ((rc = sslRead(cp, c, sizeof(buf) - (int)(c - buf), &status)) > 0) {
			c += rc;
			if (c - buf < 4 || memcmp(c - 4, "\r\n\r\n", 4) != 0) {
				goto readMore;
			}
		} else {
			if (rc < 0) {
				fprintf(stdout, "sslRead error.  dropping connection.\n");
			}
			if (rc < 0 || status == SSLSOCKET_EOF ||
					status == SSLSOCKET_CLOSE_NOTIFY) {
				socketShutdown(cp->fd);
				sslFreeConnection(&cp);
				acceptAgain = 1;
				continue;
			}
			goto readMore;
		}
/*
		Done reading.  If the incoming data starts with the quitString,
		quit the application after this request
*/
		if (memcmp(buf, quitString, min(c - buf, 
				(int)strlen(quitString))) == 0) {
			quit++;
			fprintf(stdout, "Q");
		}
/*
		If the incoming data starts with the againString,
		we are getting a pipeline request on the same session.  Don't
		close and wait for new connection in this case.
*/
		if (memcmp(buf, againString,
				min(c - buf, (int)strlen(againString))) == 0) {
			again++;
			fprintf(stdout, "A");
		} else {
			fprintf(stdout, "R");
			again = 0;
		}
/*
		Copy the canned response header and decoded data from socket as the
		response (reflector)
*/
		responseHdrLen = (int)strlen(responseHdr);
		bytes = responseHdrLen + (int)(c - buf);
		response = malloc(bytes);
		memcpy(response, responseHdr, responseHdrLen);
		memcpy(response + responseHdrLen, buf, c - buf); 
/*
		Send response.
		< 0 return indicates an error.
		0 return indicates not all data was sent and we must retry
		> 0 indicates that all requested bytes were sent
*/
writeMore:
		rc = sslWrite(cp, response, bytes, &status);
		if (rc < 0) {
			free(response);
			fprintf(stdout, "Internal sslWrite error\n");
			socketShutdown(cp->fd);
			sslFreeConnection(&cp);
			continue;
		} else if (rc == 0) {
			goto writeMore;
		}
		free(response);
/*
		If we saw an /again request, loop up and process another pipelined
		HTTP request.  The /again request is supported in the httpsClient
		example code.
*/
		if (again) {
			continue;
		}
/*
		Send a closure alert for clean shutdown of remote SSL connection
		This is for good form, some implementations just close the socket
*/
		sslWriteClosureAlert(cp);
/*
		Close the socket and wait for next connection (new session)
*/
		socketShutdown(cp->fd);
		sslFreeConnection(&cp);
		acceptAgain = 1;
	}
/*
	Close listening socket, free remaining items
*/
	if (cp && cp->ssl) {
		socketShutdown(cp->fd);
		sslFreeConnection(&cp);
	}
	socketShutdown(listenfd);

	matrixSslFreeKeys(keys);
	matrixSslClose();
	WSACleanup();
promptAndExit:
	fprintf(stdout, "\n\nPress return to exit...\n");
	getchar();
	return 0;
}
Exemple #5
0
/*
	An example socket sslRead implementation that handles the ssl handshake
	transparently.  Caller passes in allocated buf and length. 
	
	Return codes are as follows:

	-1 return code is an error.  If a socket level error, error code is
		contained in status parameter.  If using a non-blocking socket
		implementation the caller should check for non-fatal errors such as
		WOULD_BLOCK before closing the connection.  A zero value
		in status indicates an error with this routine.  

	A positive integer return code is the number of bytes successfully read
		into the supplied buffer.  User can call sslRead again on the updated
		buffer is there is more to be read.

	0 return code indicates the read was successful, but there was no data
		to be returned.  If status is set to zero, this is a case internal
		to the sslAccept and sslConnect functions that a handshake
		message has been exchanged.  If status is set to SOCKET_EOF
		the connection has been closed by the other side.

*/
int sslRead(sslConn_t *cp, char *buf, int len, int *status)
{
	int				bytes, rc, remaining;
	unsigned char	error, alertLevel, alertDescription, performRead;

	*status = 0;

	if (cp->ssl == NULL || len <= 0) {
		return -1;
	}
/*
	If inbuf is valid, then we have previously decoded data that must be
	returned, return as much as possible.  Once all buffered data is
	returned, free the inbuf.
*/
	if (cp->inbuf.buf) {
		if (cp->inbuf.start < cp->inbuf.end) {
			remaining = (int)(cp->inbuf.end - cp->inbuf.start);
			bytes = (int)min(len, remaining);
			memcpy(buf, cp->inbuf.start, bytes);
			cp->inbuf.start += bytes;
			return bytes;
		}
		free(cp->inbuf.buf);
		cp->inbuf.buf = NULL;
	}
/*
	Pack the buffered socket data (if any) so that start is at zero.
*/
	if (cp->insock.buf < cp->insock.start) {
		if (cp->insock.start == cp->insock.end) {
			cp->insock.start = cp->insock.end = cp->insock.buf;
		} else {
			memmove(cp->insock.buf, cp->insock.start, cp->insock.end - cp->insock.start);
			cp->insock.end -= (cp->insock.start - cp->insock.buf);
			cp->insock.start = cp->insock.buf;
		}
	}
/*
	Read up to as many bytes as there are remaining in the buffer.  We could
	Have encrypted data already cached in conn->insock, but might as well read more
	if we can.
*/
	performRead = 0;
readMore:
	if (cp->insock.end == cp->insock.start || performRead) {
		performRead = 1;
		bytes = recv(cp->fd, (char *)cp->insock.end, 
			(int)((cp->insock.buf + cp->insock.size) - cp->insock.end), MSG_NOSIGNAL);
		if (bytes == SOCKET_ERROR) {
			*status = getSocketError();
			return -1;
		}
		if (bytes == 0) {
			*status = SSLSOCKET_EOF;
			return 0;
		}
		cp->insock.end += bytes;
	}
/*
	Define a temporary sslBuf
*/
	cp->inbuf.start = cp->inbuf.end = cp->inbuf.buf = malloc(len);
	cp->inbuf.size = len;
/*
	Decode the data we just read from the socket
*/
decodeMore:
	error = 0;
	alertLevel = 0;
	alertDescription = 0;

	rc = matrixSslDecode(cp->ssl, &cp->insock, &cp->inbuf, &error, &alertLevel, 
		&alertDescription);
	switch (rc) {
/*
	Successfully decoded a record that did not return data or require a response.
*/
	case SSL_SUCCESS:
		return 0;
/*
	Successfully decoded an application data record, and placed in tmp buf
*/
	case SSL_PROCESS_DATA:
/*
		Copy as much as we can from the temp buffer into the caller's buffer
		and leave the remainder in conn->inbuf until the next call to read
		It is possible that len > data in buffer if the encoded record
		was longer than len, but the decoded record isn't!
*/
		rc = (int)(cp->inbuf.end - cp->inbuf.start);
		rc = min(rc, len);
		memcpy(buf, cp->inbuf.start, rc);
		cp->inbuf.start += rc;
		return rc;
/*
	We've decoded a record that requires a response into tmp
	If there is no data to be flushed in the out buffer, we can write out
	the contents of the tmp buffer.  Otherwise, we need to append the data 
	to the outgoing data buffer and flush it out.
*/
	case SSL_SEND_RESPONSE:
		bytes = send(cp->fd, (char *)cp->inbuf.start, 
			(int)(cp->inbuf.end - cp->inbuf.start), MSG_NOSIGNAL);
		if (bytes == SOCKET_ERROR) {
			*status = getSocketError();
			if (*status != WOULD_BLOCK) {
				fprintf(stdout, "Socket send error:  %d\n", *status);
				goto readError;
			}
			*status = 0;
		}
		cp->inbuf.start += bytes;
		if (cp->inbuf.start < cp->inbuf.end) {
/*
			This must be a non-blocking socket since it didn't all get sent
			out and there was no error.  We want to finish the send here
			simply because we are likely in the SSL handshake.
*/
			setSocketBlock(cp->fd);
			bytes = send(cp->fd, (char *)cp->inbuf.start, 
				(int)(cp->inbuf.end - cp->inbuf.start), MSG_NOSIGNAL);
			if (bytes == SOCKET_ERROR) {
				*status = getSocketError();
				goto readError;
			}
			cp->inbuf.start += bytes;
			socketAssert(cp->inbuf.start == cp->inbuf.end);
/*
			Can safely set back to non-blocking because we wouldn't
			have got here if this socket wasn't non-blocking to begin with.
*/
			setSocketNonblock(cp->fd);
		}
		cp->inbuf.start = cp->inbuf.end = cp->inbuf.buf;
		return 0;
/*
	There was an error decoding the data, or encoding the out buffer.
	There may be a response data in the out buffer, so try to send.
	We try a single hail-mary send of the data, and then close the socket.
	Since we're closing on error, we don't worry too much about a clean flush.
*/
	case SSL_ERROR:
		fprintf(stderr, "SSL: Closing on protocol error %d\n", error);
		if (cp->inbuf.start < cp->inbuf.end) {
			setSocketNonblock(cp->fd);
			bytes = send(cp->fd, (char *)cp->inbuf.start, 
				(int)(cp->inbuf.end - cp->inbuf.start), MSG_NOSIGNAL);
		}
		goto readError;
/*
	We've decoded an alert.  The level and description passed into
	matrixSslDecode are filled in with the specifics.
*/
	case SSL_ALERT:
		if (alertDescription == SSL_ALERT_CLOSE_NOTIFY) {
			*status = SSLSOCKET_CLOSE_NOTIFY;
			goto readZero;
		}
		fprintf(stderr, "SSL: Closing on client alert %d: %d\n",
			alertLevel, alertDescription);
		goto readError;
/*
	We have a partial record, we need to read more data off the socket.
	If we have a completely full conn->insock buffer, we'll need to grow it
	here so that we CAN read more data when called the next time.
*/
	case SSL_PARTIAL:
		if (cp->insock.start == cp->insock.buf && cp->insock.end == 
				(cp->insock.buf + cp->insock.size)) {
			if (cp->insock.size > SSL_MAX_BUF_SIZE) {
				goto readError;
			}
			cp->insock.size *= 2;
			cp->insock.start = cp->insock.buf = 
				(unsigned char *)realloc(cp->insock.buf, cp->insock.size);
			cp->insock.end = cp->insock.buf + (cp->insock.size / 2);
		}
		if (!performRead) {
			performRead = 1;
			free(cp->inbuf.buf);
			cp->inbuf.buf = NULL;
			goto readMore;
		} else {
			goto readZero;
		}
/*
	The out buffer is too small to fit the decoded or response
	data.  Increase the size of the buffer and call decode again
*/
	case SSL_FULL:
		cp->inbuf.size *= 2;
		if (cp->inbuf.buf != (unsigned char*)buf) {
			free(cp->inbuf.buf);
			cp->inbuf.buf = NULL;
		}
		cp->inbuf.start = cp->inbuf.end = cp->inbuf.buf = 
			(unsigned char *)malloc(cp->inbuf.size);
		goto decodeMore;
	}
/*
	We consolidated some of the returns here because we must ensure
	that conn->inbuf is cleared if pointing at caller's buffer, otherwise
	it will be freed later on.
*/
readZero:
	if (cp->inbuf.buf == (unsigned char*)buf) {
		cp->inbuf.buf = NULL;
	}
	return 0;
readError:
	if (cp->inbuf.buf == (unsigned char*)buf) {
		cp->inbuf.buf = NULL;
	}
	return -1;
}
Exemple #6
0
/*
	Client side. Open a socket connection to a remote ip and port.
	This code is not specific to SSL.
*/
SOCKET socketConnect(char *ip, short port, int *err)
{
	struct sockaddr_in	addr;
	SOCKET				fd;
	int					rc;
	struct hostent *hent;
	char   ipbuf[20];
	
	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		fprintf(stderr, "Error creating socket\n");
		*err = getSocketError();
		return INVALID_SOCKET;
	}
/*
	Make sure the socket is not inherited by exec'd processes
	Set the REUSEADDR flag to minimize the number of sockets in TIME_WAIT
*/
	fcntl(fd, F_SETFD, FD_CLOEXEC);
	rc = 1;
//	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&rc, sizeof(rc));
	setSocketNodelay(fd);
/*
	Turn on blocking mode for the connecting socket
*/
	setSocketBlock(fd);
/* //Marked by Gemtek
	hent = gethostbyname(ip);
	if (!hent) {
		fprintf(stderr, "Error resolving host\n");
	}
*/
	memset((char *) &addr, 0x0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	//Gemtek added
	sprintf( ipbuf ,"%s", "127.0.0.1" );
	fprintf( stderr , "ip:port ==> %s:%d\n" , ipbuf , port );
	//Gemtek added
	if( NULL != ip && strlen( ipbuf ) >= 7 && 0!=strcmp( ipbuf , "localhost") )
	{
	//bcopy(hent->h_addr, &addr.sin_addr, hent->h_length);
		 addr.sin_addr.s_addr = inet_addr( ipbuf ) ;
	}	
	rc = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
#if WIN
	if (rc != 0) {
#else
	if (rc < 0) {
#endif
		*err = getSocketError();
		return INVALID_SOCKET;
	}
	return fd;
}

/******************************************************************************/
/*
	Server side.  Accept an incomming SSL connection request.
	'conn' will be filled in with information about the accepted ssl connection

	return -1 on error, 0 on success, or WOULD_BLOCK for non-blocking sockets
*/
int sslAccept(sslConn_t **cpp, SOCKET fd, sslKeys_t *keys,
			  int (*certValidator)(sslCertInfo_t *t, void *arg), int flags)
{
	sslConn_t		*conn;
	unsigned char	buf[1024];
	int				status, rc;
/*
	Associate a new ssl session with this socket.  The session represents
	the state of the ssl protocol over this socket.  Session caching is
	handled automatically by this api.
*/
	conn = calloc(sizeof(sslConn_t), 1);
	conn->fd = fd;
	if (matrixSslNewSession(&conn->ssl, keys, NULL,
			SSL_FLAGS_SERVER | flags) < 0) {
		sslFreeConnection(&conn);
		return -1;
	}

/*
	MatrixSSL doesn't provide buffers for data internally.  Define them
	here to support buffered reading and writing for non-blocking sockets.
	Although it causes quite a bit more work, we support dynamically growing
	the buffers as needed.  Alternately, we could define 16K buffers here
	and not worry about growing them.
*/
	memset(&conn->inbuf, 0x0, sizeof(sslBuf_t));
	conn->insock.size = 10240;
	conn->insock.start = conn->insock.end = conn->insock.buf = 
		(unsigned char *)malloc(conn->insock.size);
	conn->outsock.size = 10240;
	conn->outsock.start = conn->outsock.end = conn->outsock.buf = 
		(unsigned char *)malloc(conn->outsock.size);
	conn->inbuf.size = 0;
	conn->inbuf.start = conn->inbuf.end = conn->inbuf.buf = NULL;
	*cpp = conn;

readMore:
	rc = sslRead(conn, buf, sizeof(buf), &status);
/*
	Reading handshake records should always return 0 bytes, we aren't
	expecting any data yet.
*/
	if (rc == 0) {
		if (status == SSLSOCKET_EOF || status == SSLSOCKET_CLOSE_NOTIFY) {
			sslFreeConnection(&conn);
			return -1;
		}
		if (matrixSslHandshakeIsComplete(conn->ssl) == 0) {
			goto readMore;
		}
	} else if (rc > 0) {
		socketAssert(0);
		return -1;
	} else {
		fprintf(stderr, "sslRead error in sslAccept\n");
		sslFreeConnection(&conn);
		return -1;
	}
	*cpp = conn;

	return 0;
}
int main(int argc, char **argv)
#endif
{
	SOCKET			srv_fd;
	int				status;
	WSADATA			wsaData;
	
	// options
	char				*srv_host = NULL;
	int				srv_port = 0;
	char 				*keyfile = NULL; //"privkeySrv.pem";
	char 				*certfile = NULL; //"certSrv.pem";
	int				vlevel = 0;
	char 				*cpos,*opos;
	int tmpport;
	int c;
	int 			intarg;
 	
#if VXWORKS
	int					argc;
	char				**argv;
	parseCmdLineArgs(arg1, &argc, &argv);
#endif /* VXWORKS */

#if WINCE
	int					argc;
	char				**argv;
	char				args[256];

/*
 *	parseCmdLineArgs expects an ASCII string and CE is unicoded, so convert
 *	the command line.  args will get hacked up, so you can't pass in a
 *	static string.
 */
	WideCharToMultiByte(CP_ACP, 0, lpCmdLine, -1, args, 256, NULL, NULL);

/*
 *	Parse the command line into an argv array.  This allocs memory, so
 *	we have to free argv when we're done.
 */
	parseCmdLineArgs(args, &argc, &argv);
#endif /* WINCE */


/*
	prepare
*/
	
#ifndef USE_FORK
	memset(connections,0,MAXPROXYCOUNT*sizeof(struct proxyConnection));
#endif
	
/*
	getopt
*/
	/* Gemtek add +++ */
	if(argc == 1) usage(1);
	/* Gemtek add --- */
	
	for (;;) {
		c = getopt (argc, argv, "VD:P:fo:cd:r:p:A:v:h");
		if (c == -1) {
			break;
		}

		switch (c) {
			case 'c':
				// client mode
				isClient=1;
				break;
			
			case 'd':
				// daemon mode [host:]port
				cpos = NULL;
				tmpport = 0;
				if((cpos = strchr(optarg,':'))) {				
					*cpos = '\0';
					if(optarg && optarg[0])
						srv_host = optarg;
					optarg = ++cpos;
				}
				if(optarg && optarg[0]) {
					tmpport = (int)strtol(optarg, (char **)NULL, 0);
					if(tmpport) srv_port = tmpport;
				}
				break;
			
			case 'r':
				// remote [host:]port
				cpos = NULL;
				tmpport = 0;
				if((cpos = strchr(optarg,':'))) {				
					*cpos = '\0';
					if(optarg && optarg[0])
						dst_host = optarg;
					optarg = ++cpos;
				}
				if(optarg && optarg[0]) {
					tmpport = (int)strtol(optarg, (char **)NULL, 0);
					if(tmpport) dst_port = tmpport;
				}
				break;
				
			case 'p':
				// pemfile (requred in servermode)
				keyfile = optarg;
				break;
			
			case 'A':
				// CA file
				certfile = optarg;
				break;
			
			case 'v':
				// veryfication level
				if(optarg && optarg[0]) {
					vlevel = (int)strtol(optarg, (char **)NULL, 0);
					if(vlevel == 1 ) {
						cervalidator = certChecker;
					}
					else if(vlevel > 3 || vlevel < 0) {
						fprintf(stderr,"-v takes whole numbers between 0 and 3");
						exit(2);
					}
				}
				break;
			
			case 'P':
				// create a pidfile
				pidfile=optarg;
				break;
				
			case 'f':
				// run in foreground.
				nofork=1;
				nosysl=1;
				break;
				
			case 'o':
				// append logmessages to a file instead of stdout/syslog
				break;
				
			case 'O':
				// socket options. TODO
				break;
			
			case 'D':
				// debug level 0...7
				intarg=strtol(optarg,NULL,0);
				if(intarg<0 || intarg>7) {
					usage(1);
				}
				gLogLevel=intarg;
				break;
				
			case 'V':
				// version
				break;
				
			case '?':
			case 'h':
				usage(0);
				break;
			
			default:
				usage(1);
				break;
		}
	}


/* install handlers */
	signal( SIGPIPE, SIG_IGN );
	signal(SIGCHLD,sigchld_handler); /* ignore child */
	signal(SIGHUP,kill_handler); /* catch hangup signal */
	signal(SIGTERM,kill_handler); /* catch kill signal */
	
/*
	Initialize Windows sockets (no-op on other platforms)
*/
	WSAStartup(MAKEWORD(1,1), &wsaData);
	
	if(!nosysl) {
		openlog("matrixtunnel", LOG_PID, LOG_DAEMON);
		setlogmask(LOG_UPTO(gLogLevel));
	}
	
/*
	Initialize the MatrixSSL Library, and read in the public key (certificate)
	and private key.
*/
	if (matrixSslOpen() < 0) {
		ELOG("matrixSslOpen failed, exiting...");
		exit(1);
	}

/*
	Standard PEM files
*/
	if (matrixSslReadKeys(&keys, certfile, keyfile, NULL, NULL) < 0)  {
		ELOG("Error reading or parsing %s or %s, exiting...", 
			certfile, keyfile);
		exit(1);
	}

	// go to background
	if(!nofork) {
		daemonize();
	}

/*
	Create the listen socket
*/
	if ((srv_fd = socketListen(srv_port, &status)) == INVALID_SOCKET) {
		ELOG("Cannot listen on port %d, exiting...", srv_port);
		exit(1);
	}
/*
	Set blocking or not on the listen socket
*/
	setSocketBlock(srv_fd);

/*
	Main connection loop
*/
	struct proxyConnection	*cp=NULL;
	struct proxyConnection	*ncp;
	
	fd_set	rs, ws, es, cr;
	int			fdmax;
	struct timeval tv;
	int			res, dontClose;
	
	char		buf[4096];
	int pc, sc;
	
	int			ccount;
	
	while (!quit) {
		fdmax=srv_fd;
		ncp=NULL;
		
		FD_ZERO(&rs);
		FD_ZERO(&ws);
		FD_ZERO(&es);
		
		FD_SET(srv_fd,&rs);
		FD_SET(srv_fd,&ws);
		FD_SET(srv_fd,&es);
		ccount=0;
		
#ifndef USE_FORK
		DLOG("next select on fds: %d ",srv_fd);
		for(cp=connections;cp<&connections[MAXPROXYCOUNT];cp++) {
			if (cp->done) {
				closeProxyConnection(cp);
			}
			if (cp->secure_up) {
				FD_SET(cp->secure->fd,&rs);
				FD_SET(cp->secure->fd,&ws);
				FD_SET(cp->secure->fd,&es);

				if (fdmax < cp->secure->fd)
					fdmax = cp->secure->fd;
				
				DLOG("fd: %d",cp->secure->fd);
				ccount++;
			}
			if (cp->plain_up) {
				FD_SET(cp->plain,&rs);			
				FD_SET(cp->plain,&ws);
				FD_SET(cp->plain,&es);
					
				if (fdmax < cp->plain)
					fdmax = cp->plain;
				
				DLOG("fd: %d",cp->plain);
				ccount++;
			}
			if(!ncp && !cp->inuse){
				ncp=cp;
				memset(ncp,0,sizeof(struct proxyConnection));
			}
		}
#else
		struct proxyConnection	ncp_s;
		ncp=&ncp_s;
		memset(ncp,0,sizeof(struct proxyConnection));
#endif
		
		tv.tv_sec=10;
		tv.tv_usec=0;

		DLOG("main : select on %d open connections. fdmax: %d", ccount, fdmax);
		res=select(fdmax+1,&rs,NULL,&es,&tv);
		DLOG("select returned: %d %s", res , strerror(errno) );

		if(res<0) {
			perror("select");
			continue;
		}
		
		if(res==0)
			continue;

#ifndef USE_FORK
		// handle open connections
		for(cp=connections;cp<&connections[MAXPROXYCOUNT];cp++) {
			if (cp->secure_up && cp->plain_up) {
				if(FD_ISSET(cp->secure->fd,&es) || FD_ISSET(cp->plain,&es)) {
						closeProxyConnection(cp);
						continue;
				}
				
				if(secureReady(cp)) {
					sc=proxyReadwrite(cp,1);
					if(sc<0) {
						closeProxyConnection(cp);
						continue;
					}
				}
				
				if(plainReady(cp)) {
					pc=proxyReadwrite(cp,0);
					if(pc<0) {
						closeProxyConnection(cp);
						continue;
					}
				}
			}
		}
#endif

		// do we have new connections?
		if(FD_ISSET(srv_fd,&rs)) {
			proxyAccept(srv_fd,ncp);
		}			
	}

/*
	Close listening socket, free remaining items
*/
	socketShutdown(srv_fd);
	
#ifndef USE_FORK
	for(cp=connections;cp<&connections[MAXPROXYCOUNT];cp++) {
		closeProxyConnection(cp);
	}
#endif
	
	if(!nosysl) {
		closelog();
	}
	
	matrixSslFreeKeys(keys);
	matrixSslClose();
	WSACleanup();
	return 0;
}
int sslRead(sslConn_t *cp, char *buf, int len, int *status)
{
  int				bytes, rc, remaining;
  unsigned char	error, alertLevel, alertDescription, performRead;
  
  *status = 0;
  
  if (cp->ssl == NULL || len <= 0) {
    return -1;
  }
  if (cp->inbuf.buf) {
    if (cp->inbuf.start < cp->inbuf.end) {
      remaining = (int)(cp->inbuf.end - cp->inbuf.start);
      bytes = (int)min(len, remaining);
      memcpy(buf, cp->inbuf.start, bytes);
      cp->inbuf.start += bytes;
      return bytes;
    }
    free(cp->inbuf.buf);
    cp->inbuf.buf = NULL;
  }
  if (cp->insock.buf < cp->insock.start) {
    if (cp->insock.start == cp->insock.end) {
      cp->insock.start = cp->insock.end = cp->insock.buf;
    } else {
      memmove(cp->insock.buf, cp->insock.start, cp->insock.end - cp->insock.start);
      cp->insock.end -= (cp->insock.start - cp->insock.buf);
      cp->insock.start = cp->insock.buf;
    }
  }
  performRead = 0;
 readMore:
  if (cp->insock.end == cp->insock.start || performRead) {
    performRead = 1;
    bytes = recv(cp->fd, (char *)cp->insock.end, 
		 (int)((cp->insock.buf + cp->insock.size) - cp->insock.end), MSG_NOSIGNAL);
    if (bytes == SOCKET_ERROR) {
      *status = getSocketError();
      return -1;
    }
    if (bytes == 0) {
      *status = SSLSOCKET_EOF;
      return 0;
    }
    cp->insock.end += bytes;
  }
  cp->inbuf.start = cp->inbuf.end = cp->inbuf.buf = malloc(len);
  cp->inbuf.size = len;
 decodeMore:
  error = 0;
  alertLevel = 0;
  alertDescription = 0;
  
  rc = matrixSslDecode(cp->ssl, &cp->insock, &cp->inbuf, &error, &alertLevel, 
		       &alertDescription);
  switch (rc) {
  case SSL_SUCCESS:
    return 0;
  case SSL_PROCESS_DATA:
    rc = (int)(cp->inbuf.end - cp->inbuf.start);
    rc = min(rc, len);
    memcpy(buf, cp->inbuf.start, rc);
    cp->inbuf.start += rc;
    return rc;
  case SSL_SEND_RESPONSE:
    bytes = send(cp->fd, (char *)cp->inbuf.start, 
		 (int)(cp->inbuf.end - cp->inbuf.start), MSG_NOSIGNAL);
    if (bytes == SOCKET_ERROR) {
      *status = getSocketError();
      if (*status != WOULD_BLOCK) {
	fprintf(stdout, "Socket send error:  %d\n", *status);
	goto readError;
      }
      *status = 0;
    }
    cp->inbuf.start += bytes;
    if (cp->inbuf.start < cp->inbuf.end) {
      setSocketBlock(cp->fd);
      bytes = send(cp->fd, (char *)cp->inbuf.start, 
		   (int)(cp->inbuf.end - cp->inbuf.start), MSG_NOSIGNAL);
      if (bytes == SOCKET_ERROR) {
	*status = getSocketError();
	goto readError;
      }
      cp->inbuf.start += bytes;
      socketAssert(cp->inbuf.start == cp->inbuf.end);
      setSocketNonblock(cp->fd);
    }
    cp->inbuf.start = cp->inbuf.end = cp->inbuf.buf;
    return 0;
  case SSL_ERROR:
    fprintf(stderr, "SSL: Closing on protocol error %d\n", error);
    if (cp->inbuf.start < cp->inbuf.end) {
      setSocketNonblock(cp->fd);
      bytes = send(cp->fd, (char *)cp->inbuf.start, 
		   (int)(cp->inbuf.end - cp->inbuf.start), MSG_NOSIGNAL);
    }
    goto readError;
  case SSL_ALERT:
    if (alertDescription == SSL_ALERT_CLOSE_NOTIFY) {
      *status = SSLSOCKET_CLOSE_NOTIFY;
      goto readZero;
    }
    fprintf(stderr, "SSL: Closing on client alert %d: %d\n",
	    alertLevel, alertDescription);
    goto readError;
  case SSL_PARTIAL:
    if (cp->insock.start == cp->insock.buf && cp->insock.end == 
	(cp->insock.buf + cp->insock.size)) {
      if (cp->insock.size > SSL_MAX_BUF_SIZE) {
	goto readError;
      }
      cp->insock.size *= 2;
      cp->insock.start = cp->insock.buf = 
	(unsigned char *)realloc(cp->insock.buf, cp->insock.size);
      cp->insock.end = cp->insock.buf + (cp->insock.size / 2);
    }
    if (!performRead) {
      performRead = 1;
      free(cp->inbuf.buf);
      cp->inbuf.buf = NULL;
      goto readMore;
    } else {
      goto readZero;
    }
  case SSL_FULL:
    cp->inbuf.size *= 2;
    if (cp->inbuf.buf != (unsigned char*)buf) {
      free(cp->inbuf.buf);
      cp->inbuf.buf = NULL;
    }
    cp->inbuf.start = cp->inbuf.end = cp->inbuf.buf = 
      (unsigned char *)malloc(cp->inbuf.size);
    goto decodeMore;
  }
 readZero:
  if (cp->inbuf.buf == (unsigned char*)buf) {
    cp->inbuf.buf = NULL;
  }
  return 0;
 readError:
  if (cp->inbuf.buf == (unsigned char*)buf) {
    cp->inbuf.buf = NULL;
  }
  return -1;
}