提交 d22870bc 编写于 作者: A Andy Polyakov

Drain unused MacOS directory.

上级 4ff2999e
/**************** BEGIN GUSI CONFIGURATION ****************************
*
* GUSI Configuration section generated by GUSI Configurator
* last modified: Wed Jan 5 20:33:51 2000
*
* This section will be overwritten by the next run of Configurator.
*/
#define GUSI_SOURCE
#include <GUSIConfig.h>
#include <sys/cdefs.h>
/* Declarations of Socket Factories */
__BEGIN_DECLS
void GUSIwithInetSockets();
void GUSIwithLocalSockets();
void GUSIwithMTInetSockets();
void GUSIwithMTTcpSockets();
void GUSIwithMTUdpSockets();
void GUSIwithOTInetSockets();
void GUSIwithOTTcpSockets();
void GUSIwithOTUdpSockets();
void GUSIwithPPCSockets();
void GUSISetupFactories();
__END_DECLS
/* Configure Socket Factories */
void GUSISetupFactories()
{
#ifdef GUSISetupFactories_BeginHook
GUSISetupFactories_BeginHook
#endif
GUSIwithInetSockets();
#ifdef GUSISetupFactories_EndHook
GUSISetupFactories_EndHook
#endif
}
/* Declarations of File Devices */
__BEGIN_DECLS
void GUSIwithDConSockets();
void GUSIwithNullSockets();
void GUSISetupDevices();
__END_DECLS
/* Configure File Devices */
void GUSISetupDevices()
{
#ifdef GUSISetupDevices_BeginHook
GUSISetupDevices_BeginHook
#endif
GUSIwithNullSockets();
#ifdef GUSISetupDevices_EndHook
GUSISetupDevices_EndHook
#endif
}
/**************** END GUSI CONFIGURATION *************************/
此差异已折叠。
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
void CopyPStrToCStr(const unsigned char *thePStr,char *theCStr,const int maxCStrLength);
void CopyPStrToPStr(const unsigned char *theSrcPStr,unsigned char *theDstPStr,const int maxDstStrLength);
void CopyCStrToCStr(const char *theSrcCStr,char *theDstCStr,const int maxDstStrLength);
void CopyCStrToPStr(const char *theSrcCStr,unsigned char *theDstPStr,const int maxDstStrLength);
void ConcatPStrToCStr(const unsigned char *thePStr,char *theCStr,const int maxCStrLength);
void ConcatPStrToPStr(const unsigned char *theSrcPStr,unsigned char *theDstPStr,const int maxDstStrLength);
void ConcatCStrToPStr(const char *theSrcCStr,unsigned char *theDstPStr,const int maxDstStrLength);
void ConcatCStrToCStr(const char *theSrcCStr,char *theDstCStr,const int maxCStrLength);
void ConcatCharToCStr(const char theChar,char *theDstCStr,const int maxCStrLength);
void ConcatCharToPStr(const char theChar,unsigned char *theDstPStr,const int maxPStrLength);
int ComparePStrs(const unsigned char *theFirstPStr,const unsigned char *theSecondPStr,const Boolean ignoreCase = true);
int CompareCStrs(const char *theFirstCStr,const char *theSecondCStr,const Boolean ignoreCase = true);
int CompareCStrToPStr(const char *theCStr,const unsigned char *thePStr,const Boolean ignoreCase = true);
Boolean CStrsAreEqual(const char *theFirstCStr,const char *theSecondCStr,const Boolean ignoreCase = true);
Boolean PStrsAreEqual(const unsigned char *theFirstCStr,const unsigned char *theSecondCStr,const Boolean ignoreCase = true);
void CopyLongIntToCStr(const long theNum,char *theCStr,const int maxCStrLength,const int numDigits = -1);
void CopyUnsignedLongIntToCStr(const unsigned long theNum,char *theCStr,const int maxCStrLength);
void ConcatLongIntToCStr(const long theNum,char *theCStr,const int maxCStrLength,const int numDigits = -1);
void CopyCStrAndConcatLongIntToCStr(const char *theSrcCStr,const long theNum,char *theDstCStr,const int maxDstStrLength);
void CopyLongIntToPStr(const long theNum,unsigned char *thePStr,const int maxPStrLength,const int numDigits = -1);
void ConcatLongIntToPStr(const long theNum,unsigned char *thePStr,const int maxPStrLength,const int numDigits = -1);
long CStrLength(const char *theCString);
long PStrLength(const unsigned char *thePString);
OSErr CopyCStrToExistingHandle(const char *theCString,Handle theHandle);
OSErr CopyLongIntToExistingHandle(const long inTheLongInt,Handle theHandle);
OSErr CopyCStrToNewHandle(const char *theCString,Handle *theHandle);
OSErr CopyPStrToNewHandle(const unsigned char *thePString,Handle *theHandle);
OSErr CopyLongIntToNewHandle(const long inTheLongInt,Handle *theHandle);
OSErr AppendCStrToHandle(const char *theCString,Handle theHandle,long *currentLength = nil,long *maxLength = nil);
OSErr AppendCharsToHandle(const char *theChars,const int numChars,Handle theHandle,long *currentLength = nil,long *maxLength = nil);
OSErr AppendPStrToHandle(const unsigned char *thePString,Handle theHandle,long *currentLength = nil);
OSErr AppendLongIntToHandle(const long inTheLongInt,Handle theHandle,long *currentLength = nil);
void ZeroMem(void *theMemPtr,const unsigned long numBytes);
char *FindCharInCStr(const char theChar,const char *theCString);
long FindCharOffsetInCStr(const char theChar,const char *theCString,const Boolean inIgnoreCase = false);
long FindCStrOffsetInCStr(const char *theCSubstring,const char *theCString,const Boolean inIgnoreCase = false);
void CopyCSubstrToCStr(const char *theSrcCStr,const int maxCharsToCopy,char *theDstCStr,const int maxDstStrLength);
void CopyCSubstrToPStr(const char *theSrcCStr,const int maxCharsToCopy,unsigned char *theDstPStr,const int maxDstStrLength);
void InsertCStrIntoCStr(const char *theSrcCStr,const int theInsertionOffset,char *theDstCStr,const int maxDstStrLength);
void InsertPStrIntoCStr(const unsigned char *theSrcPStr,const int theInsertionOffset,char *theDstCStr,const int maxDstStrLength);
OSErr InsertCStrIntoHandle(const char *theCString,Handle theHandle,const long inInsertOffset);
void CopyCStrAndInsertCStrIntoCStr(const char *theSrcCStr,const char *theInsertCStr,char *theDstCStr,const int maxDstStrLength);
void CopyCStrAndInsertCStrsLongIntsIntoCStr(const char *theSrcCStr,const char **theInsertCStrs,const long *theLongInts,char *theDstCStr,const int maxDstStrLength);
void CopyCStrAndInsert1LongIntIntoCStr(const char *theSrcCStr,const long theNum,char *theDstCStr,const int maxDstStrLength);
void CopyCStrAndInsert2LongIntsIntoCStr(const char *theSrcCStr,const long long1,const long long2,char *theDstCStr,const int maxDstStrLength);
void CopyCStrAndInsert3LongIntsIntoCStr(const char *theSrcCStr,const long long1,const long long2,const long long3,char *theDstCStr,const int maxDstStrLength);
void CopyCStrAndInsertCStrLongIntIntoCStr(const char *theSrcCStr,const char *theInsertCStr,const long theNum,char *theDstCStr,const int maxDstStrLength);
OSErr CopyCStrAndInsertCStrLongIntIntoHandle(const char *theSrcCStr,const char *theInsertCStr,const long theNum,Handle *theHandle);
OSErr CopyIndexedWordToCStr(char *theSrcCStr,int whichWord,char *theDstCStr,int maxDstCStrLength);
OSErr CopyIndexedWordToNewHandle(char *theSrcCStr,int whichWord,Handle *outTheHandle);
OSErr CopyIndexedLineToCStr(const char *theSrcCStr,int inWhichLine,int *lineEndIndex,Boolean *gotLastLine,char *theDstCStr,const int maxDstCStrLength);
OSErr CopyIndexedLineToNewHandle(const char *theSrcCStr,int inWhichLine,Handle *outNewHandle);
OSErr ExtractIntFromCStr(const char *theSrcCStr,int *outInt,Boolean skipLeadingSpaces = true);
OSErr ExtractIntFromPStr(const unsigned char *theSrcPStr,int *outInt,Boolean skipLeadingSpaces = true);
void ConvertCStrToUpperCase(char *theSrcCStr);
int CountOccurencesOfCharInCStr(const char inChar,const char *inSrcCStr);
int CountWordsInCStr(const char *inSrcCStr);
OSErr CountDigits(const char *inCStr,int *outNumIntegerDigits,int *outNumFractDigits);
void ExtractCStrItemFromCStr(const char *inSrcCStr,const char inItemDelimiter,const int inItemNumber,Boolean *foundItem,char *outDstCharPtr,const int inDstCharPtrMaxLength,const Boolean inTreatMultipleDelimsAsSingleDelim = false);
OSErr ExtractCStrItemFromCStrIntoNewHandle(const char *inSrcCStr,const char inItemDelimiter,const int inItemNumber,Boolean *foundItem,Handle *outNewHandle,const Boolean inTreatMultipleDelimsAsSingleDelim = false);
OSErr ExtractFloatFromCStr(const char *inCString,extended80 *outFloat);
OSErr CopyFloatToCStr(const extended80 *theFloat,char *theCStr,const int maxCStrLength,const int inMaxNumIntDigits = -1,const int inMaxNumFractDigits = -1);
void SkipWhiteSpace(char **ioSrcCharPtr,const Boolean inStopAtEOL = false);
#ifdef __cplusplus
}
#endif
/* ====================================================================
* Copyright (c) 1998-1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "ErrorHandling.hpp"
#include "CPStringUtils.hpp"
#ifdef __EXCEPTIONS_ENABLED__
#include "CMyException.hpp"
#endif
static char gErrorMessageBuffer[512];
char *gErrorMessage = gErrorMessageBuffer;
int gErrorMessageMaxLength = sizeof(gErrorMessageBuffer);
void SetErrorMessage(const char *theErrorMessage)
{
if (theErrorMessage != nil)
{
CopyCStrToCStr(theErrorMessage,gErrorMessage,gErrorMessageMaxLength);
}
}
void SetErrorMessageAndAppendLongInt(const char *theErrorMessage,const long theLongInt)
{
if (theErrorMessage != nil)
{
CopyCStrAndConcatLongIntToCStr(theErrorMessage,theLongInt,gErrorMessage,gErrorMessageMaxLength);
}
}
void SetErrorMessageAndCStrAndLongInt(const char *theErrorMessage,const char * theCStr,const long theLongInt)
{
if (theErrorMessage != nil)
{
CopyCStrAndInsertCStrLongIntIntoCStr(theErrorMessage,theCStr,theLongInt,gErrorMessage,gErrorMessageMaxLength);
}
}
void SetErrorMessageAndCStr(const char *theErrorMessage,const char * theCStr)
{
if (theErrorMessage != nil)
{
CopyCStrAndInsertCStrLongIntIntoCStr(theErrorMessage,theCStr,-1,gErrorMessage,gErrorMessageMaxLength);
}
}
void AppendCStrToErrorMessage(const char *theErrorMessage)
{
if (theErrorMessage != nil)
{
ConcatCStrToCStr(theErrorMessage,gErrorMessage,gErrorMessageMaxLength);
}
}
void AppendLongIntToErrorMessage(const long theLongInt)
{
ConcatLongIntToCStr(theLongInt,gErrorMessage,gErrorMessageMaxLength);
}
char *GetErrorMessage(void)
{
return gErrorMessage;
}
OSErr GetErrorMessageInNewHandle(Handle *inoutHandle)
{
OSErr errCode;
errCode = CopyCStrToNewHandle(gErrorMessage,inoutHandle);
return(errCode);
}
OSErr GetErrorMessageInExistingHandle(Handle inoutHandle)
{
OSErr errCode;
errCode = CopyCStrToExistingHandle(gErrorMessage,inoutHandle);
return(errCode);
}
OSErr AppendErrorMessageToHandle(Handle inoutHandle)
{
OSErr errCode;
errCode = AppendCStrToHandle(gErrorMessage,inoutHandle,nil);
return(errCode);
}
#ifdef __EXCEPTIONS_ENABLED__
void ThrowErrorMessageException(void)
{
ThrowDescriptiveException(gErrorMessage);
}
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef kGenericError
#define kGenericError -1
#endif
extern char *gErrorMessage;
void SetErrorMessage(const char *theErrorMessage);
void SetErrorMessageAndAppendLongInt(const char *theErrorMessage,const long theLongInt);
void SetErrorMessageAndCStrAndLongInt(const char *theErrorMessage,const char * theCStr,const long theLongInt);
void SetErrorMessageAndCStr(const char *theErrorMessage,const char * theCStr);
void AppendCStrToErrorMessage(const char *theErrorMessage);
void AppendLongIntToErrorMessage(const long theLongInt);
char *GetErrorMessage(void);
OSErr GetErrorMessageInNewHandle(Handle *inoutHandle);
OSErr GetErrorMessageInExistingHandle(Handle inoutHandle);
OSErr AppendErrorMessageToHandle(Handle inoutHandle);
#ifdef __EXCEPTIONS_ENABLED__
void ThrowErrorMessageException(void);
#endif
// A bunch of evil macros that would be unnecessary if I were always using C++ !
#define SetErrorMessageAndBailIfNil(theArg,theMessage) \
{ \
if (theArg == nil) \
{ \
SetErrorMessage(theMessage); \
errCode = kGenericError; \
goto EXITPOINT; \
} \
}
#define SetErrorMessageAndBail(theMessage) \
{ \
SetErrorMessage(theMessage); \
errCode = kGenericError; \
goto EXITPOINT; \
}
#define SetErrorMessageAndLongIntAndBail(theMessage,theLongInt) \
{ \
SetErrorMessageAndAppendLongInt(theMessage,theLongInt); \
errCode = kGenericError; \
goto EXITPOINT; \
}
#define SetErrorMessageAndLongIntAndBailIfError(theErrCode,theMessage,theLongInt) \
{ \
if (theErrCode != noErr) \
{ \
SetErrorMessageAndAppendLongInt(theMessage,theLongInt); \
errCode = theErrCode; \
goto EXITPOINT; \
} \
}
#define SetErrorMessageCStrLongIntAndBailIfError(theErrCode,theMessage,theCStr,theLongInt) \
{ \
if (theErrCode != noErr) \
{ \
SetErrorMessageAndCStrAndLongInt(theMessage,theCStr,theLongInt); \
errCode = theErrCode; \
goto EXITPOINT; \
} \
}
#define SetErrorMessageAndCStrAndBail(theMessage,theCStr) \
{ \
SetErrorMessageAndCStr(theMessage,theCStr); \
errCode = kGenericError; \
goto EXITPOINT; \
}
#define SetErrorMessageAndBailIfError(theErrCode,theMessage) \
{ \
if (theErrCode != noErr) \
{ \
SetErrorMessage(theMessage); \
errCode = theErrCode; \
goto EXITPOINT; \
} \
}
#define SetErrorMessageAndLongIntAndBailIfNil(theArg,theMessage,theLongInt) \
{ \
if (theArg == nil) \
{ \
SetErrorMessageAndAppendLongInt(theMessage,theLongInt); \
errCode = kGenericError; \
goto EXITPOINT; \
} \
}
#define BailIfError(theErrCode) \
{ \
if ((theErrCode) != noErr) \
{ \
goto EXITPOINT; \
} \
}
#define SetErrCodeAndBail(theErrCode) \
{ \
errCode = theErrCode; \
\
goto EXITPOINT; \
}
#define SetErrorCodeAndMessageAndBail(theErrCode,theMessage) \
{ \
SetErrorMessage(theMessage); \
errCode = theErrCode; \
goto EXITPOINT; \
}
#define BailNow() \
{ \
errCode = kGenericError; \
goto EXITPOINT; \
}
#ifdef __cplusplus
}
#endif
/*
* An demo illustrating how to retrieve a URI from a secure HTTP server.
*
* Author: Roy Wood
* Date: September 7, 1999
* Comments: This relies heavily on my MacSockets library.
* This project is also set up so that it expects the OpenSSL source folder (0.9.4 as I write this)
* to live in a folder called "OpenSSL-0.9.4" in this project's parent folder. For example:
*
* Macintosh HD:
* Development:
* OpenSSL-0.9.4:
* (OpenSSL sources here)
* OpenSSL Example:
* (OpenSSL example junk here)
*
*
* Also-- before attempting to compile this, make sure the aliases in "OpenSSL-0.9.4:include:openssl"
* are installed! Use the AppleScript applet in the "openssl-0.9.4" folder to do this!
*/
/* modified to seed the PRNG */
/* modified to use CRandomizer for seeding */
// Include some funky libs I've developed over time
#include "CPStringUtils.hpp"
#include "ErrorHandling.hpp"
#include "MacSocket.h"
#include "Randomizer.h"
// We use the OpenSSL implementation of SSL....
// This was a lot of work to finally get going, though you wouldn't know it by the results!
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <timer.h>
// Let's try grabbing some data from here:
#define kHTTPS_DNS "www.apache-ssl.org"
#define kHTTPS_Port 443
#define kHTTPS_URI "/"
// Forward-declare this
OSErr MyMacSocket_IdleWaitCallback(void *inUserRefPtr);
// My idle-wait callback. Doesn't do much, does it? Silly cooperative multitasking.
OSErr MyMacSocket_IdleWaitCallback(void *inUserRefPtr)
{
#pragma unused(inUserRefPtr)
EventRecord theEvent;
::EventAvail(everyEvent,&theEvent);
CRandomizer *randomizer = (CRandomizer*)inUserRefPtr;
if (randomizer)
randomizer->PeriodicAction();
return(noErr);
}
// Finally!
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());
// Create a socket-like object
BailIfError(errCode = MacSocket_socket(&theSocket,false,theTimeout * 60,MyMacSocket_IdleWaitCallback,&randomizer));
// Set up the connect string and try to connect
CopyCStrAndInsertCStrLongIntIntoCStr("%s:%ld",kHTTPS_DNS,kHTTPS_Port,tempString,sizeof(tempString));
printf("Connecting to %s....\n",tempString);
BailIfError(errCode = MacSocket_connect(theSocket,tempString));
// Init SSL stuff
SSL_load_error_strings();
SSLeay_add_ssl_algorithms();
// Pick the SSL method
// ssl_ctx = SSL_CTX_new(SSLv2_client_method());
ssl_ctx = SSL_CTX_new(SSLv23_client_method());
// ssl_ctx = SSL_CTX_new(SSLv3_client_method());
// Create an SSL thingey and try to negotiate the connection
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);
}
// Request the URI from the host
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;
// Read some bytes and dump them to the console
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");
// All done!
errCode = noErr;
EXITPOINT:
// Clean up and go home
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();
}
此差异已折叠。
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
enum
{
kMacSocket_TimeoutErr = -2
};
// Since MacSocket does busy waiting, I do a callback while waiting
typedef OSErr (*MacSocket_IdleWaitCallback)(void *);
// Call this before anything else!
OSErr MacSocket_Startup(void);
// Call this to cleanup before quitting
OSErr MacSocket_Shutdown(void);
// Call this to allocate a "socket" (reference number is returned in outSocketNum)
// Note that inDoThreadSwitching is pretty much irrelevant right now, since I ignore it
// The inTimeoutTicks parameter is applied during reads/writes of data
// The inIdleWaitCallback parameter specifies a callback which is called during busy-waiting periods
// The inUserRefPtr parameter is passed back to the idle-wait callback
OSErr MacSocket_socket(int *outSocketNum,const Boolean inDoThreadSwitching,const long inTimeoutTicks,MacSocket_IdleWaitCallback inIdleWaitCallback,void *inUserRefPtr);
// Call this to connect to an IP/DNS address
// Note that inTargetAddressAndPort is in "IP:port" format-- e.g. 10.1.1.1:123
OSErr MacSocket_connect(const int inSocketNum,char *inTargetAddressAndPort);
// Call this to listen on a port
// Since this a low-performance implementation, I allow a maximum of 1 (one!) incoming request when I listen
OSErr MacSocket_listen(const int inSocketNum,const int inPortNum);
// Call this to close a socket
OSErr MacSocket_close(const int inSocketNum);
// Call this to receive data on a socket
// Most parameters' purpose are obvious-- except maybe "inBlock" which controls whether I wait for data or return immediately
int MacSocket_recv(const int inSocketNum,void *outBuff,int outBuffLength,const Boolean inBlock);
// Call this to send data on a socket
int MacSocket_send(const int inSocketNum,const void *inBuff,int inBuffLength);
// If zero bytes were read in a call to MacSocket_recv(), it may be that the remote end has done a half-close
// This function will let you check whether that's true or not
Boolean MacSocket_RemoteEndIsClosing(const int inSocketNum);
// Call this to see if the listen has completed after a call to MacSocket_listen()
Boolean MacSocket_ListenCompleted(const int inSocketNum);
// These really aren't very useful anymore
Boolean MacSocket_LocalEndIsOpen(const int inSocketNum);
Boolean MacSocket_RemoteEndIsOpen(const int inSocketNum);
// You may wish to change the userRefPtr for a socket callback-- use this to do it
void MacSocket_SetUserRefPtr(const int inSocketNum,void *inNewRefPtr);
// Call these to get the socket's IP:port descriptor
void MacSocket_GetLocalIPAndPort(const int inSocketNum,char *outIPAndPort,const int inIPAndPortLength);
void MacSocket_GetRemoteIPAndPort(const int inSocketNum,char *outIPAndPort,const int inIPAndPortLength);
// Call this to get error info from a socket
void MacSocket_GetSocketErrorInfo(const int inSocketNum,int *outSocketErrCode,char *outSocketErrString,const int inSocketErrStringMaxLength);
#ifdef __cplusplus
}
#endif
此差异已折叠。
/*
------- Strong random data generation on a Macintosh (pre - OS X) ------
-- GENERAL: We aim to generate unpredictable bits without explicit
user interaction. A general review of the problem may be found
in RFC 1750, "Randomness Recommendations for Security", and some
more discussion, of general and Mac-specific issues has appeared
in "Using and Creating Cryptographic- Quality Random Numbers" by
Jon Callas (www.merrymeet.com/jon/usingrandom.html).
The data and entropy estimates provided below are based on my
limited experimentation and estimates, rather than by any
rigorous study, and the entropy estimates tend to be optimistic.
They should not be considered absolute.
Some of the information being collected may be correlated in
subtle ways. That includes mouse positions, timings, and disk
size measurements. Some obvious correlations will be eliminated
by the programmer, but other, weaker ones may remain. The
reliability of the code depends on such correlations being
poorly understood, both by us and by potential interceptors.
This package has been planned to be used with OpenSSL, v. 0.9.5.
It requires the OpenSSL function RAND_add.
-- OTHER WORK: Some source code and other details have been
published elsewhere, but I haven't found any to be satisfactory
for the Mac per se:
* The Linux random number generator (by Theodore Ts'o, in
drivers/char/random.c), is a carefully designed open-source
crypto random number package. It collects data from a variety
of sources, including mouse, keyboard and other interrupts.
One nice feature is that it explicitly estimates the entropy
of the data it collects. Some of its features (e.g. interrupt
timing) cannot be reliably exported to the Mac without using
undocumented APIs.
* Truerand by Don P. Mitchell and Matt Blaze uses variations
between different timing mechanisms on the same system. This
has not been tested on the Mac, but requires preemptive
multitasking, and is hardware-dependent, and can't be relied
on to work well if only one oscillator is present.
* Cryptlib's RNG for the Mac (RNDMAC.C by Peter Gutmann),
gathers a lot of information about the machine and system
environment. Unfortunately, much of it is constant from one
startup to the next. In other words, the random seed could be
the same from one day to the next. Some of the APIs are
hardware-dependent, and not all are compatible with Carbon (OS
X). Incidentally, the EGD library is based on the UNIX entropy
gathering methods in cryptlib, and isn't suitable for MacOS
either.
* Mozilla (and perhaps earlier versions of Netscape) uses the
time of day (in seconds) and an uninitialized local variable
to seed the random number generator. The time of day is known
to an outside interceptor (to within the accuracy of the
system clock). The uninitialized variable could easily be
identical between subsequent launches of an application, if it
is reached through the same path.
* OpenSSL provides the function RAND_screen(), by G. van
Oosten, which hashes the contents of the screen to generate a
seed. This is not useful for an extension or for an
application which launches at startup time, since the screen
is likely to look identical from one launch to the next. This
method is also rather slow.
* Using variations in disk drive seek times has been proposed
(Davis, Ihaka and Fenstermacher, world.std.com/~dtd/;
Jakobsson, Shriver, Hillyer and Juels,
www.bell-labs.com/user/shriver/random.html). These variations
appear to be due to air turbulence inside the disk drive
mechanism, and are very strongly unpredictable. Unfortunately
this technique is slow, and some implementations of it may be
patented (see Shriver's page above.) It of course cannot be
used with a RAM disk.
-- TIMING: On the 601 PowerPC the time base register is guaranteed
to change at least once every 10 addi instructions, i.e. 10
cycles. On a 60 MHz machine (slowest PowerPC) this translates to
a resolution of 1/6 usec. Newer machines seem to be using a 10
cycle resolution as well.
For 68K Macs, the Microseconds() call may be used. See Develop
issue 29 on the Apple developer site
(developer.apple.com/dev/techsupport/develop/issue29/minow.html)
for information on its accuracy and resolution. The code below
has been tested only on PowerPC based machines.
The time from machine startup to the launch of an application in
the startup folder has a variance of about 1.6 msec on a new G4
machine with a defragmented and optimized disk, most extensions
off and no icons on the desktop. This can be reasonably taken as
a lower bound on the variance. Most of this variation is likely
due to disk seek time variability. The distribution of startup
times is probably not entirely even or uncorrelated. This needs
to be investigated, but I am guessing that it not a majpor
problem. Entropy = log2 (1600/0.166) ~= 13 bits on a 60 MHz
machine, ~16 bits for a 450 MHz machine.
User-launched application startup times will have a variance of
a second or more relative to machine startup time. Entropy >~22
bits.
Machine startup time is available with a 1-second resolution. It
is predictable to no better a minute or two, in the case of
people who show up punctually to work at the same time and
immediately start their computer. Using the scheduled startup
feature (when available) will cause the machine to start up at
the same time every day, making the value predictable. Entropy
>~7 bits, or 0 bits with scheduled startup.
The time of day is of course known to an outsider and thus has 0
entropy if the system clock is regularly calibrated.
-- KEY TIMING: A very fast typist (120 wpm) will have a typical
inter-key timing interval of 100 msec. We can assume a variance
of no less than 2 msec -- maybe. Do good typists have a constant
rhythm, like drummers? Since what we measure is not the
key-generated interrupt but the time at which the key event was
taken off the event queue, our resolution is roughly the time
between process switches, at best 1 tick (17 msec). I therefore
consider this technique questionable and not very useful for
obtaining high entropy data on the Mac.
-- MOUSE POSITION AND TIMING: The high bits of the mouse position
are far from arbitrary, since the mouse tends to stay in a few
limited areas of the screen. I am guessing that the position of
the mouse is arbitrary within a 6 pixel square. Since the mouse
stays still for long periods of time, it should be sampled only
after it was moved, to avoid correlated data. This gives an
entropy of log2(6*6) ~= 5 bits per measurement.
The time during which the mouse stays still can vary from zero
to, say, 5 seconds (occasionally longer). If the still time is
measured by sampling the mouse during null events, and null
events are received once per tick, its resolution is 1/60th of a
second, giving an entropy of log2 (60*5) ~= 8 bits per
measurement. Since the distribution of still times is uneven,
this estimate is on the high side.
For simplicity and compatibility across system versions, the
mouse is to be sampled explicitly (e.g. in the event loop),
rather than in a time manager task.
-- STARTUP DISK TOTAL FILE SIZE: Varies typically by at least 20k
from one startup to the next, with 'minimal' computer use. Won't
vary at all if machine is started again immediately after
startup (unless virtual memory is on), but any application which
uses the web and caches information to disk is likely to cause
this much variation or more. The variation is probably not
random, but I don't know in what way. File sizes tend to be
divisible by 4 bytes since file format fields are often
long-aligned. Entropy > log2 (20000/4) ~= 12 bits.
-- STARTUP DISK FIRST AVAILABLE ALLOCATION BLOCK: As the volume
gets fragmented this could be anywhere in principle. In a
perfectly unfragmented volume this will be strongly correlated
with the total file size on the disk. With more fragmentation
comes less certainty. I took the variation in this value to be
1/8 of the total file size on the volume.
-- SYSTEM REQUIREMENTS: The code here requires System 7.0 and above
(for Gestalt and Microseconds calls). All the calls used are
Carbon-compatible.
*/
/*------------------------------ Includes ----------------------------*/
#include "Randomizer.h"
// Mac OS API
#include <Files.h>
#include <Folders.h>
#include <Events.h>
#include <Processes.h>
#include <Gestalt.h>
#include <Resources.h>
#include <LowMem.h>
// Standard C library
#include <stdlib.h>
#include <math.h>
/*---------------------- Function declarations -----------------------*/
// declared in OpenSSL/crypto/rand/rand.h
extern "C" void RAND_add (const void *buf, int num, double entropy);
unsigned long GetPPCTimer (bool is601); // Make it global if needed
// elsewhere
/*---------------------------- Constants -----------------------------*/
#define kMouseResolution 6 // Mouse position has to differ
// from the last one by this
// much to be entered
#define kMousePositionEntropy 5.16 // log2 (kMouseResolution**2)
#define kTypicalMouseIdleTicks 300.0 // I am guessing that a typical
// amount of time between mouse
// moves is 5 seconds
#define kVolumeBytesEntropy 12.0 // about log2 (20000/4),
// assuming a variation of 20K
// in total file size and
// long-aligned file formats.
#define kApplicationUpTimeEntropy 6.0 // Variance > 1 second, uptime
// in ticks
#define kSysStartupEntropy 7.0 // Entropy for machine startup
// time
/*------------------------ Function definitions ----------------------*/
CRandomizer::CRandomizer (void)
{
long result;
mSupportsLargeVolumes =
(Gestalt(gestaltFSAttr, &result) == noErr) &&
((result & (1L << gestaltFSSupports2TBVols)) != 0);
if (Gestalt (gestaltNativeCPUtype, &result) != noErr)
{
mIsPowerPC = false;
mIs601 = false;
}
else
{
mIs601 = (result == gestaltCPU601);
mIsPowerPC = (result >= gestaltCPU601);
}
mLastMouse.h = mLastMouse.v = -10; // First mouse will
// always be recorded
mLastPeriodicTicks = TickCount();
GetTimeBaseResolution ();
// Add initial entropy
AddTimeSinceMachineStartup ();
AddAbsoluteSystemStartupTime ();
AddStartupVolumeInfo ();
AddFiller ();
}
void CRandomizer::PeriodicAction (void)
{
AddCurrentMouse ();
AddNow (0.0); // Should have a better entropy estimate here
mLastPeriodicTicks = TickCount();
}
/*------------------------- Private Methods --------------------------*/
void CRandomizer::AddCurrentMouse (void)
{
Point mouseLoc;
unsigned long lastCheck; // Ticks since mouse was last
// sampled
#if TARGET_API_MAC_CARBON
GetGlobalMouse (&mouseLoc);
#else
mouseLoc = LMGetMouseLocation();
#endif
if (labs (mLastMouse.h - mouseLoc.h) > kMouseResolution/2 &&
labs (mLastMouse.v - mouseLoc.v) > kMouseResolution/2)
AddBytes (&mouseLoc, sizeof (mouseLoc),
kMousePositionEntropy);
if (mLastMouse.h == mouseLoc.h && mLastMouse.v == mouseLoc.v)
mMouseStill ++;
else
{
double entropy;
// Mouse has moved. Add the number of measurements for
// which it's been still. If the resolution is too
// coarse, assume the entropy is 0.
lastCheck = TickCount() - mLastPeriodicTicks;
if (lastCheck <= 0)
lastCheck = 1;
entropy = log2l
(kTypicalMouseIdleTicks/(double)lastCheck);
if (entropy < 0.0)
entropy = 0.0;
AddBytes (&mMouseStill, sizeof (mMouseStill), entropy);
mMouseStill = 0;
}
mLastMouse = mouseLoc;
}
void CRandomizer::AddAbsoluteSystemStartupTime (void)
{
unsigned long now; // Time in seconds since
// 1/1/1904
GetDateTime (&now);
now -= TickCount() / 60; // Time in ticks since machine
// startup
AddBytes (&now, sizeof (now), kSysStartupEntropy);
}
void CRandomizer::AddTimeSinceMachineStartup (void)
{
AddNow (1.5); // Uncertainty in app startup
// time is > 1.5 msec (for
// automated app startup).
}
void CRandomizer::AddAppRunningTime (void)
{
ProcessSerialNumber PSN;
ProcessInfoRec ProcessInfo;
ProcessInfo.processInfoLength = sizeof (ProcessInfoRec);
ProcessInfo.processName = nil;
ProcessInfo.processAppSpec = nil;
GetCurrentProcess (&PSN);
GetProcessInformation (&PSN, &ProcessInfo);
// Now add the amount of time in ticks that the current process
// has been active
AddBytes (&ProcessInfo, sizeof (ProcessInfoRec),
kApplicationUpTimeEntropy);
}
void CRandomizer::AddStartupVolumeInfo (void)
{
short vRefNum;
long dirID;
XVolumeParam pb;
OSErr err;
if (!mSupportsLargeVolumes)
return;
FindFolder (kOnSystemDisk, kSystemFolderType, kDontCreateFolder,
&vRefNum, &dirID);
pb.ioVRefNum = vRefNum;
pb.ioCompletion = 0;
pb.ioNamePtr = 0;
pb.ioVolIndex = 0;
err = PBXGetVolInfoSync (&pb);
if (err != noErr)
return;
// Base the entropy on the amount of space used on the disk and
// on the next available allocation block. A lot else might be
// unpredictable, so might as well toss the whole block in. See
// comments for entropy estimate justifications.
AddBytes (&pb, sizeof (pb),
kVolumeBytesEntropy +
log2l (((pb.ioVTotalBytes.hi - pb.ioVFreeBytes.hi)
* 4294967296.0D +
(pb.ioVTotalBytes.lo - pb.ioVFreeBytes.lo))
/ pb.ioVAlBlkSiz - 3.0));
}
/*
On a typical startup CRandomizer will come up with about 60
bits of good, unpredictable data. Assuming no more input will
be available, we'll need some more lower-quality data to give
OpenSSL the 128 bits of entropy it desires. AddFiller adds some
relatively predictable data into the soup.
*/
void CRandomizer::AddFiller (void)
{
struct
{
ProcessSerialNumber psn; // Front process serial
// number
RGBColor hiliteRGBValue; // User-selected
// highlight color
long processCount; // Number of active
// processes
long cpuSpeed; // Processor speed
long totalMemory; // Total logical memory
// (incl. virtual one)
long systemVersion; // OS version
short resFile; // Current resource file
} data;
GetNextProcess ((ProcessSerialNumber*) kNoProcess);
while (GetNextProcess (&data.psn) == noErr)
data.processCount++;
GetFrontProcess (&data.psn);
LMGetHiliteRGB (&data.hiliteRGBValue);
Gestalt (gestaltProcClkSpeed, &data.cpuSpeed);
Gestalt (gestaltLogicalRAMSize, &data.totalMemory);
Gestalt (gestaltSystemVersion, &data.systemVersion);
data.resFile = CurResFile ();
// Here we pretend to feed the PRNG completely random data. This
// is of course false, as much of the above data is predictable
// by an outsider. At this point we don't have any more
// randomness to add, but with OpenSSL we must have a 128 bit
// seed before we can start. We just add what we can, without a
// real entropy estimate, and hope for the best.
AddBytes (&data, sizeof(data), 8.0 * sizeof(data));
AddCurrentMouse ();
AddNow (1.0);
}
//------------------- LOW LEVEL ---------------------
void CRandomizer::AddBytes (void *data, long size, double entropy)
{
RAND_add (data, size, entropy * 0.125); // Convert entropy bits
// to bytes
}
void CRandomizer::AddNow (double millisecondUncertainty)
{
long time = SysTimer();
AddBytes (&time, sizeof (time), log2l (millisecondUncertainty *
mTimebaseTicksPerMillisec));
}
//----------------- TIMING SUPPORT ------------------
void CRandomizer::GetTimeBaseResolution (void)
{
#ifdef __powerc
long speed;
// gestaltProcClkSpeed available on System 7.5.2 and above
if (Gestalt (gestaltProcClkSpeed, &speed) != noErr)
// Only PowerPCs running pre-7.5.2 are 60-80 MHz
// machines.
mTimebaseTicksPerMillisec = 6000.0D;
// Assume 10 cycles per clock update, as in 601 spec. Seems true
// for later chips as well.
mTimebaseTicksPerMillisec = speed / 1.0e4D;
#else
// 68K VIA-based machines (see Develop Magazine no. 29)
mTimebaseTicksPerMillisec = 783.360D;
#endif
}
unsigned long CRandomizer::SysTimer (void) // returns the lower 32
// bit of the chip timer
{
#ifdef __powerc
return GetPPCTimer (mIs601);
#else
UnsignedWide usec;
Microseconds (&usec);
return usec.lo;
#endif
}
#ifdef __powerc
// The timebase is available through mfspr on 601, mftb on later chips.
// Motorola recommends that an 601 implementation map mftb to mfspr
// through an exception, but I haven't tested to see if MacOS actually
// does this. We only sample the lower 32 bits of the timer (i.e. a
// few minutes of resolution)
asm unsigned long GetPPCTimer (register bool is601)
{
cmplwi is601, 0 // Check if 601
bne _601 // if non-zero goto _601
mftb r3 // Available on 603 and later.
blr // return with result in r3
_601:
mfspr r3, spr5 // Available on 601 only.
// blr inserted automatically
}
#endif
// Gathers unpredictable system data to be used for generating
// random bits
#include <MacTypes.h>
class CRandomizer
{
public:
CRandomizer (void);
void PeriodicAction (void);
private:
// Private calls
void AddTimeSinceMachineStartup (void);
void AddAbsoluteSystemStartupTime (void);
void AddAppRunningTime (void);
void AddStartupVolumeInfo (void);
void AddFiller (void);
void AddCurrentMouse (void);
void AddNow (double millisecondUncertainty);
void AddBytes (void *data, long size, double entropy);
void GetTimeBaseResolution (void);
unsigned long SysTimer (void);
// System Info
bool mSupportsLargeVolumes;
bool mIsPowerPC;
bool mIs601;
// Time info
double mTimebaseTicksPerMillisec;
unsigned long mLastPeriodicTicks;
// Mouse info
long mSamplePeriod;
Point mLastMouse;
long mMouseStill;
};
-------------------------------------------------------------------
Verify server certificate
-------------------------------------------------------------------
Currently omitted from the project:
crypto/tmdiff.c
crypto/bio/bss_conn.c
crypto/bio/b_sock.c
crypto/bio/bss_acpt.c
crypto/bio/bss_log.h
-------------------------------------------------------------------
Build libraries to link with...
-------------------------------------------------------------------
Port openssl application.
-------------------------------------------------------------------
BN optimizations (currently PPC version is compiled with BN_LLONG)
-------------------------------------------------------------------
#include <MacHeaders.h>
#define B_ENDIAN
#ifdef __POWERPC__
#pragma longlong on
#endif
#if 1
#define MAC_OS_GUSI_SOURCE
#endif
#define MONOLITH
#include <MacHeaders.h>
#define B_ENDIAN
#ifdef __POWERPC__
#pragma longlong on
#endif
#if 0
#define MAC_OS_GUSI_SOURCE
#endif
#define MONOLITH
#ifndef MK1MF_BUILD
# define CFLAGS "-DB_ENDIAN"
# define PLATFORM "macos"
# define DATE "Sun Feb 27 19:44:16 MET 2000"
#endif
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册