int MailConnection::authenticate()
{
    std::cout << "x\n";
    char buffer[BUFSIZE];
    std::string response;

    response = sslRead();
    std::cout << response;

    sslWrite(("ehlo "+_address+"\r\n").c_str());
    response = sslRead();
    std::cout << response;

	sslWrite("AUTH LOGIN\r\n");
	response = sslRead();
	std::cout << response;

	sslWrite((_login+"\r\n").c_str());
	response = sslRead();
	std::cout << response;

	sslWrite((_password+"\r\n").c_str());
	response = sslRead();
	std::cout << response;

	if (response.compare("235 2.7.0 Accepted\r\n") == 0)
        return 1;
    return 0;
}
void MailConnection::Send(std::string author, std::string recipient, std::string subject, std::string body)
{
    std::string response;

    // author
	sslWrite(("MAIL FROM: <" + originalLogin + ">\r\n").c_str());
	response = sslRead();
	std::cout << response;

    // recipient
	sslWrite(("RCPT TO: <" + recipient + ">\r\n").c_str());
	response = sslRead();
	std::cout << response;

	sslWrite("DATA\r\n");
    response = sslRead();
    std::cout << response;

    // email text
    std::string _body;
    _body  = "From: " + author + " <" + originalLogin + ">"
	   "\nSubject: " + subject +
	   "\nTo: <" + recipient + ">"
	   "\n\n" + body;

	sslWrite(_body.c_str());
	sslWrite("\r\n.\r\n");
}
예제 #3
0
파일: main_rc.c 프로젝트: fzoli/C
// Very basic main: we send GET / and print the response.
int main(int argc, char **argv) {
    sslInit();

    SSL_CTX* ctx = sslCreateCtx(SSLv23_client_method());
    if (ctx == NULL) return EXIT_FAILURE;
    
    connection *c;
    char *response;

    c = sslConnect(ctx);
    
    sslWriteByte(c, 1);
    sslWriteByte(c, 0);
    
    sslWrite(c, "OK\r\n");
    
    response = sslRead(c);

    if (response) printf("%s\n", response);

    sleep(2);
    
    free(response);

    sslDisconnect(c);
    
    sslDestroyCtx(ctx);
    
    sslDestroy();
    
    return EXIT_SUCCESS;
}
예제 #4
0
// Read bytes from the already opened SSL connection
int
SSLClient::sslRead(amf::Buffer &buf)
{
    GNASH_REPORT_FUNCTION;

    return sslRead(buf.reference(), buf.allocated());
}
예제 #5
0
// Send the data using a telnet session on a TLS connection
void sendByTelnet(sensor_data data, char * token, char * metric, char * additional_tags) {

	ssl_connection *c;
	char *response, *response_auth, query[1024];
	time_t now;

	// Initiate the connection
	c = sslConnect ();

	// Initiate the authentication
	snprintf(query, 1023, "auth %s\n", token);
	sslWrite (c, query);
	response_auth = sslRead (c);

	// Read the response from the server (should send 'ok' if the token is valid)
	if (0 == strcmp("ok\n", response_auth)) {
		time(&now);

		// Send the put commands one after the other
		snprintf(query, 1023, "put %s.hum %ld %s %s\n", metric, now, data.hum, additional_tags);
		sslWrite (c, query);

		snprintf(query, 1023, "put %s.temp %ld %s %s\n", metric, now, data.temp, additional_tags);
		sslWrite (c, query);
	} else {
		printf("Error auth, response is %s\n", response_auth);
	}

	free (response_auth);

	sslWrite (c, "exit\n");
	// Read the response from the server. No response means no error
	response = sslRead (c);
	if (0 != strcmp("", response)) {
		printf ("Command put error\n  \"%s\"\n", response);
	}
	free(response);

	// Disconnect from the server
	sslDisconnect (c);
}
예제 #6
0
int SP_MatrixsslChannel :: receive( SP_Session * session )
{
	char buffer[ 4096 ] = { 0 };

	int ret = sslRead( mConn, buffer, sizeof( buffer ), &errno );
	if( ret > 0 ) {
		session->getInBuffer()->append( buffer, ret );
	} else if( ret < 0 ) {
		sp_syslog( LOG_EMERG, "sslRead fail" );
	}

	return ret;
}
예제 #7
0
// Serve the connection
void handle_client(int client, SSL_CTX *ctx) {
    char *request = NULL;
    size_t len;
    char *response = "HTTP/1.0 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n";
    SSL *ssl;

    ssl = SSL_new(ctx); //get new SSL state with context
    SSL_set_fd(ssl, client); //set connection socket to SSL state

    // do SSL-protocol accept
    if (SSL_accept(ssl) == FAIL) {
        ERR_print_errors_fp(stderr);
        SSL_free(ssl);
        return;
    }
    
    ShowCerts(ssl); // get any certificates
    
    do {
        if (request) {
            free(request);
            request = NULL;
        }
    
        request = sslRead(ssl); // get request
        len = strlen(request);
        
        if (len > 0) {
#ifdef _WIN32
            printf("Echo(%u): %s\n", len, request);
#else
            printf("Echo(%zu): %s\n", len, request);
#endif
            
            printf("send\n");
            SSL_write(ssl, response, strlen(response)); // send request back
        }
        else {
            ERR_print_errors_fp(stderr);
            break;
        }
    }
    while (strlen(request) > 0);
    
    if (request) {
        free(request);
        request = NULL;
    }

    SSL_free(ssl); //release SSL state
}
예제 #8
0
sslConn_t *sslDoHandshake(sslConn_t *conn, short cipherSuite)
{
  char	buf[1024];
  int	bytes, status, rc;
  
  conn->insock.size = 1024;
  conn->insock.start = conn->insock.end = conn->insock.buf = 
    (unsigned char *)malloc(conn->insock.size);
  conn->outsock.size = 1024;
  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;
  
  bytes = matrixSslEncodeClientHello(conn->ssl, &conn->outsock, cipherSuite);
  if (bytes < 0) {
    fprintf(stderr, "error %s:%d\n",__FILE__,__LINE__);
    socketAssert(bytes < 0);
    goto error;
  }
  if (psSocketWrite(conn->fd, &conn->outsock) < 0) {
    fprintf(stdout, "Error in socketWrite\n");
    goto error;
  }
  conn->outsock.start = conn->outsock.end = conn->outsock.buf;
 readMore:
  rc = sslRead(conn, buf, sizeof(buf), &status);
  if (rc == 0) {
    if (status == SSLSOCKET_EOF || status == SSLSOCKET_CLOSE_NOTIFY) {
      fprintf(stderr, "error %s:%d\n",__FILE__,__LINE__);
      goto error;
    }
    if (matrixSslHandshakeIsComplete(conn->ssl) == 0) {
      goto readMore;
    }
  } else if (rc > 0) {
    fprintf(stderr, "sslRead got %d data in sslDoHandshake %s\n", rc, buf);
    goto readMore;
  } else {
    fprintf(stderr, "sslRead error in sslDoHandhake\n");
    goto error;
  }
  
  return conn;
  
 error:
  fprintf(stderr, "error %s:%d\n",__FILE__,__LINE__);
  sslFreeConnection(&conn);
  return NULL;
}
예제 #9
0
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;
  conn = calloc(sizeof(sslConn_t), 1);
  conn->fd = fd;
  if (matrixSslNewSession(&conn->ssl, keys, NULL,
			  SSL_FLAGS_SERVER | flags) < 0) {
    sslFreeConnection(&conn);
    return -1;
  }
  
