#include "CPStringUtils.hpp"
#include "ErrorHandling.hpp"
#include "MacSocket.h"
#include "Randomizer.h"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <timer.h>
#define kHTTPS_DNS "www.apache-ssl.org"
#define kHTTPS_Port 443
#define kHTTPS_URI "/"
OSErr MyMacSocket_IdleWaitCallback(void *inUserRefPtr);
OSErr MyMacSocket_IdleWaitCallback(void *inUserRefPtr)
{
#pragma unused(inUserRefPtr)
EventRecord theEvent;
::EventAvail(everyEvent,&theEvent);
CRandomizer *randomizer = (CRandomizer*)inUserRefPtr;
if (randomizer)
randomizer->PeriodicAction();
return(noErr);
}
void main(void)
{
OSErr errCode;
int theSocket = -1;
int theTimeout = 30;
SSL_CTX *ssl_ctx = nil;
SSL *ssl = nil;
char tempString[256];
UnsignedWide microTickCount;
CRandomizer randomizer;
printf("OpenSSL Demo by Roy Wood, roy@centricsystems.ca\n\n");
BailIfError(errCode = MacSocket_Startup());
BailIfError(errCode = MacSocket_socket(&theSocket,false,theTimeout * 60,MyMacSocket_IdleWaitCallback,&randomizer));
CopyCStrAndInsertCStrLongIntIntoCStr("%s:%ld",kHTTPS_DNS,kHTTPS_Port,tempString,sizeof(tempString));
printf("Connecting to %s....\n",tempString);
BailIfError(errCode = MacSocket_connect(theSocket,tempString));
SSL_load_error_strings();
SSLeay_add_ssl_algorithms();
ssl_ctx = SSL_CTX_new(SSLv23_client_method());
ssl = SSL_new(ssl_ctx);
SSL_set_fd(ssl,theSocket);
errCode = SSL_connect(ssl);
if (errCode < 0)
{
SetErrorMessageAndLongIntAndBail("OpenSSL: Can't initiate SSL connection, SSL_connect() = ",errCode);
}
CopyCStrToCStr("GET ",tempString,sizeof(tempString));
ConcatCStrToCStr(kHTTPS_URI,tempString,sizeof(tempString));
ConcatCStrToCStr(" HTTP/1.0\r\n\r\n",tempString,sizeof(tempString));
errCode = SSL_write(ssl,tempString,CStrLength(tempString));
if (errCode < 0)
{
SetErrorMessageAndLongIntAndBail("OpenSSL: Error writing data via ssl, SSL_write() = ",errCode);
}
for (;;)
{
char tempString[256];
int bytesRead;
bytesRead = SSL_read(ssl,tempString,sizeof(tempString) - 1);
if (bytesRead == 0 && MacSocket_RemoteEndIsClosing(theSocket))
{
break;
}
else if (bytesRead < 0)
{
SetErrorMessageAndLongIntAndBail("OpenSSL: Error reading data via ssl, SSL_read() = ",bytesRead);
}
tempString[bytesRead] = '\0';
printf("%s", tempString);
}
printf("\n\n\n");
errCode = noErr;
EXITPOINT:
if (theSocket >= 0)
{
MacSocket_close(theSocket);
}
if (ssl != nil)
{
SSL_free(ssl);
}
if (ssl_ctx != nil)
{
SSL_CTX_free(ssl_ctx);
}
if (errCode != noErr)
{
printf("An error occurred:\n");
printf("%s",GetErrorMessage());
}
MacSocket_Shutdown();
}