#ifdef USE_CLIENT_AUTH
  matrixSslSetCertValidator(conn->ssl, certValidator, keys);
#endif /* USE_CLIENT_AUTH */
  memset(&conn->inbuf, 0x0, sizeof(sslBuf_t));
  conn->insock.size = 1024;
  conn->insock.start = conn->insock.end = conn->insock.buf = 
    (unsigned char *)malloc(conn->insock.size);
  conn->outsock.size = 1024;
  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);
  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;
}
예제 #10
0
// Very basic main: we send GET / and print the response.
int main (int argc, char **argv)
{
  connection *c;
  char *response;

  c = sslConnect ();

  sslWrite (c, "GET /\r\n\r\n");
  response = sslRead (c);

  printf ("%s\n", response);

  sslDisconnect (c);
  free (response);

  return 0;
}
예제 #11
0
파일: SSL.c 프로젝트: EasyCard/CMAS_VG5000S
// Very basic main: we send GET / and print the response.
int SSLSendandRecv ()
{
  connection *c;
  char *response;
  BYTE recvbuf[1024];
  c = sslConnect ();
  int size=0;
  unsigned char  SendPack[1024];
  memset(SendPack,0x00,sizeof(SendPack));
  USHORT   ret=usReadFileData(SendFile,&size,(BYTE *)&SendPack);
  if(ret!=d_OK) return ret;
  
  
  int iret=sslWrite (c, SendPack,size);
  
  response = sslRead (c);
 
  sslDisconnect (c);
  free (response);

  return 0;
}
예제 #12
0
void MailConnection::sslDisconnect()
{
    if (!conn)
        return;

    std::string response;
    sslWrite("quit\r\n");
	response = sslRead();
	std::cout << response;

    if (conn->socket)
        close(conn->socket);
    if (conn->sslHandle)
    {
        SSL_shutdown(conn->sslHandle);
        SSL_free(conn->sslHandle);
    }
    if (conn->sslContext)
        SSL_CTX_free(conn->sslContext);

    delete conn;
    conn = nullptr;
}
/*
	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 **conn, SOCKET fd, sslKeys_t *keys, int32 resume,
              int32 (*certValidator)(ssl_t *, psX509Cert_t *, int32))
{
    sslConn_t		*cp;
    int				rc;

    if (resume == 0) {
        /*
        		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.
        */
        cp = balloc(B_L, sizeof(sslConn_t));
        memset(cp, 0x0, sizeof(sslConn_t));
        cp->fd = fd;
        if (matrixSslNewServerSession(&cp->ssl, keys, certValidator) < 0) {
            sslFreeConnection(&cp);
            return -1;
        }
#ifdef USE_NONBLOCKING_SSL_SOCKETS
        /* Set this ourselves, "just to make sure" */
        setSocketNonblock(fd);
#endif
    } else {
        cp = *conn;
    }
    /*
    	This call will perform the SSL handshake
    */
    rc = sslRead(cp, NULL, 0);
    if (rc < 0) {
        return -1;
    }
    *conn = cp;
    return 0;
}
예제 #14
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;
}
예제 #15
0
int main (int argc, char **argv)
{
   int i;
   connection *c;
   char request[1024]="";
   char key[1024]="";
   char terms[1024]="";
   char filename[128]="";
   FILE* pSearchTerms = NULL;

   /*****************************************/
   /* Open the search term file for reading */
   /*****************************************/
   sprintf(filename, "./%s", argv[1]);
   pSearchTerms = fopen(filename, "r");

   if(pSearchTerms == NULL)
   {
      fprintf(stderr, "Error opening search terms file %s!\n", filename);
      return (EXIT_FAILURE);
   }

   /***************************************/
   /* Open the results file for appending */
   /***************************************/
   sprintf(filename, "./%s.res", argv[1]);
   pResults = fopen(filename, "w+");

   if(pResults == NULL)
   {
      fprintf(stderr, "Error opening results file %s!\n", filename);
      return (EXIT_FAILURE);
   }

   /***********************************/
   /* Read from the search terms file */
   /***********************************/
   fgets(terms, 1024, pSearchTerms);
   terms[strlen(terms)-1] = '\0';

   /**************************/
   /* Get our search results */
   /**************************/
   for(i = 0; i < NUM_QUERIES; i++)
   {
      c = sslConnect ();
      sprintf(key, "/customsearch/v1?key=GOOGLE_API_SECRET&cx=003397780648636422832:u25rx3s92ro&fields=items(link)&start=%d&q=%s", ((i* 10) + 1), terms);
      sprintf(request, "GET https://%s%s\r\n\r\n", SERVER, key);
      fprintf(stdout, "%s", request);
      sslWrite(c, request);
      sslRead(c);
      sslDisconnect (c);
   }

   /***************************/
   /* Close the file pointers */
   /***************************/
   fclose(pSearchTerms);
   fclose(pResults);

   /************************/
   /* Call the JSON parser */
   /************************/

   /*****************************************/
   /* Call the Text Processor and Retriever */
   /*****************************************/

   /****************************/
   /* Call the Site Classifier */
   /****************************/

   return (EXIT_SUCCESS);
}
예제 #16
0
파일: httpsClient.c 프로젝트: CarlHuff/kgui
int main(int argc, char **argv)
#endif
{
	sslSessionId_t		*sessionId;
	sslConn_t			*conn;
	sslKeys_t			*keys;
	WSADATA				wsaData;
	SOCKET				fd;
	short				cipherSuite;
	unsigned char		*ip, *c, *requestBuf;
	unsigned char		buf[1024];
	int					iterations, requests, connectAgain, status;
	int					quit, rc, bytes, i, j, err;
	time_t				t0, t1;
#if REUSE
	int					anonStatus;
#endif
#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 */

	conn = NULL;
/*
	First (optional) argument is ip address to connect to (port is hardcoded)
	Second (optional) argument is number of iterations to perform
	Third (optional) argument is number of keepalive HTTP requests
	Fourth (optional) argument is cipher suite number to use (0 for any)
*/
	ip = HTTPS_IP;
	iterations = ITERATIONS;
	requests = REQUESTS;
	cipherSuite = 0x0000;
	if (argc > 1) {
		ip = argv[1];
		if (argc > 2) {
			iterations = atoi(argv[2]);
			socketAssert(iterations > 0);
			if (argc > 3) {
				requests = atoi(argv[3]);
				socketAssert(requests > 0);
				if (argc > 4) {
					cipherSuite = (short)atoi(argv[4]);
				}
			}
		}
	}
/*
	Initialize Windows sockets (no-op on other platforms)
*/
	WSAStartup(MAKEWORD(1,1), &wsaData);
/*
	Initialize the MatrixSSL Library, and read in the certificate file
	used to validate the server.
*/
	if (matrixSslOpen() < 0) {
		fprintf(stderr, "matrixSslOpen failed, exiting...");
	}
	sessionId = NULL;
	if (matrixSslReadKeys(&keys, NULL, NULL, NULL, CAfile) < 0) {
		goto promptAndExit;
	}
/*
	Intialize loop control variables
*/
	quit = 0;
	connectAgain = 1;
	i = 1;
/*
	Just reuse the requestBuf and malloc to largest possible message size
*/
	requestBuf = malloc(sizeof(requestAgain));
	t0 = time(0);
/*
	Main ITERATIONS loop
*/
	while (!quit && (i < iterations)) {
/*
		sslConnect uses port and ip address to connect to SSL server.
		Generates a new session
*/
		if (connectAgain) {
			if ((fd = socketConnect(ip, HTTPS_PORT, &err)) == INVALID_SOCKET) {
				fprintf(stdout, "Error connecting to server %s:%d\n", ip, HTTPS_PORT);
				matrixSslFreeKeys(keys);
				goto promptAndExit;
			}
			if (sslConnect(&conn, fd, keys, sessionId, cipherSuite, certChecker) < 0) {
				quit = 1;
				socketShutdown(fd);
				fprintf(stderr, "Error connecting to %s:%d\n", ip, HTTPS_PORT);
				continue;
			}
			i++;
			connectAgain = 0;
			j = 1;
		}
		if (conn == NULL) {
			quit++;
			continue;
		}
/*
		Copy the HTTP request header into the buffer, based of whether or
		not we want httpReflector to keep the socket open or not
*/
		if (j == requests) {
			bytes = (int)strlen(request);
			memcpy(requestBuf, request, bytes);
		} else {
			bytes = (int)strlen(requestAgain);
			memcpy(requestBuf, requestAgain, bytes);
		}
/*
		Send request.  
		< 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(conn, requestBuf, bytes, &status);
		if (rc < 0) {
			fprintf(stdout, "Internal sslWrite error\n");
			socketShutdown(conn->fd);
			sslFreeConnection(&conn);
			continue;
		} else if (rc == 0) {
			goto writeMore;
		}
/*
		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 response header.  There may be data following
		this header, but we don't try too hard to read it for this example.
*/
		c = buf;
readMore:
		if ((rc = sslRead(conn, 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(conn->fd);
				sslFreeConnection(&conn);
				continue;
			}
			goto readMore;
		}
/*
		Determine if we want to do a pipelined HTTP request/response
*/
		if (j++ < requests) {
			fprintf(stdout, "R");
			continue;
		} else {
			fprintf(stdout, "C");
		}
/*
		Reuse the session.  Comment out these two lines to test the entire
		public key renegotiation each iteration
*/
#if REUSE
		matrixSslFreeSessionId(sessionId);
		matrixSslGetSessionId(conn->ssl, &sessionId);
/*
		This example shows how a user might want to limit a client to
		resuming handshakes only with authenticated servers.  In this
		example, the client will force any non-authenticated (anonymous)
		server to go through a complete handshake each time.  This is
		strictly an example of one policy decision an implementation 
		might wish to make.
*/
		matrixSslGetAnonStatus(conn->ssl, &anonStatus);
		if (anonStatus) {
			matrixSslFreeSessionId(sessionId);
			sessionId = NULL;
		}
#endif
/*
		Send a closure alert for clean shutdown of remote SSL connection
		This is for good form, some implementations just close the socket
*/
		sslWriteClosureAlert(conn);
/*
		Session done.  Connect again if more iterations remaining
*/
		socketShutdown(conn->fd);
		sslFreeConnection(&conn);
		connectAgain = 1;
	}

	t1 = time(0);
	free(requestBuf);
	matrixSslFreeSessionId(sessionId);
	if (conn && conn->ssl) {
		socketShutdown(conn->fd);
		sslFreeConnection(&conn);
	}
	fprintf(stdout, "\n%d connections in %d seconds (%f c/s)\n", 
		i, (int)(t1 - t0), (double)i / (t1 - t0));
	fprintf(stdout, "\n%d requests in %d seconds (%f r/s)\n", 
		i * requests, (int)(t1 - t0), 
		(double)(i * requests) / (t1 - t0));
/*
	Close listening socket, free remaining items
*/
	matrixSslFreeKeys(keys);
	matrixSslClose();
	WSACleanup();
promptAndExit:
	fprintf(stdout, "Press return to exit...\n");
	getchar();

#if WINCE || VXWORKS
	if (argv) {
		free((void*) argv);
	}
#endif /* WINCE */
	return 0;
}
예제 #17
0
/*
	Construct the initial HELLO message to send to the server and initiate
	the SSL handshake.  Can be used in the re-handshake scenario as well.
*/
sslConn_t *sslDoHandshake(sslConn_t *conn, short cipherSuite)
{
	char	buf[1024];
	int		bytes, status, rc;

/*
	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.
*/
	conn->insock.size = 1024;
	conn->insock.start = conn->insock.end = conn->insock.buf = 
		(unsigned char *)malloc(conn->insock.size);
	conn->outsock.size = 1024;
	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;

	bytes = matrixSslEncodeClientHello(conn->ssl, &conn->outsock, cipherSuite);
	if (bytes < 0) {
		socketAssert(bytes < 0);
		goto error;
	}
/*
	Send the hello with a blocking write
*/
	if (psSocketWrite(conn->fd, &conn->outsock) < 0) {
		fprintf(stdout, "Error in socketWrite\n");
		goto error;
	}
	conn->outsock.start = conn->outsock.end = conn->outsock.buf;
/*
	Call sslRead to work through the handshake.  Not actually expecting
	data back, so the finished case is simply when the handshake is
	complete.
*/
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) {
			goto error;
		}
		if (matrixSslHandshakeIsComplete(conn->ssl) == 0) {
			goto readMore;
		}
	} else if (rc > 0) {
		fprintf(stderr, "sslRead got %d data in sslDoHandshake %s\n", rc, buf);
		goto readMore;
	} else {
		fprintf(stderr, "sslRead error in sslDoHandhake\n");
		goto error;
	}

	return conn;

error:
	sslFreeConnection(&conn);
	return NULL;
}
예제 #18
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;
}
예제 #19
0
static int
proxyReadwrite(struct proxyConnection *cp, int isServer)
{
	char buf[4096];
	int	status=0;
	int rc, total=0;
	int amt;
	int offset;
	
	char* sense = isServer ? "ssl->plain" : "plain->ssl";
	
	DLOG("%s reading",sense);
	while(1) {
		if(isServer) {
			if(!secureReady(cp)) {
				DLOG("%s connection not ready",sense);
				break;
			}
			rc = sslRead(cp->secure, buf, sizeof(buf), &status);
			
			if(status == SSLSOCKET_EOF || status == SSLSOCKET_CLOSE_NOTIFY) {
				DLOG("%s EOF. rc=%d, status=%d, errno=%d",sense,rc, status,errno);
				cp->done=1;
				return 0;
			}
		}
		else {
				if(!plainReady(cp)) {
					DLOG("%s connection not ready",sense);
				break;
			}
			rc = read(cp->plain, buf, sizeof(buf));
			
			if (rc == 0) {
				DLOG("%s EOF. rc=%d, status=%d, errno=%d",sense,rc, status,errno);
				cp->done=1;
				return 0;
			}
		}
		
		if (rc < 0) {
			if (errno == EINTR || errno == EAGAIN) //continue;
			{       
				/* Gemtek add +++ */
				errno=0;
				/* Gemtek add --- */
				continue;
			}
			cp->error=1;
			perror("read error");
			return -1;
		}
		
		total+=rc;
		DLOG("%s read %d bytes",sense,rc);
		offset = 0;
		amt = rc;
		
		while (amt>0) {
			DLOG("%s writing",sense);
			if(isServer)
				rc = write(cp->plain, buf+offset, amt);
			else
				rc = sslWrite(cp->secure, buf+offset, amt, &status);
			if (rc < 0) {
				if (errno == EINTR || errno == EAGAIN) //continue;
				{
                                        /* Gemtek add +++ */
				        errno=0;
					continue;
                                        /* Gemtek add --- */
				}
				cp->error=1;
				perror("write error");
				return -1;
			}
			DLOG("%s written %d bytes. amt=%d",sense, rc, amt);
			offset += rc;
			amt -= rc;
		}
	}
	return total;
}