mirror of
https://bitbucket.org/theswgsource/src-1.2.git
synced 2026-08-01 02:15:54 -04:00
Added CentralServer project
This commit is contained in:
+272
@@ -0,0 +1,272 @@
|
||||
#include "GenericApiCore.h"
|
||||
#include "GenericConnection.h"
|
||||
#include "GenericMessage.h"
|
||||
|
||||
//----------------------------------------
|
||||
//
|
||||
// WARNING: These files are NOT standard generic API files
|
||||
// They have been modified for this project.
|
||||
// Do NOT replace them with generic API files
|
||||
//
|
||||
//----------------------------------------
|
||||
|
||||
using namespace std;
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
|
||||
//----------------------------------------
|
||||
ServerTrackObject::ServerTrackObject(unsigned mapped_track, unsigned real_track, GenericConnection *con)
|
||||
: m_mappedTrack(mapped_track), m_realTrack(real_track), m_connection(con)
|
||||
//----------------------------------------
|
||||
{
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
GenericAPICore::GenericAPICore(const char *host,
|
||||
short port,
|
||||
unsigned reqTimeout,
|
||||
unsigned reconnectTimeout,
|
||||
unsigned noDataTimeoutSecs,
|
||||
unsigned noAckTimeoutSecs,
|
||||
unsigned incomingBufSizeInKB,
|
||||
unsigned outgoingBufSizeInKB,
|
||||
unsigned keepAlive,
|
||||
unsigned maxRecvMessageSizeInKB)
|
||||
: m_currTrack(0),
|
||||
m_reconnectTimeout(0),
|
||||
m_outCount(0),
|
||||
m_pendingCount(0),
|
||||
m_requestTimeout(reqTimeout),
|
||||
m_currentConnections(0), m_maxConnections(0),
|
||||
m_suspended(false),
|
||||
m_nextConnectionIndex(0)
|
||||
//----------------------------------------
|
||||
{
|
||||
GenericConnection *con = new GenericConnection(host, port, this, reconnectTimeout, noDataTimeoutSecs, noAckTimeoutSecs, incomingBufSizeInKB, outgoingBufSizeInKB, keepAlive, maxRecvMessageSizeInKB);
|
||||
m_serverConnections.push_back(con);
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
GenericAPICore::GenericAPICore(const char *game, const char *hosts[],
|
||||
const short port[],
|
||||
unsigned arraySize,
|
||||
unsigned reqTimeout,
|
||||
unsigned reconnectTimeout,
|
||||
unsigned noDataTimeoutSecs,
|
||||
unsigned noAckTimeoutSecs,
|
||||
unsigned incomingBufSizeInKB,
|
||||
unsigned outgoingBufSizeInKB,
|
||||
unsigned keepAlive,
|
||||
unsigned maxRecvMessageSizeInKB)
|
||||
: m_currTrack(0),
|
||||
m_reconnectTimeout(0),
|
||||
m_outCount(0),
|
||||
m_pendingCount(0),
|
||||
m_requestTimeout(reqTimeout),
|
||||
m_currentConnections(0), m_maxConnections(0),
|
||||
m_suspended(false),
|
||||
m_nextConnectionIndex(0),
|
||||
m_game(game)
|
||||
//----------------------------------------
|
||||
{
|
||||
for (unsigned i=0; i<arraySize; i++)
|
||||
{
|
||||
GenericConnection *con = new GenericConnection(hosts[i], port[i], this, reconnectTimeout, noDataTimeoutSecs, noAckTimeoutSecs, incomingBufSizeInKB, outgoingBufSizeInKB, keepAlive, maxRecvMessageSizeInKB);
|
||||
m_serverConnections.push_back(con);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//----------------------------------------
|
||||
GenericAPICore::~GenericAPICore()
|
||||
//----------------------------------------
|
||||
{
|
||||
for (std::vector<GenericConnection *>::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++)
|
||||
{
|
||||
GenericConnection *con = *conIter;
|
||||
delete con;
|
||||
}
|
||||
m_serverConnections.clear();
|
||||
|
||||
for(map<unsigned, GenericResponse *>::iterator iter = m_pending.begin(); iter != m_pending.end(); ++iter)
|
||||
{
|
||||
delete (*iter).second;
|
||||
}
|
||||
|
||||
m_pending.empty();
|
||||
|
||||
while(m_outCount > 0)
|
||||
{
|
||||
delete m_outboundQueue.front().second;
|
||||
delete m_outboundQueue.front().first;
|
||||
m_outboundQueue.pop();
|
||||
--m_outCount;
|
||||
}
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
unsigned GenericAPICore::submitRequest(GenericRequest *req, GenericResponse *res)
|
||||
//----------------------------------------
|
||||
{
|
||||
++m_outCount;
|
||||
if(m_currTrack == 0)
|
||||
{
|
||||
m_currTrack++;
|
||||
}
|
||||
req->setTrack(m_currTrack);
|
||||
res->setTrack(m_currTrack);
|
||||
time_t timeout = time(NULL) + m_requestTimeout;
|
||||
|
||||
req->setTimeout(timeout);
|
||||
res->setTimeout(timeout);
|
||||
|
||||
m_outboundQueue.push(pair<GenericRequest *, GenericResponse *>(req, res));
|
||||
return(m_currTrack++);
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
void GenericAPICore::process()
|
||||
//----------------------------------------
|
||||
{
|
||||
GenericRequest *req;
|
||||
GenericResponse *res;
|
||||
|
||||
if (!m_suspended)
|
||||
{
|
||||
// Process timeout on pending requests
|
||||
while((m_outCount > 0) && ((req = m_outboundQueue.front().first)->getTimeout() <= time(NULL)))
|
||||
{
|
||||
--m_outCount;
|
||||
res = m_outboundQueue.front().second;
|
||||
m_outboundQueue.pop();
|
||||
|
||||
responseCallback(res);
|
||||
delete res;
|
||||
delete req;
|
||||
}
|
||||
|
||||
// Process timeout on pending responses
|
||||
while((m_pendingCount > 0) && ((res = (*m_pending.begin()).second)->getTimeout() <= time(NULL)))
|
||||
{
|
||||
--m_pendingCount;
|
||||
m_pending.erase(m_pending.begin());
|
||||
responseCallback(res);
|
||||
delete res;
|
||||
}
|
||||
|
||||
while(m_outCount > 0)
|
||||
{
|
||||
pair<GenericRequest *, GenericResponse *> out_pair = m_outboundQueue.front();
|
||||
req = out_pair.first;
|
||||
res = out_pair.second;
|
||||
GenericConnection *con = NULL;
|
||||
if (req->getMappedServerTrack() == 0) // request has no originating "owner" server
|
||||
{
|
||||
con = getNextActiveConnection(); // it does not matter which server we send this to
|
||||
}
|
||||
else
|
||||
{
|
||||
ServerTrackObject *stobj = findServer(req->getMappedServerTrack());
|
||||
if (stobj)
|
||||
{
|
||||
con = stobj->getConnection(); // the server connection to respond to
|
||||
req->setServerTrack(stobj->getRealServerTrack()); // map server track back to REAL server track
|
||||
//printf("\nUnmapping %d to %d", stobj->getMappedServerTrack(), req->getMappedServerTrack()); //debug
|
||||
delete stobj;
|
||||
}
|
||||
}
|
||||
|
||||
if (con != NULL)
|
||||
{
|
||||
Base::ByteStream msg;
|
||||
req->pack(msg);
|
||||
con->Send(msg);
|
||||
m_pending.insert(pair<unsigned, GenericResponse *>(res->getTrack(), res));
|
||||
--m_outCount;
|
||||
++m_pendingCount;
|
||||
m_outboundQueue.pop();
|
||||
delete req;
|
||||
}
|
||||
else
|
||||
{
|
||||
//no active connections
|
||||
break; //from while loop
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
for (std::vector<GenericConnection *>::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++)
|
||||
{
|
||||
GenericConnection *con = *conIter;
|
||||
con->process();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//----------------------------------------
|
||||
GenericConnection *GenericAPICore::getNextActiveConnection()
|
||||
//----------------------------------------
|
||||
{
|
||||
unsigned startIndex = m_nextConnectionIndex;
|
||||
unsigned maxIndex = m_serverConnections.size() - 1;
|
||||
|
||||
GenericConnection *con = NULL;
|
||||
|
||||
//loop until we find an active connection, or until we get back
|
||||
// to where we started
|
||||
do
|
||||
{
|
||||
if (m_serverConnections[m_nextConnectionIndex]->isConnected())
|
||||
{
|
||||
con = m_serverConnections[m_nextConnectionIndex];
|
||||
if (m_nextConnectionIndex == maxIndex)
|
||||
m_nextConnectionIndex = 0;
|
||||
else
|
||||
m_nextConnectionIndex++;
|
||||
|
||||
}
|
||||
else if (++m_nextConnectionIndex > maxIndex)
|
||||
{
|
||||
//went past end of vector, start back at 0
|
||||
m_nextConnectionIndex = 0;
|
||||
}
|
||||
}while (con == NULL && m_nextConnectionIndex != startIndex);
|
||||
|
||||
return con;
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
void GenericAPICore::countOpenConnections()
|
||||
//----------------------------------------
|
||||
{
|
||||
m_currentConnections = 0;
|
||||
m_maxConnections = m_serverConnections.size();
|
||||
|
||||
for (std::vector<GenericConnection *>::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++)
|
||||
{
|
||||
GenericConnection *con = *conIter;
|
||||
if (con->isConnected())
|
||||
++m_currentConnections;
|
||||
}
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
ServerTrackObject *GenericAPICore::findServer(unsigned server_track)
|
||||
//----------------------------------------
|
||||
{
|
||||
std::map<unsigned, ServerTrackObject *>::iterator iter = m_serverTracks.find(server_track);
|
||||
if (iter == m_serverTracks.end())
|
||||
return NULL;
|
||||
ServerTrackObject *stobj = (*iter).second;
|
||||
m_serverTracks.erase(server_track);
|
||||
return stobj;
|
||||
}
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#if !defined (GENERICAPICORE_H_)
|
||||
#define GENERICAPICORE_H_
|
||||
|
||||
//----------------------------------------
|
||||
//
|
||||
// WARNING: These files are NOT standard generic API files
|
||||
// They have been modified for this project.
|
||||
// Do NOT replace them with generic API files
|
||||
//
|
||||
//----------------------------------------
|
||||
|
||||
#pragma warning (disable: 4786)
|
||||
|
||||
#include <map>
|
||||
#include <queue>
|
||||
#include <time.h>
|
||||
#include "Base/Archive.h"
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
class GenericRequest;
|
||||
class GenericResponse;
|
||||
class GenericConnection;
|
||||
|
||||
//----------------------------------------------
|
||||
class ServerTrackObject
|
||||
//----------------------------------------------
|
||||
{
|
||||
public:
|
||||
ServerTrackObject(unsigned mapped_track, unsigned real_track, GenericConnection *con);
|
||||
~ServerTrackObject() { }
|
||||
|
||||
inline GenericConnection *getConnection() { return m_connection; }
|
||||
inline unsigned getRealServerTrack() { return m_realTrack; }
|
||||
inline unsigned getMappedServerTrack() { return m_mappedTrack; }
|
||||
|
||||
private:
|
||||
unsigned m_mappedTrack;
|
||||
unsigned m_realTrack;
|
||||
GenericConnection *m_connection;
|
||||
};
|
||||
|
||||
//----------------------------------------------
|
||||
class GenericAPICore
|
||||
//----------------------------------------------
|
||||
{
|
||||
public:
|
||||
friend class GenericConnection;
|
||||
|
||||
GenericAPICore::GenericAPICore(const char *host,
|
||||
short port,
|
||||
unsigned reqTimeout,
|
||||
unsigned reconnectTimeout,
|
||||
unsigned noDataTimeoutSecs = 5,
|
||||
unsigned noAckTimeoutSecs = 5,
|
||||
unsigned incomingBufSizeInKB = 32,
|
||||
unsigned outgoingBufSizeInKB = 32,
|
||||
unsigned keepAlive = 1,
|
||||
unsigned maxRecvMessageSizeInKB = 0);
|
||||
|
||||
/**
|
||||
* NOTE: arraySize must be actual size of host and port arrays.
|
||||
* ALSO: cannot specify a 0 array size.
|
||||
*/
|
||||
GenericAPICore(const char *game, const char *hosts[],
|
||||
const short port[],
|
||||
unsigned arraySize,
|
||||
unsigned reqTimeout,
|
||||
unsigned reconnectTimeout,
|
||||
unsigned noDataTimeoutSecs = 5,
|
||||
unsigned noAckTimeoutSecs = 5,
|
||||
unsigned incomingBufSizeInKB = 32,
|
||||
unsigned outgoingBufSizeInKB = 32,
|
||||
unsigned keepAlive = 1,
|
||||
unsigned maxRecvMessageSizeInKB = 0);
|
||||
|
||||
virtual ~GenericAPICore();
|
||||
|
||||
void process();
|
||||
virtual void responseCallback(short type, Base::ByteStream::ReadIterator &iter, GenericConnection *con) = 0;
|
||||
virtual void responseCallback(GenericResponse *R) = 0;
|
||||
|
||||
virtual void OnDisconnect(GenericConnection *con) = 0;
|
||||
virtual void OnConnect(GenericConnection *con) = 0;
|
||||
|
||||
void countOpenConnections();
|
||||
ServerTrackObject *findServer(unsigned server_track);
|
||||
|
||||
|
||||
void suspendProcessing() { m_suspended = true; }
|
||||
void resumeProcessing() { m_suspended = false; }
|
||||
unsigned submitRequest(GenericRequest *req, GenericResponse *res);
|
||||
GenericConnection *getNextActiveConnection();
|
||||
std::string &getGameCode() { return m_game; }
|
||||
void addIdentifier(std::string id) { m_gameIdentifiers.push_back(id);}
|
||||
|
||||
protected:
|
||||
std::vector<GenericConnection *> m_serverConnections;
|
||||
std::map<unsigned, GenericResponse *> m_pending;
|
||||
std::queue<std::pair<GenericRequest *, GenericResponse *> > m_outboundQueue;
|
||||
unsigned m_currTrack;
|
||||
time_t m_reconnectTimeout;
|
||||
unsigned m_outCount;
|
||||
unsigned m_pendingCount;
|
||||
unsigned m_requestTimeout;
|
||||
unsigned m_currentConnections; // number currently connected
|
||||
unsigned m_maxConnections; // number that should be connected
|
||||
std::map<unsigned, ServerTrackObject *> m_serverTracks;
|
||||
std::vector<std::string> m_gameIdentifiers;
|
||||
|
||||
private:
|
||||
bool m_suspended;
|
||||
unsigned m_nextConnectionIndex;
|
||||
std::string m_game;
|
||||
};
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
#endif
|
||||
BIN
Binary file not shown.
+218
@@ -0,0 +1,218 @@
|
||||
#include "GenericApiCore.h"
|
||||
#include "GenericConnection.h"
|
||||
#include "GenericMessage.h"
|
||||
#include "AuctionTransferAPICore.h"
|
||||
|
||||
//----------------------------------------
|
||||
//
|
||||
// WARNING: These files are NOT standard generic API files
|
||||
// They have been modified for this project.
|
||||
// Do NOT replace them with generic API files
|
||||
//
|
||||
//----------------------------------------
|
||||
|
||||
#define REQUEST_SET_API 0
|
||||
#define GAME_RESOURCE 1
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
using namespace std;
|
||||
using namespace Base;
|
||||
|
||||
GenericConnection::GenericConnection(const char *host, short port, GenericAPICore *apiCore, unsigned reconnectTimeout, unsigned noDataTimeoutSecs, unsigned, unsigned incomingBufSizeInKB, unsigned outgoingBufSizeInKB, unsigned keepAlive, unsigned maxRecvMessageSizeInKB)
|
||||
: m_bConnected(CON_NONE),
|
||||
m_apiCore(apiCore),
|
||||
m_con(NULL),
|
||||
m_host(host),
|
||||
m_port(port),
|
||||
m_lastTrack(123455), //random choice != 1
|
||||
m_conState(CON_DISCONNECT),
|
||||
m_reconnectTimeout(reconnectTimeout)
|
||||
{
|
||||
TcpManager::TcpParams params;
|
||||
|
||||
params.incomingBufferSize = incomingBufSizeInKB * 1024;
|
||||
params.outgoingBufferSize = outgoingBufSizeInKB * 1024;
|
||||
params.maxConnections = 1;
|
||||
params.port = 0;
|
||||
params.maxRecvMessageSize = maxRecvMessageSizeInKB*1024;
|
||||
params.keepAliveDelay = keepAlive * 1000;
|
||||
params.noDataTimeout = noDataTimeoutSecs * 1000;
|
||||
//params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000;
|
||||
|
||||
m_manager = new TcpManager(params);
|
||||
}
|
||||
|
||||
GenericConnection::~GenericConnection()
|
||||
{
|
||||
if(m_con)
|
||||
{
|
||||
m_con->SetHandler(NULL);
|
||||
m_con->Disconnect();//don't worry about onterminated being called, we've set it's handler to null, so it wont
|
||||
m_con->Release();
|
||||
}
|
||||
|
||||
m_manager->Release();
|
||||
}
|
||||
|
||||
void GenericConnection::disconnect()
|
||||
{
|
||||
if (m_con)
|
||||
{
|
||||
m_con->Disconnect();
|
||||
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
|
||||
m_con = NULL;
|
||||
}
|
||||
m_conState = CON_DISCONNECT;
|
||||
m_bConnected = CON_NONE;
|
||||
}
|
||||
|
||||
void GenericConnection::OnTerminated(TcpConnection *)
|
||||
{
|
||||
// m_apiCore->OnDisconnect(m_host.c_str(), m_port);
|
||||
m_apiCore->OnDisconnect(this);
|
||||
if(m_con)
|
||||
{
|
||||
m_con->Release();
|
||||
m_con = NULL;
|
||||
}
|
||||
m_conState = CON_DISCONNECT;
|
||||
m_bConnected = CON_NONE;
|
||||
}
|
||||
|
||||
void GenericConnection::OnRoutePacket(TcpConnection *, const unsigned char *data, int dataLen)
|
||||
{
|
||||
short type;
|
||||
unsigned track;
|
||||
|
||||
ByteStream msg(data, dataLen);
|
||||
ByteStream::ReadIterator iter = msg.begin();
|
||||
|
||||
get(iter, type);
|
||||
get(iter, track);
|
||||
GenericResponse *res = NULL;
|
||||
|
||||
// the following if block is a temporary fix that prevents
|
||||
// a crash with a game team in which they occasionally find
|
||||
// themselves receiving a dupe track in consecutive calls to
|
||||
// OnRoutePacket (which then leads to a callback being called
|
||||
// twice and data being invalid on the second call -> crash!).
|
||||
// TODO: resolve this BK
|
||||
/* if (track != 0 &&
|
||||
track == m_lastTrack)
|
||||
{
|
||||
printf("!!! ERROR !!! Got a duplicate track ID %u\n", track);
|
||||
return;
|
||||
}
|
||||
m_lastTrack = track;
|
||||
*/
|
||||
// end temporary fix.
|
||||
|
||||
if(track == 0) // notification message from the server, not as a response to a request from this API
|
||||
{
|
||||
if (type == ATGAME_REQUEST_CONNECT)
|
||||
{ // this is a special case, for when we have identified our game code to server
|
||||
m_bConnected = CON_IDENTIFIED;
|
||||
m_apiCore->OnConnect(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_apiCore->responseCallback(type, iter, this);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
map<unsigned, GenericResponse *>::iterator mapIter = m_apiCore->m_pending.find(track);
|
||||
|
||||
if(mapIter != m_apiCore->m_pending.end())
|
||||
{
|
||||
res = (*mapIter).second;
|
||||
iter = msg.begin();
|
||||
res->unpack(iter);
|
||||
m_apiCore->responseCallback(res);
|
||||
m_apiCore->m_pendingCount--;
|
||||
m_apiCore->m_pending.erase(mapIter);
|
||||
delete res;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void GenericConnection::process()
|
||||
{
|
||||
switch(m_conState)
|
||||
{
|
||||
case CON_DISCONNECT:
|
||||
// create connection object, attempting to connect and
|
||||
// checking for connection in next state, CON_NEGOTIATE
|
||||
m_con = m_manager->EstablishConnection(m_host.c_str(), m_port);
|
||||
if(m_con)
|
||||
{
|
||||
m_con->SetHandler(this);
|
||||
m_conState = CON_NEGOTIATE;
|
||||
m_conTimeout = time(NULL) + m_reconnectTimeout;
|
||||
}
|
||||
break;
|
||||
case CON_NEGOTIATE:
|
||||
// check for connection
|
||||
|
||||
if(m_con->GetStatus() == TcpConnection::StatusConnected)
|
||||
{
|
||||
// we're connected
|
||||
m_conState = CON_CONNECT;
|
||||
m_bConnected = CON_CONNECTED;
|
||||
// instead of calling OnConnect() right now, we are going to submit a connection packet
|
||||
// identifying us
|
||||
// m_apiCore->OnConnect(this);
|
||||
Base::ByteStream msg;
|
||||
put(msg, (short)REQUEST_SET_API);
|
||||
put(msg, (unsigned)0); // track
|
||||
put(msg, (unsigned)API_VERSION_CODE);
|
||||
put(msg, GAME_RESOURCE); // identify us as a game connection resource
|
||||
|
||||
// now add in the game identifiers
|
||||
put(msg, (unsigned)m_apiCore->m_gameIdentifiers.size()); // number of strings to read
|
||||
for(unsigned index = 0; index < m_apiCore->m_gameIdentifiers.size(); index++)
|
||||
put(msg, std::string(m_apiCore->m_gameIdentifiers[index]));
|
||||
Send(msg);
|
||||
}
|
||||
else if(time(NULL) > m_conTimeout)
|
||||
{
|
||||
// we did not connect
|
||||
m_con->Disconnect();
|
||||
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
|
||||
m_con = NULL;
|
||||
m_conState = CON_DISCONNECT;
|
||||
m_bConnected = CON_NONE;
|
||||
}
|
||||
break;
|
||||
case CON_CONNECT:
|
||||
// do nothing
|
||||
break;
|
||||
default:
|
||||
// this should not occur, but we revert to CON_DISCONNECT if it does
|
||||
m_conState = CON_DISCONNECT;
|
||||
m_bConnected = CON_NONE;
|
||||
if (m_con)
|
||||
{
|
||||
m_con->Disconnect();
|
||||
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
|
||||
m_con = NULL;
|
||||
}
|
||||
}
|
||||
m_manager->GiveTime();
|
||||
}
|
||||
|
||||
void GenericConnection::Send(Base::ByteStream &msg)
|
||||
{
|
||||
if(m_con && m_con->GetStatus() == TcpConnection::StatusConnected)
|
||||
{
|
||||
m_con->Send((const char *)msg.getBuffer(), msg.getSize());
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
#if !defined (GENERICCONNECTION_H_)
|
||||
#define GENERICCONNECTION_H_
|
||||
|
||||
//----------------------------------------
|
||||
//
|
||||
// WARNING: These files are NOT standard generic API files
|
||||
// They have been modified for this project.
|
||||
// Do NOT replace them with generic API files
|
||||
//
|
||||
//----------------------------------------
|
||||
|
||||
#include <Base/Archive.h>
|
||||
#include <TcpLibrary/TcpManager.h>
|
||||
#include <TcpLibrary/TcpConnection.h>
|
||||
#include <TcpLibrary/TcpHandlers.h>
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
static const unsigned API_VERSION_CODE = 1;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// these will never change. They will also be in the enumeration. These are defined here to
|
||||
// prevent us from having to re-compile and include the enumeration file in this generic code.
|
||||
#define ATGAME_REQUEST_CONNECT 0
|
||||
#define ATWEB_REQUEST_CONNECT 10000
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
enum eConState
|
||||
{
|
||||
CON_DISCONNECT,
|
||||
CON_NEGOTIATE,
|
||||
CON_CONNECT
|
||||
};
|
||||
enum eConnectStatus
|
||||
{
|
||||
CON_NONE,
|
||||
CON_CONNECTED,
|
||||
CON_IDENTIFIED
|
||||
};
|
||||
|
||||
class GenericConnection : public TcpConnectionHandler
|
||||
{
|
||||
public:
|
||||
GenericConnection(const char *host,
|
||||
short port,
|
||||
GenericAPICore *apiCore,
|
||||
unsigned reconnectTimeout,
|
||||
unsigned noDataTimeoutSecs = 5,
|
||||
unsigned noAckTimeoutSecs = 5,
|
||||
unsigned incomingBufSizeInKB = 32,
|
||||
unsigned outgoingBufSizeInKB = 32,
|
||||
unsigned keepAlive = 1,
|
||||
unsigned maxRecvMessageSizeInKB = 0);
|
||||
|
||||
virtual ~GenericConnection();
|
||||
|
||||
virtual void OnRoutePacket(TcpConnection *con, const unsigned char *data, int dataLen);
|
||||
virtual void OnTerminated(TcpConnection *con);
|
||||
void Send(Base::ByteStream &msg);
|
||||
inline const char *getHost() const { return m_host.c_str(); }
|
||||
inline const short getPort() const { return m_port; }
|
||||
|
||||
inline eConnectStatus isConnected() { return m_bConnected; }
|
||||
void disconnect();
|
||||
void process();
|
||||
|
||||
private:
|
||||
eConnectStatus m_bConnected;
|
||||
GenericAPICore *m_apiCore;
|
||||
TcpManager *m_manager;
|
||||
TcpConnection *m_con;
|
||||
std::string m_host;
|
||||
short m_port;
|
||||
unsigned m_lastTrack;
|
||||
eConState m_conState;
|
||||
time_t m_conTimeout;
|
||||
unsigned m_reconnectTimeout;
|
||||
};
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif
|
||||
BIN
Binary file not shown.
+44
@@ -0,0 +1,44 @@
|
||||
#include "GenericMessage.h"
|
||||
|
||||
//----------------------------------------
|
||||
//
|
||||
// WARNING: These files are NOT standard generic API files
|
||||
// They have been modified for this project.
|
||||
// Do NOT replace them with generic API files
|
||||
//
|
||||
//----------------------------------------
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
|
||||
using namespace Base;
|
||||
|
||||
//-------------------------------------------
|
||||
GenericRequest::GenericRequest(short type, unsigned server_track)
|
||||
: m_type(type), m_server_track(server_track)
|
||||
//-------------------------------------------
|
||||
{
|
||||
}
|
||||
|
||||
//-------------------------------------------
|
||||
GenericResponse::GenericResponse(short type, unsigned result, void *user)
|
||||
: m_type(type), m_result(result), m_user(user)
|
||||
//-------------------------------------------
|
||||
{
|
||||
}
|
||||
|
||||
//-----------------------------------------
|
||||
void GenericResponse::unpack(ByteStream::ReadIterator &iter)
|
||||
//-----------------------------------------
|
||||
{
|
||||
get(iter, m_type);
|
||||
get(iter, m_track);
|
||||
get(iter, m_result);
|
||||
}
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
#if !defined (GENERICMESSAGE_H_)
|
||||
#define GENERICMESSAGE_H_
|
||||
|
||||
//----------------------------------------
|
||||
//
|
||||
// WARNING: These files are NOT standard generic API files
|
||||
// They have been modified for this project.
|
||||
// Do NOT replace them with generic API files
|
||||
//
|
||||
//----------------------------------------
|
||||
|
||||
#include <time.h>
|
||||
#include <Base/Archive.h>
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
//-------------------------------------------
|
||||
class GenericRequest
|
||||
//-------------------------------------------
|
||||
{
|
||||
public:
|
||||
GenericRequest(short type, unsigned server_track = 0);
|
||||
virtual ~GenericRequest() {};
|
||||
|
||||
virtual void pack(Base::ByteStream &msg) = 0;
|
||||
short getType() const { return m_type; }
|
||||
void setTimeout(time_t t) { m_timeout = t; }
|
||||
time_t getTimeout() { return m_timeout; }
|
||||
void setTrack(unsigned t) { m_track = t; }
|
||||
unsigned getTrack() const { return m_track; }
|
||||
inline const unsigned getMappedServerTrack() const { return m_server_track; }
|
||||
inline void setServerTrack(unsigned track) { m_server_track = track; }
|
||||
|
||||
protected:
|
||||
short m_type;
|
||||
unsigned m_track;
|
||||
time_t m_timeout;
|
||||
unsigned m_server_track;
|
||||
};
|
||||
|
||||
// Basic response message from server. In the case that this response to a request
|
||||
// submitted from this API, the response would have been generated at request submission
|
||||
// time, and the timeout value filled in appropriatly
|
||||
//-------------------------------------------
|
||||
class GenericResponse
|
||||
//-------------------------------------------
|
||||
{
|
||||
public:
|
||||
GenericResponse(short type, unsigned result, void *user);
|
||||
virtual ~GenericResponse() {};
|
||||
virtual void unpack(Base::ByteStream::ReadIterator &iter);
|
||||
|
||||
short getType() const { return m_type; }
|
||||
void setTimeout(time_t t) { m_timeout = t; }
|
||||
time_t getTimeout() { return m_timeout; }
|
||||
void setTrack(unsigned t) { m_track = t; }
|
||||
unsigned getTrack() const { return m_track; }
|
||||
unsigned getResult() const { return m_result; }
|
||||
void setResult(unsigned res) { m_result = res; }
|
||||
void * getUser() const { return m_user; }
|
||||
protected:
|
||||
short m_type;
|
||||
unsigned m_track;
|
||||
unsigned m_result;
|
||||
void *m_user;
|
||||
time_t m_timeout;
|
||||
};
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
#endif
|
||||
BIN
Binary file not shown.
+194
@@ -0,0 +1,194 @@
|
||||
#include "AuctionTransferAPI.h"
|
||||
#include "AuctionTransferAPICore.h"
|
||||
#include "Request.h"
|
||||
#include "Response.h"
|
||||
#include "zip/GZipHelper.h"
|
||||
|
||||
#define DEFAULT_HOST "sdt-auctionsys1"
|
||||
#define DEFAULT_PORT 5901
|
||||
#define DEFAULT_IDENTIFIER "GAME+UNKNOWN"
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
namespace AuctionTransfer
|
||||
{
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
AuctionTransferAPI::AuctionTransferAPI(const char *hostName[], const short port[], int count, const char *identifier[], unsigned identifierCount, unsigned reqTimeout, unsigned maxRecvMessageSizeInKB)
|
||||
{
|
||||
m_apiCore = new AuctionTransferAPICore(hostName, port, count, this, identifier, identifierCount, reqTimeout, maxRecvMessageSizeInKB);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
AuctionTransferAPI::AuctionTransferAPI(const char *hostNames, const char *identifiers)
|
||||
{
|
||||
std::vector<const char *> hostArray;
|
||||
std::vector<const char *> identifierArray;
|
||||
std::vector<short> portArray;
|
||||
char hostConfig[4096];
|
||||
char identifierConfig[4096];
|
||||
if (hostNames == NULL)
|
||||
hostNames = DEFAULT_HOST;
|
||||
if(identifiers == NULL)
|
||||
identifiers = DEFAULT_IDENTIFIER;
|
||||
|
||||
// parse the hosts and ports out :
|
||||
strncpy(hostConfig, hostNames, 4096); hostConfig[4095] = 0;
|
||||
char *ptr;
|
||||
if ((ptr = strtok(hostConfig, " ")) != 0)
|
||||
{
|
||||
do
|
||||
{
|
||||
char * host = ptr;
|
||||
char * portStr = strchr(host, ':');
|
||||
unsigned short port = DEFAULT_PORT;
|
||||
if (portStr)
|
||||
{
|
||||
*portStr++ = 0;
|
||||
port = (short)atoi(portStr);
|
||||
}
|
||||
|
||||
if (::strlen(host) && port)
|
||||
{
|
||||
hostArray.push_back(host);
|
||||
portArray.push_back(port);
|
||||
}
|
||||
}
|
||||
while ((ptr = strtok(NULL, " ")) != NULL);
|
||||
}
|
||||
|
||||
strncpy(identifierConfig, identifiers, 4096); identifierConfig[4095] = 0;
|
||||
// parse the identifiers out
|
||||
if ((ptr = strtok(identifierConfig, ";")) != 0)
|
||||
{
|
||||
do
|
||||
{
|
||||
char * identifier = ptr;
|
||||
if (::strlen(identifier))
|
||||
{
|
||||
identifierArray.push_back(identifier);
|
||||
}
|
||||
}
|
||||
while ((ptr = strtok(NULL, ";")) != NULL);
|
||||
}
|
||||
|
||||
if (hostArray.empty())
|
||||
{
|
||||
hostArray.push_back(DEFAULT_HOST);
|
||||
portArray.push_back(DEFAULT_PORT);
|
||||
}
|
||||
if(identifierArray.empty())
|
||||
identifierArray.push_back(DEFAULT_IDENTIFIER);
|
||||
|
||||
m_apiCore = new AuctionTransferAPICore(&hostArray[0], &portArray[0], hostArray.size(), this, &identifierArray[0], identifierArray.size());
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
AuctionTransferAPI::~AuctionTransferAPI()
|
||||
{
|
||||
if( m_apiCore)
|
||||
delete m_apiCore;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
void AuctionTransferAPI::process()
|
||||
{
|
||||
m_apiCore->process();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
// Calls and replies
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::replyReceiveAbortTransaction(unsigned trackingNumber, unsigned responseCode, void *user)
|
||||
{
|
||||
ReplyRequest *req = new ReplyRequest( GAME_REPLY_RECEIVE_ABORT, trackingNumber, responseCode );
|
||||
return m_apiCore->submitRequest( req, new CommonResponse( GAME_REPLY_RECEIVE_ABORT, user ));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::replyReceiveCommitTransaction(unsigned trackingNumber, unsigned responseCode, void *user)
|
||||
{
|
||||
ReplyRequest *req = new ReplyRequest( GAME_REPLY_RECEIVE_COMMIT, trackingNumber, responseCode );
|
||||
return m_apiCore->submitRequest( req, new CommonResponse( GAME_REPLY_RECEIVE_COMMIT, user ));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::replyReceivePrepareTransaction(unsigned trackingNumber, unsigned responseCode, void *user)
|
||||
{
|
||||
ReplyRequest *req = new ReplyRequest( GAME_REPLY_RECEIVE_PREPARE_TRANSACTION, trackingNumber, responseCode );
|
||||
return m_apiCore->submitRequest( req, new CommonResponse( GAME_REPLY_RECEIVE_PREPARE_TRANSACTION, user ));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::sendAbortTransaction(long long transactionID, void *user)
|
||||
{
|
||||
CommonRequest *req = new CommonRequest( GAME_REQUEST_SEND_ABORT, 0, transactionID );
|
||||
return m_apiCore->submitRequest( req, new CommonResponse( GAME_REQUEST_SEND_ABORT, user ));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::sendCommitTransaction(long long transactionID, void *user)
|
||||
{
|
||||
CommonRequest *req = new CommonRequest( GAME_REQUEST_SEND_COMMIT, 0, transactionID );
|
||||
return m_apiCore->submitRequest( req, new CommonResponse( GAME_REQUEST_SEND_COMMIT, user ));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::sendPrepareTransaction(const char *serverIdentifier, long long transactionID, unsigned stationID, unsigned characterID, long long assetID, const char *xmlAsset, void *user, bool compress)
|
||||
{
|
||||
RequestTypes requestEnum = GAME_REQUEST_SEND_PREPARE_TRANSACTION;
|
||||
GenericRequest *req = NULL;
|
||||
if( compress )
|
||||
{
|
||||
requestEnum = GAME_REQUEST_SEND_PREPARE_TRANSACTION_COMPRESSED;
|
||||
// compress and create the request here
|
||||
char *data = (char *)xmlAsset;
|
||||
CA2GZIP zippedData(data, strlen(xmlAsset));
|
||||
req = new SendPrepareCompressedRequest( requestEnum, 0, serverIdentifier, transactionID, stationID, characterID, assetID, zippedData.pgzip, zippedData.Length );
|
||||
}
|
||||
else
|
||||
{
|
||||
req = new SendPrepareRequest( requestEnum, 0, serverIdentifier, transactionID, stationID, characterID, assetID, xmlAsset );
|
||||
}
|
||||
|
||||
return m_apiCore->submitRequest( req, new CommonResponse( requestEnum, user ));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::sendPrepareTransactionCompressed (const char *serverIdentifier, long long transactionID, unsigned stationID, unsigned characterID, long long assetID, const unsigned char *zippedXmlAsset, unsigned length, void *user)
|
||||
{
|
||||
SendPrepareCompressedRequest *req = new SendPrepareCompressedRequest( GAME_REQUEST_SEND_PREPARE_TRANSACTION_COMPRESSED, 0, serverIdentifier, transactionID, stationID, characterID, assetID, zippedXmlAsset, length );
|
||||
|
||||
return m_apiCore->submitRequest( req, new CommonResponse( GAME_REQUEST_SEND_PREPARE_TRANSACTION_COMPRESSED, user ));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::replyReceiveGetCharacterList(unsigned trackingNumber, unsigned responseCode, const Character characters[], unsigned numCharacters, void *user)
|
||||
{
|
||||
ReplyGetCharacterListRequest *req = new ReplyGetCharacterListRequest(GAME_REPLY_RECEIVE_GET_CHARACTER_LIST, trackingNumber, responseCode, characters, numCharacters);
|
||||
return m_apiCore->submitRequest(req, new CommonResponse(GAME_REPLY_RECEIVE_GET_CHARACTER_LIST, user));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::identifyHost( const char *serverID[], unsigned idCount, void *user)
|
||||
{
|
||||
IdentifyServerRequest *req = new IdentifyServerRequest(REQUEST_SET_SERVER_LIST, 0, serverID, idCount);
|
||||
return m_apiCore->submitRequest( req, new CommonResponse(REQUEST_SET_SERVER_LIST, user));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::sendAuditAssetTransfer(const char *gameCode, const char *serverCode, long long inGameAssetID, unsigned stationID, const char *event, const char *message, void *user)
|
||||
{
|
||||
SendAuditRequest *req = new SendAuditRequest( GAME_SEND_AUDIT_MESSAGE, 0, gameCode, serverCode, inGameAssetID, stationID, event, message );
|
||||
return m_apiCore->submitRequest(req, new CommonResponse(GAME_SEND_AUDIT_MESSAGE, user));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
unsigned AuctionTransferAPI::getNewTransactionID(void *user)
|
||||
{
|
||||
GetIDRequest *req = new GetIDRequest( GAME_REQUEST_GET_TRANSACTION_ID, 0);
|
||||
return m_apiCore->submitRequest(req, new GetIDResponse( GAME_REQUEST_GET_TRANSACTION_ID, user));
|
||||
}
|
||||
|
||||
}; // namespace
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
#ifndef AUCTIONTRANSFERAPI_H
|
||||
#define AUCTIONTRANSFERAPI_H
|
||||
|
||||
#pragma warning (disable : 4786)
|
||||
|
||||
#include "AuctionTransferEnum.h"
|
||||
#include <Base/Archive.h>
|
||||
#include "Character.h"
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
namespace AuctionTransfer
|
||||
{
|
||||
|
||||
class AuctionTransferAPICore;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class AuctionTransferAPI
|
||||
{
|
||||
public:
|
||||
// constructor & destructor
|
||||
AuctionTransferAPI(const char *hostName[], const short port[], int count, const char *identifier[], unsigned identifierCount, unsigned reqTimeout = 60, unsigned maxRecvMessageSizeInKB = 16000);
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// the identifier list does not have one entry for each connection, it is a simple list of world names that
|
||||
// are handled by this API connection, no matter how many servers are connected to. In the case of EQ2 this
|
||||
// identifier list will just contain 1 name, the name of the world making the connection.
|
||||
|
||||
// the following constructor does the same as the one above, except that the host array is in the format of:
|
||||
// "hostname1:port1 hostname2:port2"
|
||||
// and the identifier array would be a semi-colon separated list of world names such as:
|
||||
// "Guk Befallen" or "GUK"
|
||||
AuctionTransferAPI(const char *hostNames, const char *identifiers);
|
||||
virtual ~AuctionTransferAPI();
|
||||
|
||||
// connect and disconnect call backs
|
||||
virtual void onConnect(const char* hostname, unsigned short port, const short current, const short max) = 0;
|
||||
virtual void onDisconnect(const char *host, const short port, const short current, const short max) = 0;
|
||||
|
||||
|
||||
//processing
|
||||
void process();
|
||||
|
||||
// Requests Generated by API
|
||||
unsigned sendPrepareTransaction (const char *serverIdentifier, long long transactionID, unsigned stationID, unsigned characterID, long long assetID, const char *xmlAsset, void *user, bool compress = false);
|
||||
unsigned sendPrepareTransactionCompressed (const char *serverIdentifier, long long transactionID, unsigned stationID, unsigned characterID, long long assetID, const unsigned char *zippedXmlAsset, unsigned length, void *user);
|
||||
unsigned sendCommitTransaction (long long transactionID, void *user);
|
||||
unsigned sendAbortTransaction (long long transactionID, void *user);
|
||||
unsigned sendAuditAssetTransfer(const char *gameCode, const char *serverCode, long long inGameAssetID, unsigned stationID, const char *event, const char *message, void *user);
|
||||
unsigned getNewTransactionID(void *user);
|
||||
|
||||
// requests as responses to a call initiated by the auction system
|
||||
unsigned replyReceivePrepareTransaction (unsigned trackingNumber,unsigned responseCode,void *user);
|
||||
unsigned replyReceiveCommitTransaction (unsigned trackingNumber, unsigned responseCode, void *user);
|
||||
unsigned replyReceiveAbortTransaction (unsigned trackingNumber, unsigned responseCode, void *user);
|
||||
unsigned replyReceiveGetCharacterList(unsigned trackingNumber, unsigned responseCode, const Character characters[], unsigned numCharacters, void *user);
|
||||
|
||||
// house keeping routines
|
||||
unsigned identifyHost( const char *serverID[], unsigned idCount, void *user);
|
||||
|
||||
// Callbacks that are repsonses
|
||||
virtual void onSendPrepareTransaction (unsigned trackingNumber, unsigned responseCode, void *user) = 0;
|
||||
virtual void onSendPrepareTransactionCompressed (unsigned trackingNumber, unsigned responseCode, void *user) = 0;
|
||||
virtual void onSendCommitTransaction (unsigned trackingNumber, unsigned responseCode, void *user) = 0;
|
||||
virtual void onSendAbortTransaction (unsigned trackingNumber, unsigned responseCode, void *user) = 0;
|
||||
virtual void onSendAuditAssetTransfer(unsigned trackingNumber, unsigned responseCode, void *user) = 0;
|
||||
virtual void onGetNewTransactionID( unsigned trackingNumber, unsigned responseCode, long long transactionID, void *user) = 0;
|
||||
|
||||
// responses to reply requests
|
||||
virtual void onReplyReceivePrepareTransaction (unsigned trackingNumber, unsigned responseCode, void *user) = 0;
|
||||
virtual void onReplyReceiveCommitTransaction (unsigned trackingNumber, unsigned responseCode, void *user) = 0;
|
||||
virtual void onReplyReceiveAbortTransaction (unsigned trackingNumber, unsigned responseCode, void *user) = 0;
|
||||
virtual void onReplyReceiveGetCharacterList(unsigned trackingNumber, unsigned responseCode, void *user) = 0;
|
||||
|
||||
// house keeping callbacks
|
||||
virtual void onIdentifyHost(unsigned trackingNumber, unsigned responseCode, void *user) = 0;
|
||||
|
||||
|
||||
// Callbacks initiated by the Auction System
|
||||
virtual void onReceivePrepareTransaction (unsigned trackingNumber, long long transactionID, unsigned stationID, unsigned characterID, long long assetID, const char *newName) = 0;
|
||||
virtual void onReceiveCommitTransaction (unsigned trackingNumber, long long transactionID) = 0;
|
||||
virtual void onReceiveAbortTransaction (unsigned trackingNumber, long long transactionID) = 0;
|
||||
virtual void onReceiveGetCharacterList(unsigned trackingNumber, unsigned stationID, const char *serverID) = 0;
|
||||
|
||||
private:
|
||||
AuctionTransferAPICore *m_apiCore;
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
}; // namespace
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
#endif
|
||||
BIN
Binary file not shown.
+181
@@ -0,0 +1,181 @@
|
||||
#include "AuctionTransferAPICore.h"
|
||||
#include "AuctionTransferAPI.h"
|
||||
#include "Response.h"
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
namespace AuctionTransfer
|
||||
{
|
||||
|
||||
/*/////////////////////////////////////////////////////////////////////////////////////
|
||||
AuctionTransferAPICore::AuctionTransferAPICore(const char *hostName[], const short port[], int count, AuctionTransferAPI *api, const char *identifier[], unsigned identifierCount)
|
||||
: GenericAPICore(identifier[0], hostName, port, count, 45, 5, 0, 90, 32, 32),
|
||||
m_api(api),
|
||||
m_mappedServerTrack(1000)
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
{
|
||||
for(unsigned i = 0; i < identifierCount; i++)
|
||||
addIdentifier(identifier[i]);
|
||||
}
|
||||
*/
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
AuctionTransferAPICore::AuctionTransferAPICore(const char *hostName[], const short port[], int count, AuctionTransferAPI *api, const char *identifier[], unsigned identifierCount, unsigned reqTimeout, unsigned maxRecvMessageSizeInKB)
|
||||
: GenericAPICore(identifier[0], hostName, port, count, reqTimeout, 5, 0, 90, 32, 32, 1, maxRecvMessageSizeInKB),
|
||||
m_api(api),
|
||||
m_mappedServerTrack(1000)
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
{
|
||||
for(unsigned i = 0; i < identifierCount; i++)
|
||||
addIdentifier(identifier[i]);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
AuctionTransferAPICore::~AuctionTransferAPICore()
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
{
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
void AuctionTransferAPICore::OnConnect(GenericConnection *connection)
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
{
|
||||
countOpenConnections();
|
||||
m_api->onConnect(connection->getHost(), connection->getPort(), (short)m_currentConnections, (short)m_maxConnections);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
void AuctionTransferAPICore::OnDisconnect(GenericConnection *connection)
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
{
|
||||
countOpenConnections();
|
||||
m_api->onDisconnect(connection->getHost(), connection->getPort(), (short)m_currentConnections, (short)m_maxConnections);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
void AuctionTransferAPICore::responseCallback(GenericResponse *response)
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
// these callbacks are a result of a call initiated by the game server.
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
{
|
||||
switch(response->getType())
|
||||
{
|
||||
case GAME_REPLY_RECEIVE_PREPARE_TRANSACTION:
|
||||
m_api->onReplyReceivePrepareTransaction(response->getTrack(),
|
||||
response->getResult(),
|
||||
response->getUser());
|
||||
break;
|
||||
case GAME_REPLY_RECEIVE_COMMIT:
|
||||
m_api->onReplyReceiveCommitTransaction( response->getTrack(),
|
||||
response->getResult(),
|
||||
response->getUser());
|
||||
break;
|
||||
case GAME_REPLY_RECEIVE_ABORT:
|
||||
m_api->onReplyReceiveAbortTransaction( response->getTrack(),
|
||||
response->getResult(),
|
||||
response->getUser());
|
||||
break;
|
||||
case GAME_REQUEST_SEND_PREPARE_TRANSACTION:
|
||||
m_api->onSendPrepareTransaction(response->getTrack(),
|
||||
response->getResult(),
|
||||
response->getUser());
|
||||
break;
|
||||
case GAME_REQUEST_SEND_PREPARE_TRANSACTION_COMPRESSED:
|
||||
m_api->onSendPrepareTransactionCompressed(response->getTrack(),
|
||||
response->getResult(),
|
||||
response->getUser());
|
||||
break;
|
||||
case GAME_REQUEST_SEND_COMMIT:
|
||||
m_api->onSendCommitTransaction( response->getTrack(),
|
||||
response->getResult(),
|
||||
response->getUser());
|
||||
break;
|
||||
case GAME_REQUEST_SEND_ABORT:
|
||||
m_api->onSendAbortTransaction( response->getTrack(),
|
||||
response->getResult(),
|
||||
response->getUser());
|
||||
break;
|
||||
case GAME_REPLY_RECEIVE_GET_CHARACTER_LIST:
|
||||
m_api->onReplyReceiveGetCharacterList( response->getTrack(),
|
||||
response->getResult(),
|
||||
response->getUser());
|
||||
break;
|
||||
case GAME_SEND_AUDIT_MESSAGE:
|
||||
m_api->onSendAuditAssetTransfer( response->getTrack(),
|
||||
response->getResult(),
|
||||
response->getUser());
|
||||
break;
|
||||
case REQUEST_SET_SERVER_LIST:
|
||||
m_api->onIdentifyHost( response->getTrack(),
|
||||
response->getResult(),
|
||||
response->getUser());
|
||||
break;
|
||||
case GAME_REQUEST_GET_TRANSACTION_ID:
|
||||
{
|
||||
GetIDResponse *r = static_cast<GetIDResponse *>(response);
|
||||
m_api->onGetNewTransactionID( r->getTrack(),
|
||||
r->getResult(),
|
||||
r->getNewID(),
|
||||
r->getUser());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
void AuctionTransferAPICore::responseCallback(short type, Base::ByteStream::ReadIterator &iter, GenericConnection *connection)
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
// these are the callbacks that are initiated from the Auction System. These callbacks
|
||||
// will be called to initiate a series of communication between the auction system and
|
||||
// the game servers.
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
{
|
||||
unsigned real_server_track;
|
||||
get(iter, real_server_track);
|
||||
ServerTrackObject *stobj = new ServerTrackObject(++m_mappedServerTrack, real_server_track, connection);
|
||||
m_serverTracks.insert(std::pair<unsigned, ServerTrackObject *>(m_mappedServerTrack, stobj));
|
||||
|
||||
long long transactionID;
|
||||
get(iter, transactionID);
|
||||
switch (type)
|
||||
{
|
||||
case GAME_REQUEST_RECEIVE_PREPARE_TRANSACTION:
|
||||
{
|
||||
unsigned stationID;
|
||||
unsigned characterID;
|
||||
long long assetID;
|
||||
std::string newName;
|
||||
get(iter, stationID);
|
||||
get(iter, characterID);
|
||||
get(iter, assetID);
|
||||
get(iter, newName);
|
||||
m_api->onReceivePrepareTransaction(m_mappedServerTrack, transactionID, stationID, characterID, assetID, newName.c_str());
|
||||
break;
|
||||
}
|
||||
case GAME_REQUEST_RECEIVE_COMMIT:
|
||||
{
|
||||
m_api->onReceiveCommitTransaction(m_mappedServerTrack, transactionID);
|
||||
break;
|
||||
}
|
||||
case GAME_REQUEST_RECEIVE_ABORT:
|
||||
{
|
||||
m_api->onReceiveAbortTransaction(m_mappedServerTrack, transactionID);
|
||||
break;
|
||||
}
|
||||
case GAME_REQUEST_RECEIVE_GET_CHARACTER_LIST:
|
||||
{
|
||||
// this had the stationID read in as the transactionID
|
||||
std::string serverID;
|
||||
get(iter, serverID);
|
||||
m_api->onReceiveGetCharacterList(m_mappedServerTrack, (unsigned int)transactionID, serverID.c_str());
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}; // namespace AuctionTransfer
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
#ifndef AUCTIONTRANSFERAPICORE_H
|
||||
#define AUCTIONTRANSFERAPICORE_H
|
||||
|
||||
|
||||
#include "ATGenericAPI/GenericApiCore.h"
|
||||
#include "ATGenericAPI/GenericConnection.h"
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
namespace AuctionTransfer
|
||||
{
|
||||
|
||||
class AuctionTransferAPI;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class AuctionTransferAPICore : public GenericAPICore
|
||||
{
|
||||
public:
|
||||
AuctionTransferAPICore(const char *hostName[], const short port[], int count, AuctionTransferAPI *api, const char *identifier[], unsigned identifierCount, unsigned timeout = 60, unsigned maxRecvMessageSizeInKB = 16000);
|
||||
virtual ~AuctionTransferAPICore();
|
||||
|
||||
void OnConnect(GenericConnection *connection);
|
||||
void OnDisconnect(GenericConnection *connection);
|
||||
void responseCallback(GenericResponse *response);
|
||||
void responseCallback(short type, Base::ByteStream::ReadIterator &iter, GenericConnection *connection);
|
||||
|
||||
private:
|
||||
AuctionTransferAPI *m_api;
|
||||
unsigned m_mappedServerTrack;
|
||||
};
|
||||
|
||||
}; // namespace AuctionTransfer
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#endif //AUCTIONTRANSFERAPICORE_H
|
||||
|
||||
BIN
Binary file not shown.
+164
@@ -0,0 +1,164 @@
|
||||
#ifndef AUCTIONTRANSFERENUM_H
|
||||
#define AUCTIONTRANSFERENUM_H
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
#define DEFAULT_TIMEOUTSECS 60
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
namespace AuctionTransfer
|
||||
{
|
||||
enum CloseReason
|
||||
{
|
||||
REASON_HOST_UNREACHABLE,
|
||||
REASON_LOCAL_DISCONNECT,
|
||||
REASON_REMOTE_DISCONNECT,
|
||||
REASON_SOCKET_FAILURE,
|
||||
REASON_DNS_FAILURE
|
||||
};
|
||||
|
||||
enum ResponseCode
|
||||
{
|
||||
RESPONSE_FIRST = 0,
|
||||
RESPONSE_UNKNOWN = RESPONSE_FIRST, // Initial state internally for call denotes no response yet
|
||||
RESPONSE_ACCEPTED = 1,
|
||||
RESPONSE_REJECTED,
|
||||
RESPONSE_FAILURE,
|
||||
RESPONSE_DUPLICATE,
|
||||
GAME_API_TIME_OUT, //5
|
||||
TRANSFER_SERVER_TIME_OUT,
|
||||
AUCTION_API_TIME_OUT,
|
||||
RESPONSE_REJECTED_INVALID_XML,
|
||||
RESPONSE_REJECTED_USER_NOT_REGISTERED,
|
||||
RESPONSE_REJECTED_UNABLE_TO_VALIDATE_USER, //10
|
||||
RESPONSE_REJECTED_NO_PAPER_DOLL_IMAGE,
|
||||
RESPONSE_REJECTED_INVALID_TRANSACTION_ID,
|
||||
RESPONSE_REJECTED_USER_NOT_AUTHORIZED,
|
||||
RESPONSE_REJECTED_HOLDING_AREA_FULL,
|
||||
RESPONSE_REJECTED_HOLDING_AREA_ASSET_TOO_OLD, //15
|
||||
RESPONSE_REJECTED_CHARACTER_LIMIT_REACHED,
|
||||
RESPONSE_REJECTED_CHARACTER_NOT_AVAILABLE,
|
||||
RESPONSE_REJECTED_MAILBOX_FULL,
|
||||
RESPONSE_REJECTED_GAME_SERVER_DOWN,
|
||||
RESPONSE_NAME_INVALID, //20
|
||||
RESPONSE_NAME_TAKEN,
|
||||
RESPONSE_FAILURE_DATABASE,
|
||||
RESPONSE_FAILURE_SERVER,
|
||||
RESPONSE_FAILURE_NETWORK,
|
||||
RESPONSE_INVALID_ALIGNMENT, //25
|
||||
RESPONSE_WEB_SERVICE_TIMEOUT,
|
||||
RESPONSE_REJECTED_EMAIL_NOT_VALIDATED,
|
||||
|
||||
//NOTE: THESE ALWAYS STAY AT THE END. IF EVER ADD A VALUE AFTER THE LAST RESPONSE_*, THEN IT NEEDS TO BE ASSIGNED BELOW
|
||||
RESPONSE_LAST = RESPONSE_REJECTED_EMAIL_NOT_VALIDATED,
|
||||
RESPONSE_COUNT = RESPONSE_LAST - RESPONSE_FIRST + 1
|
||||
};
|
||||
|
||||
enum RequestTypes
|
||||
{
|
||||
REQUEST_SET_API = 0,
|
||||
REQUEST_SET_SERVER_LIST,
|
||||
GAME_REQUEST_SEND_PREPARE_TRANSACTION,
|
||||
GAME_REQUEST_SEND_COMMIT,
|
||||
GAME_REQUEST_SEND_ABORT,
|
||||
GAME_REQUEST_RECEIVE_PREPARE_TRANSACTION, //5
|
||||
GAME_REQUEST_RECEIVE_COMMIT,
|
||||
GAME_REQUEST_RECEIVE_ABORT,
|
||||
GAME_REPLY_RECEIVE_PREPARE_TRANSACTION,
|
||||
GAME_REPLY_RECEIVE_COMMIT,
|
||||
GAME_REPLY_RECEIVE_ABORT, //10
|
||||
GAME_REQUEST_RECEIVE_GET_CHARACTER_LIST,
|
||||
GAME_REPLY_RECEIVE_GET_CHARACTER_LIST,
|
||||
GAME_SEND_AUDIT_MESSAGE,
|
||||
GAME_REQUEST_GET_TRANSACTION_ID,
|
||||
GAME_REQUEST_SEND_PREPARE_TRANSACTION_COMPRESSED,
|
||||
|
||||
WEB_REQUEST_SEND_PREPARE_TRANSACTION = 10000,
|
||||
WEB_REQUEST_SEND_COMMIT,
|
||||
WEB_REQUEST_SEND_ABORT,
|
||||
WEB_REQUEST_RECEIVE_PREPARE_TRANSACTION,
|
||||
WEB_REQUEST_RECEIVE_COMMIT,
|
||||
WEB_REQUEST_RECEIVE_ABORT, //10005
|
||||
WEB_REPLY_RECEIVE_PREPARE_TRANSACTION,
|
||||
WEB_REPLY_RECEIVE_COMMIT,
|
||||
WEB_REPLY_RECEIVE_ABORT,
|
||||
WEB_REQUEST_SEND_GET_CHARACTER_LIST,
|
||||
WEB_REQUEST_SEND_GET_SERVER_LIST, //10010
|
||||
WEB_REPLY_RECEIVE_AUDIT,
|
||||
WEB_REQUEST_RECEIVE_GET_TRANSACTION_ID,
|
||||
WEB_REPLY_RECEIVE_GET_TRANSACTION_ID,
|
||||
WEB_REQUEST_RECEIVE_PREPARE_TRANSACTION_COMPRESSED,
|
||||
WEB_REPLY_RECEIVE_PREPARE_TRANSACTION_COMPRESSED
|
||||
|
||||
};
|
||||
|
||||
#define response_text std::pair<unsigned,const char *>
|
||||
static const response_text _responseString[RESPONSE_COUNT] =
|
||||
{
|
||||
response_text(RESPONSE_UNKNOWN, "RESPONSE_UNKNOWN"),
|
||||
response_text(RESPONSE_ACCEPTED, "RESPONSE_ACCEPTED"),
|
||||
response_text(RESPONSE_REJECTED, "RESPONSE_REJECTED"),
|
||||
response_text(RESPONSE_FAILURE, "RESPONSE_FAILURE"),
|
||||
response_text(RESPONSE_DUPLICATE, "RESPONSE_DUPLICATE"),
|
||||
response_text(GAME_API_TIME_OUT, "GAME_API_TIME_OUT"),
|
||||
response_text(TRANSFER_SERVER_TIME_OUT, "TRANSFER_SERVER_TIME_OUT"),
|
||||
response_text(AUCTION_API_TIME_OUT, "AUCTION_API_TIME_OUT"),
|
||||
response_text(RESPONSE_REJECTED_INVALID_XML, "RESPONSE_REJECTED_INVALID_XML"),
|
||||
response_text(RESPONSE_REJECTED_USER_NOT_REGISTERED, "RESPONSE_REJECTED_USER_NOT_REGISTERED"),
|
||||
response_text(RESPONSE_REJECTED_UNABLE_TO_VALIDATE_USER, "RESPONSE_REJECTED_UNABLE_TO_VALIDATE_USER"),
|
||||
response_text(RESPONSE_REJECTED_NO_PAPER_DOLL_IMAGE, "RESPONSE_REJECTED_NO_PAPER_DOLL_IMAGE"),
|
||||
response_text(RESPONSE_REJECTED_INVALID_TRANSACTION_ID, "RESPONSE_REJECTED_INVALID_TRANSACTION_ID"),
|
||||
response_text(RESPONSE_REJECTED_USER_NOT_AUTHORIZED, "RESPONSE_REJECTED_USER_NOT_AUTHORIZED"),
|
||||
response_text(RESPONSE_REJECTED_HOLDING_AREA_FULL, "RESPONSE_REJECTED_HOLDING_AREA_FULL"),
|
||||
response_text(RESPONSE_REJECTED_HOLDING_AREA_ASSET_TOO_OLD, "RESPONSE_REJECTED_HOLDING_AREA_ASSET_TOO_OLD"),
|
||||
response_text(RESPONSE_REJECTED_CHARACTER_LIMIT_REACHED, "RESPONSE_REJECTED_CHARACTER_LIMIT_REACHED"),
|
||||
response_text(RESPONSE_REJECTED_CHARACTER_NOT_AVAILABLE, "RESPONSE_REJECTED_CHARACTER_NOT_AVAILABLE"),
|
||||
response_text(RESPONSE_REJECTED_MAILBOX_FULL, "RESPONSE_REJECTED_MAILBOX_FULL"),
|
||||
response_text(RESPONSE_REJECTED_GAME_SERVER_DOWN, "RESPONSE_REJECTED_GAME_SERVER_DOWN"),
|
||||
response_text(RESPONSE_NAME_INVALID, "RESPONSE_NAME_INVALID"),
|
||||
response_text(RESPONSE_NAME_TAKEN, "RESPONSE_NAME_TAKEN"),
|
||||
response_text(RESPONSE_FAILURE_DATABASE, "RESPONSE_FAILURE_DATABASE"),
|
||||
response_text(RESPONSE_FAILURE_SERVER, "RESPONSE_FAILURE_SERVER"),
|
||||
response_text(RESPONSE_FAILURE_NETWORK, "RESPONSE_FAILURE_NETWORK"),
|
||||
response_text(RESPONSE_INVALID_ALIGNMENT, "RESPONSE_INVALID_ALIGNMENT"),
|
||||
response_text(RESPONSE_WEB_SERVICE_TIMEOUT, "RESPONSE_WEB_SERVICE_TIMEOUT"),
|
||||
response_text(RESPONSE_REJECTED_EMAIL_NOT_VALIDATED, "RESPONSE_EMAIL_NOT_VALIDATED"),
|
||||
};
|
||||
static std::map<unsigned,const char *> ResponseString((const std::map<unsigned,const char *>::value_type *)&_responseString[0],(const std::map<unsigned,const char *>::value_type *)&_responseString[RESPONSE_COUNT]);
|
||||
|
||||
static const response_text _responseText[RESPONSE_COUNT] =
|
||||
{
|
||||
response_text(RESPONSE_UNKNOWN, "Unknown response code - default."),
|
||||
response_text(RESPONSE_ACCEPTED, "The operation completed successfully."),
|
||||
response_text(RESPONSE_REJECTED, "The operation was rejected by by the auction system."),
|
||||
response_text(RESPONSE_FAILURE, "There was a general failure processing the request."),
|
||||
response_text(RESPONSE_DUPLICATE, "This transaction was initiated previously."),
|
||||
response_text(GAME_API_TIME_OUT, "Unable to contact the Auction Transfer Server."),
|
||||
response_text(TRANSFER_SERVER_TIME_OUT, "The Auction Transfer Server could not Contact the Web Services."),
|
||||
response_text(AUCTION_API_TIME_OUT, "The SysEng Web Services did not respond."),
|
||||
response_text(RESPONSE_REJECTED_INVALID_XML, "The XML format was invalid."),
|
||||
response_text(RESPONSE_REJECTED_USER_NOT_REGISTERED, "The user has not registered in the Auction System yet."),
|
||||
response_text(RESPONSE_REJECTED_UNABLE_TO_VALIDATE_USER, "The user account was not able to be validated at this time."),
|
||||
response_text(RESPONSE_REJECTED_NO_PAPER_DOLL_IMAGE, "There was no image uploaded for this character yet."),
|
||||
response_text(RESPONSE_REJECTED_INVALID_TRANSACTION_ID, "The transaction id is not valid."),
|
||||
response_text(RESPONSE_REJECTED_USER_NOT_AUTHORIZED, "The station account is not authorized."),
|
||||
response_text(RESPONSE_REJECTED_HOLDING_AREA_FULL, "The user has too many items in their holding area."),
|
||||
response_text(RESPONSE_REJECTED_HOLDING_AREA_ASSET_TOO_OLD, "The user has an item in their holding area that is too old."),
|
||||
response_text(RESPONSE_REJECTED_CHARACTER_LIMIT_REACHED, "Too Many characters in Auctions."),
|
||||
response_text(RESPONSE_REJECTED_CHARACTER_NOT_AVAILABLE, "The character is not available for this transaction."),
|
||||
response_text(RESPONSE_REJECTED_MAILBOX_FULL, "The character mailbox is full."),
|
||||
response_text(RESPONSE_REJECTED_GAME_SERVER_DOWN, "The game server is unable to process the request."),
|
||||
response_text(RESPONSE_NAME_INVALID, "The new character name is invalid."),
|
||||
response_text(RESPONSE_NAME_TAKEN, "The new character name is taken."),
|
||||
response_text(RESPONSE_FAILURE_DATABASE, "There was a database failure during the transaction."),
|
||||
response_text(RESPONSE_FAILURE_SERVER, "There was a server failure during the transaction."),
|
||||
response_text(RESPONSE_FAILURE_NETWORK, "There was a network failure during the transaction."),
|
||||
response_text(RESPONSE_INVALID_ALIGNMENT, "The alignment of the character for this item is incorrect."),
|
||||
response_text(RESPONSE_WEB_SERVICE_TIMEOUT, "The AppEng web service failed to respond."),
|
||||
response_text(RESPONSE_REJECTED_EMAIL_NOT_VALIDATED, "The user has not validated their email with the auction system yet."),
|
||||
};
|
||||
static std::map<unsigned,const char *> ResponseText((const std::map<unsigned,const char *>::value_type *)&_responseText[0],(const std::map<unsigned,const char *>::value_type *)&_responseText[RESPONSE_COUNT]);
|
||||
|
||||
|
||||
}; //namespace AuctionTransfer
|
||||
#endif //AUCTIONTRANSFERENUM_H
|
||||
BIN
Binary file not shown.
+30
@@ -0,0 +1,30 @@
|
||||
Microsoft Visual Studio Solution File, Format Version 8.00
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AuctionTransferGameAPI", "AuctionTransferGameAPI.vcproj", "{CC51D0B0-3994-474D-BD51-5B49919AEBE0}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestApp", "TestApp\TestApp.vcproj", "{7AA05E1D-9952-4432-9975-6C00659BC0ED}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{CC51D0B0-3994-474D-BD51-5B49919AEBE0} = {CC51D0B0-3994-474D-BD51-5B49919AEBE0}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfiguration) = preSolution
|
||||
Debug = Debug
|
||||
Release = Release
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfiguration) = postSolution
|
||||
{CC51D0B0-3994-474D-BD51-5B49919AEBE0}.Debug.ActiveCfg = Debug|Win32
|
||||
{CC51D0B0-3994-474D-BD51-5B49919AEBE0}.Debug.Build.0 = Debug|Win32
|
||||
{CC51D0B0-3994-474D-BD51-5B49919AEBE0}.Release.ActiveCfg = Release|Win32
|
||||
{CC51D0B0-3994-474D-BD51-5B49919AEBE0}.Release.Build.0 = Release|Win32
|
||||
{7AA05E1D-9952-4432-9975-6C00659BC0ED}.Debug.ActiveCfg = Debug|Win32
|
||||
{7AA05E1D-9952-4432-9975-6C00659BC0ED}.Debug.Build.0 = Debug|Win32
|
||||
{7AA05E1D-9952-4432-9975-6C00659BC0ED}.Release.ActiveCfg = Release|Win32
|
||||
{7AA05E1D-9952-4432-9975-6C00659BC0ED}.Release.Build.0 = Release|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityAddIns) = postSolution
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
BIN
Binary file not shown.
+326
@@ -0,0 +1,326 @@
|
||||
<?xml version="1.0" encoding="Windows-1252"?>
|
||||
<VisualStudioProject
|
||||
ProjectType="Visual C++"
|
||||
Version="7.10"
|
||||
Name="AuctionTransferGameAPI"
|
||||
ProjectGUID="{CC51D0B0-3994-474D-BD51-5B49919AEBE0}"
|
||||
Keyword="Win32Proj">
|
||||
<Platforms>
|
||||
<Platform
|
||||
Name="Win32"/>
|
||||
</Platforms>
|
||||
<Configurations>
|
||||
<Configuration
|
||||
Name="Debug|Win32"
|
||||
OutputDirectory="Debug"
|
||||
IntermediateDirectory="Debug"
|
||||
ConfigurationType="4"
|
||||
CharacterSet="2">
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
Optimization="0"
|
||||
AdditionalIncludeDirectories=".\"
|
||||
PreprocessorDefinitions="WIN32;_DEBUG;_LIB;EXTERNAL_DISTRO;NAMESPACE="AuctionTransfer";USE_TCP_LIBRARY"
|
||||
MinimalRebuild="TRUE"
|
||||
BasicRuntimeChecks="3"
|
||||
RuntimeLibrary="5"
|
||||
UsePrecompiledHeader="0"
|
||||
WarningLevel="3"
|
||||
Detect64BitPortabilityProblems="TRUE"
|
||||
DebugInformationFormat="4"/>
|
||||
<Tool
|
||||
Name="VCCustomBuildTool"/>
|
||||
<Tool
|
||||
Name="VCLibrarianTool"
|
||||
AdditionalDependencies="ws2_32.lib"/>
|
||||
<Tool
|
||||
Name="VCMIDLTool"/>
|
||||
<Tool
|
||||
Name="VCPostBuildEventTool"/>
|
||||
<Tool
|
||||
Name="VCPreBuildEventTool"/>
|
||||
<Tool
|
||||
Name="VCPreLinkEventTool"/>
|
||||
<Tool
|
||||
Name="VCResourceCompilerTool"/>
|
||||
<Tool
|
||||
Name="VCWebServiceProxyGeneratorTool"/>
|
||||
<Tool
|
||||
Name="VCXMLDataGeneratorTool"/>
|
||||
<Tool
|
||||
Name="VCManagedWrapperGeneratorTool"/>
|
||||
<Tool
|
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
|
||||
</Configuration>
|
||||
<Configuration
|
||||
Name="Release|Win32"
|
||||
OutputDirectory="Release"
|
||||
IntermediateDirectory="Release"
|
||||
ConfigurationType="4"
|
||||
CharacterSet="2">
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
AdditionalIncludeDirectories="C:\P4\projects\AuctionTransfer\AuctionTransferGameAPI"
|
||||
PreprocessorDefinitions="WIN32;_DEBUG;_LIB;EXTERNAL_DISTRO;NAMESPACE="AuctionTransfer";USE_TCP_LIBRARY"
|
||||
RuntimeLibrary="4"
|
||||
UsePrecompiledHeader="0"
|
||||
WarningLevel="3"
|
||||
Detect64BitPortabilityProblems="TRUE"
|
||||
DebugInformationFormat="3"/>
|
||||
<Tool
|
||||
Name="VCCustomBuildTool"/>
|
||||
<Tool
|
||||
Name="VCLibrarianTool"
|
||||
AdditionalDependencies="ws2_32.lib"/>
|
||||
<Tool
|
||||
Name="VCMIDLTool"/>
|
||||
<Tool
|
||||
Name="VCPostBuildEventTool"/>
|
||||
<Tool
|
||||
Name="VCPreBuildEventTool"/>
|
||||
<Tool
|
||||
Name="VCPreLinkEventTool"/>
|
||||
<Tool
|
||||
Name="VCResourceCompilerTool"/>
|
||||
<Tool
|
||||
Name="VCWebServiceProxyGeneratorTool"/>
|
||||
<Tool
|
||||
Name="VCXMLDataGeneratorTool"/>
|
||||
<Tool
|
||||
Name="VCManagedWrapperGeneratorTool"/>
|
||||
<Tool
|
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
|
||||
</Configuration>
|
||||
</Configurations>
|
||||
<References>
|
||||
</References>
|
||||
<Files>
|
||||
<Filter
|
||||
Name="Source Files"
|
||||
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
|
||||
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
|
||||
<File
|
||||
RelativePath=".\AuctionTransferAPI.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\AuctionTransferAPICore.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\Character.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\Request.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\Response.cpp">
|
||||
</File>
|
||||
<Filter
|
||||
Name="TCP Library"
|
||||
Filter="">
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\Clock.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\IPAddress.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\TcpBlockAllocator.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\TcpConnection.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\TcpManager.cpp">
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Base"
|
||||
Filter="">
|
||||
<File
|
||||
RelativePath=".\Base\Archive.cpp">
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="GenericAPI_TCP"
|
||||
Filter="">
|
||||
<File
|
||||
RelativePath=".\ATGenericAPI\GenericApiCore.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\ATGenericAPI\GenericConnection.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\ATGenericAPI\GenericMessage.cpp">
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Gzip"
|
||||
Filter="">
|
||||
<File
|
||||
RelativePath=".\zip\Zip\adler32.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\compress.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\crc32.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\deflate.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\gzio.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\infblock.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\infcodes.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\inffast.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\inflate.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\inftrees.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\infutil.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\maketree.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\trees.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\uncompr.c">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\zutil.c">
|
||||
</File>
|
||||
</Filter>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Header Files"
|
||||
Filter="h;hpp;hxx;hm;inl;inc;xsd"
|
||||
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
|
||||
<File
|
||||
RelativePath=".\AuctionTransferAPI.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\AuctionTransferAPICore.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\Character.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\Request.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\Response.h">
|
||||
</File>
|
||||
<Filter
|
||||
Name="TCP Library"
|
||||
Filter="">
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\Clock.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\IPAddress.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\TcpBlockAllocator.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\TcpConnection.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\TcpHandlers.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\TcpLibrary\TcpManager.h">
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Base"
|
||||
Filter="">
|
||||
<File
|
||||
RelativePath=".\Base\Archive.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\Base\Platform.h">
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="GenericAPI_TCP"
|
||||
Filter="">
|
||||
<File
|
||||
RelativePath=".\ATGenericAPI\GenericApiCore.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\ATGenericAPI\GenericConnection.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\ATGenericAPI\GenericMessage.h">
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Common"
|
||||
Filter="">
|
||||
<File
|
||||
RelativePath=".\AuctionTransferEnum.h">
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Gzip"
|
||||
Filter="">
|
||||
<File
|
||||
RelativePath=".\zip\Zip\deflate.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\GZipHelper.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\infblock.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\infcodes.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\inffast.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\inffixed.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\inftrees.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\infutil.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\trees.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\zconf.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\zlib.h">
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\zip\Zip\zutil.h">
|
||||
</File>
|
||||
</Filter>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Resource Files"
|
||||
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
|
||||
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}">
|
||||
</Filter>
|
||||
</Files>
|
||||
<Globals>
|
||||
</Globals>
|
||||
</VisualStudioProject>
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// The author of this code is Justin Randall
|
||||
//
|
||||
// I have made modifications to the ByteStream
|
||||
// and AutoByteStream classes in order to make them suitable
|
||||
// for use in messaging systems which require objects that
|
||||
// are copyable and assignable. It is also desirable for
|
||||
// the ByteStream object to use a flexible allocator system
|
||||
// that may support multi-threaded programming models.
|
||||
|
||||
|
||||
#include "Archive.h"
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
CMutex ByteStreamMutex;
|
||||
#endif
|
||||
|
||||
#if defined (PASCAL_STRING)
|
||||
#pragma message ("--- Packing pascal style strings ---")
|
||||
void get(Base::ByteStream::ReadIterator& source, std::string& target)
|
||||
{
|
||||
unsigned int size = 0;
|
||||
Base::get (source, size);
|
||||
|
||||
const unsigned char *buf = source.getBuffer();
|
||||
|
||||
target.assign((const char *)buf, (const char *)(buf + size));
|
||||
|
||||
const unsigned int readSize = size * sizeof(char);
|
||||
source.advance(readSize);
|
||||
}
|
||||
|
||||
void put(ByteStream& target, const std::string& source)
|
||||
{
|
||||
const unsigned int size = source.size();
|
||||
put(target, size);
|
||||
target.put(source.data(), size * sizeof (char));
|
||||
}
|
||||
|
||||
#else
|
||||
#pragma message ("--- Packing c style strings ---")
|
||||
void get(ByteStream::ReadIterator & source, std::string & target)
|
||||
{
|
||||
target = reinterpret_cast<const char *>(source.getBuffer());
|
||||
source.advance(target.length() + 1);
|
||||
}
|
||||
|
||||
|
||||
void put(ByteStream & target, const std::string & source)
|
||||
{
|
||||
target.put(source.c_str(), source.size()+1);
|
||||
}
|
||||
#endif
|
||||
|
||||
ByteStream::ReadIterator::ReadIterator() :
|
||||
readPtr(0),
|
||||
stream(0)
|
||||
{
|
||||
}
|
||||
|
||||
ByteStream::ReadIterator::ReadIterator(const ReadIterator & source) :
|
||||
readPtr(source.readPtr),
|
||||
stream(source.stream)
|
||||
{
|
||||
}
|
||||
|
||||
ByteStream::ReadIterator::ReadIterator(const ByteStream & source) :
|
||||
readPtr(0),
|
||||
stream(&source)
|
||||
{
|
||||
}
|
||||
|
||||
ByteStream::ReadIterator::~ReadIterator()
|
||||
{
|
||||
stream = 0;
|
||||
}
|
||||
|
||||
ByteStream::ByteStream() :
|
||||
allocatedSize(0),
|
||||
beginReadIterator(),
|
||||
data(NULL),
|
||||
size(0),
|
||||
lastPutSize(0)
|
||||
{
|
||||
data = Data::getNewData();
|
||||
beginReadIterator = ReadIterator(*this);
|
||||
}
|
||||
|
||||
ByteStream::ByteStream(const unsigned char * const newBuffer, const unsigned int bufferSize) :
|
||||
allocatedSize(bufferSize),
|
||||
data(0),
|
||||
size(bufferSize),
|
||||
lastPutSize(0)
|
||||
{
|
||||
data = Data::getNewData();
|
||||
if(data->size < size)
|
||||
{
|
||||
delete[] data->buffer;
|
||||
data->buffer = new unsigned char[size];
|
||||
data->size = size;
|
||||
}
|
||||
memcpy(data->buffer, newBuffer, size);
|
||||
beginReadIterator = ReadIterator(*this);
|
||||
}
|
||||
|
||||
ByteStream::ByteStream(const ByteStream & source):
|
||||
allocatedSize(source.getSize()), // only allocate what is really there, be opportinistic when grow()'ing
|
||||
data(source.data),
|
||||
size(source.getSize()),
|
||||
lastPutSize(source.lastPutSize)
|
||||
{
|
||||
source.data->ref();
|
||||
beginReadIterator = ReadIterator(*this);
|
||||
}
|
||||
|
||||
ByteStream::ByteStream(ReadIterator & source) :
|
||||
allocatedSize(0),
|
||||
size(0),
|
||||
lastPutSize(0)
|
||||
{
|
||||
data = Data::getNewData();
|
||||
put(source.getBuffer(), source.getSize());
|
||||
source.advance(source.getSize());
|
||||
beginReadIterator = ReadIterator(*this);
|
||||
}
|
||||
|
||||
ByteStream::~ByteStream()
|
||||
{
|
||||
data->deref();
|
||||
allocatedSize = 0;
|
||||
data = 0; //lint !e672 (data deref insures the data is deleted if no one references it)
|
||||
size = 0;
|
||||
}
|
||||
|
||||
ByteStream & ByteStream::operator=(const ByteStream & rhs)
|
||||
{
|
||||
if(this != &rhs)
|
||||
{
|
||||
data->deref(); // deref local data
|
||||
rhs.data->ref();
|
||||
allocatedSize = rhs.allocatedSize;
|
||||
size = rhs.size;
|
||||
data = rhs.data; //lint !e672 (data is ref counted)
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void ByteStream::get(void * target, ReadIterator & readIterator, const unsigned long int targetSize) const
|
||||
{
|
||||
assert(readIterator.getReadPosition() + targetSize <= allocatedSize);
|
||||
memcpy(target, &data->buffer[readIterator.getReadPosition()], targetSize);
|
||||
}
|
||||
|
||||
void ByteStream::put(const void * const source, const unsigned int sourceSize)
|
||||
{
|
||||
if(data->getRef() > 1)
|
||||
{
|
||||
const unsigned char * const tmp = data->buffer;
|
||||
data->deref();
|
||||
data = Data::getNewData();
|
||||
if(data->size < sourceSize)
|
||||
{
|
||||
delete[] data->buffer;
|
||||
data->buffer = new unsigned char[size];
|
||||
data->size = size;
|
||||
}
|
||||
memcpy(data->buffer, tmp, size);
|
||||
allocatedSize = size;
|
||||
}
|
||||
growToAtLeast(size + sourceSize);
|
||||
memcpy(&data->buffer[size], source, sourceSize);
|
||||
size += sourceSize;
|
||||
if (sourceSize > 0)
|
||||
lastPutSize = sourceSize;
|
||||
}
|
||||
|
||||
bool ByteStream::overwriteEnd(const void * const source, const unsigned int sourceSize)
|
||||
{
|
||||
if(data->getRef() <= 1 &&
|
||||
lastPutSize == sourceSize &&
|
||||
sourceSize <= data->size)
|
||||
{
|
||||
memcpy(&data->buffer[size-sourceSize], source, sourceSize);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void ByteStream::reAllocate(const unsigned int newSize)
|
||||
{
|
||||
allocatedSize = newSize;
|
||||
if(data->size < allocatedSize)
|
||||
{
|
||||
unsigned char * tmp = new unsigned char[newSize];
|
||||
if(data->buffer != NULL)
|
||||
memcpy(tmp, data->buffer, size);
|
||||
delete[] data->buffer;
|
||||
data->buffer = tmp;
|
||||
data->size = newSize;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
AutoByteStream::AutoByteStream() :
|
||||
members()
|
||||
{
|
||||
}
|
||||
|
||||
AutoByteStream::~AutoByteStream()
|
||||
{
|
||||
}
|
||||
|
||||
void AutoByteStream::addVariable(AutoVariableBase & newVariable)
|
||||
{
|
||||
members.push_back(&newVariable);
|
||||
}
|
||||
|
||||
const unsigned int AutoByteStream::getItemCount() const
|
||||
{
|
||||
return members.size();
|
||||
}
|
||||
|
||||
void AutoByteStream::pack(ByteStream & target) const
|
||||
{
|
||||
std::vector<AutoVariableBase *>::const_iterator i;
|
||||
unsigned short packedSize=static_cast<unsigned short>(members.size());
|
||||
put(target,packedSize);
|
||||
for(i = members.begin(); i != members.end(); ++i)
|
||||
{
|
||||
(*i)->pack(target);
|
||||
}
|
||||
}
|
||||
|
||||
void AutoByteStream::unpack(ByteStream::ReadIterator & source)
|
||||
{
|
||||
std::vector<AutoVariableBase *>::iterator i;
|
||||
unsigned short packedSize;
|
||||
get(source,packedSize);
|
||||
for(i = members.begin(); i != members.end(); ++i)
|
||||
{
|
||||
(*i)->unpack(source);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
AutoVariableBase::AutoVariableBase()
|
||||
{
|
||||
}
|
||||
|
||||
AutoVariableBase::~AutoVariableBase()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
};
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
+746
@@ -0,0 +1,746 @@
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// The author of this code is Justin Randall
|
||||
//
|
||||
// I have made modifications to the ByteStream
|
||||
// and AutoByteStream classes in order to make them suitable
|
||||
// for use in messaging systems which require objects that
|
||||
// are copyable and assignable. It is also desirable for
|
||||
// the ByteStream object to use a flexible allocator system
|
||||
// that may support multi-threaded programming models.
|
||||
|
||||
|
||||
#ifndef BASE_ARCHIVE_H
|
||||
#define BASE_ARCHIVE_H
|
||||
|
||||
|
||||
#include <assert.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "Platform.h"
|
||||
|
||||
|
||||
//#if !defined PLATFORM_BASE_SINGLE_THREAD && ( defined _MT || defined _REENTRANT )
|
||||
//# define USE_ARCHIVE_MUTEX
|
||||
//# include "Mutex.h"
|
||||
//#endif
|
||||
|
||||
#ifdef WIN32
|
||||
# include "win32/Archive.h"
|
||||
#elif linux
|
||||
# include "linux/Archive.h"
|
||||
#elif sparc
|
||||
# include "solaris/Archive.h"
|
||||
#else
|
||||
#error /Base/Archive.h: Undefine platform type
|
||||
#endif
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
|
||||
const unsigned MAX_ARRAY_SIZE = 1024;
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
extern CMutex ByteStreamMutex;
|
||||
#endif
|
||||
|
||||
class ByteStream
|
||||
{
|
||||
public:
|
||||
class ReadIterator
|
||||
{
|
||||
public:
|
||||
ReadIterator();
|
||||
ReadIterator(const ReadIterator & source);
|
||||
explicit ReadIterator(const ByteStream & source);
|
||||
~ReadIterator();
|
||||
|
||||
ReadIterator & operator = (const ReadIterator & source);
|
||||
void advance (const unsigned int distance);
|
||||
void get (void * target, const unsigned long int readSize);
|
||||
const unsigned int getSize () const;
|
||||
const unsigned char * const getBuffer () const;
|
||||
const unsigned int getReadPosition () const;
|
||||
|
||||
private:
|
||||
unsigned int readPtr;
|
||||
const ByteStream * stream;
|
||||
};
|
||||
|
||||
private:
|
||||
class Data
|
||||
{
|
||||
friend class ByteStream;
|
||||
friend class ReadIterator;
|
||||
public:
|
||||
~Data();
|
||||
|
||||
static Data * getNewData();
|
||||
|
||||
const int getRef () const;
|
||||
void deref ();
|
||||
void ref ();
|
||||
protected:
|
||||
unsigned char * buffer;
|
||||
unsigned long size;
|
||||
private:
|
||||
struct DataFreeList
|
||||
{
|
||||
~DataFreeList()
|
||||
{
|
||||
std::vector<ByteStream::Data *>::iterator i;
|
||||
for(i = freeList.begin(); i != freeList.end(); ++i)
|
||||
{
|
||||
delete (*i);
|
||||
}
|
||||
};
|
||||
std::vector<Data *> freeList;
|
||||
};
|
||||
Data();
|
||||
//explicit Data(unsigned char * buffer);
|
||||
static std::vector<Data *> & getDataFreeList();
|
||||
static void releaseOldData(Data * oldData);
|
||||
private:
|
||||
int refCount;
|
||||
};
|
||||
|
||||
friend class ReadIterator;
|
||||
public:
|
||||
ByteStream();
|
||||
ByteStream(const unsigned char * const buffer, const unsigned int bufferSize);
|
||||
ByteStream(const ByteStream & source);
|
||||
virtual ~ByteStream();
|
||||
|
||||
public:
|
||||
ByteStream(ReadIterator & source);
|
||||
ByteStream & operator = (const ByteStream & source);
|
||||
ByteStream & operator = (ReadIterator & source);
|
||||
const ReadIterator & begin() const;
|
||||
void clear();
|
||||
const unsigned char * const getBuffer() const;
|
||||
const unsigned int getSize() const;
|
||||
void put(const void * const source, const unsigned int sourceSize);
|
||||
bool overwriteEnd(const void * const source, const unsigned int sourceSize);
|
||||
|
||||
private:
|
||||
void get(void * target, ReadIterator & readIterator, const unsigned long int readSize) const;
|
||||
void growToAtLeast(const unsigned int targetSize);
|
||||
void reAllocate(const unsigned int newSize);
|
||||
|
||||
private:
|
||||
unsigned int allocatedSize;
|
||||
ReadIterator beginReadIterator;
|
||||
Data * data;
|
||||
unsigned int size;
|
||||
unsigned int lastPutSize;
|
||||
|
||||
};
|
||||
|
||||
inline ByteStream::Data::Data() :
|
||||
buffer(0),
|
||||
size(0),
|
||||
refCount(1)
|
||||
{
|
||||
}
|
||||
|
||||
inline ByteStream::Data::~Data()
|
||||
{
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Lock();
|
||||
#endif
|
||||
|
||||
refCount = 0;
|
||||
delete[] buffer;
|
||||
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Unlock();
|
||||
#endif
|
||||
}
|
||||
|
||||
inline void ByteStream::Data::deref()
|
||||
{
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Lock();
|
||||
#endif
|
||||
|
||||
refCount--;
|
||||
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Unlock();
|
||||
#endif
|
||||
|
||||
if(refCount < 1)
|
||||
releaseOldData(this);
|
||||
}
|
||||
|
||||
inline std::vector<ByteStream::Data *> & ByteStream::Data::getDataFreeList()
|
||||
{
|
||||
static DataFreeList freeList;
|
||||
return freeList.freeList;
|
||||
}
|
||||
|
||||
inline ByteStream::Data * ByteStream::Data::getNewData()
|
||||
{
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Lock();
|
||||
#endif
|
||||
|
||||
Data * result = 0;
|
||||
if(getDataFreeList().empty())
|
||||
{
|
||||
result = new Data;
|
||||
}
|
||||
else
|
||||
{
|
||||
result = getDataFreeList().back();
|
||||
getDataFreeList().pop_back();
|
||||
}
|
||||
result->refCount = 1;
|
||||
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Unlock();
|
||||
#endif
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
inline const int ByteStream::Data::getRef() const
|
||||
{
|
||||
return refCount;
|
||||
}
|
||||
|
||||
inline void ByteStream::Data::ref()
|
||||
{
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Lock();
|
||||
#endif
|
||||
|
||||
refCount++;
|
||||
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Unlock();
|
||||
#endif
|
||||
}
|
||||
|
||||
inline void ByteStream::Data::releaseOldData(ByteStream::Data * oldData)
|
||||
{
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Lock();
|
||||
#endif
|
||||
|
||||
getDataFreeList().push_back(oldData);
|
||||
oldData->refCount = 0;
|
||||
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Unlock();
|
||||
#endif
|
||||
}
|
||||
|
||||
inline ByteStream::ReadIterator & ByteStream::ReadIterator::operator = (const ByteStream::ReadIterator & rhs)
|
||||
{
|
||||
if(&rhs != this)
|
||||
{
|
||||
readPtr = rhs.readPtr;
|
||||
stream = rhs.stream;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
inline void ByteStream::ReadIterator::get(void * target, const unsigned long int readSize)
|
||||
{
|
||||
assert(stream);
|
||||
stream->get(target, *this, readSize);
|
||||
readPtr += readSize;
|
||||
}
|
||||
|
||||
inline const unsigned int ByteStream::ReadIterator::getSize() const
|
||||
{
|
||||
assert(stream);
|
||||
return stream->getSize() - readPtr;
|
||||
}
|
||||
|
||||
inline const ByteStream::ReadIterator & ByteStream::begin() const
|
||||
{
|
||||
return beginReadIterator;
|
||||
}
|
||||
|
||||
inline void ByteStream::ReadIterator::advance(const unsigned int distance)
|
||||
{
|
||||
readPtr += distance;
|
||||
}
|
||||
|
||||
inline const unsigned int ByteStream::ReadIterator::getReadPosition() const
|
||||
{
|
||||
return readPtr;
|
||||
}
|
||||
|
||||
inline const unsigned char * const ByteStream::ReadIterator::getBuffer() const
|
||||
{
|
||||
if(stream)
|
||||
return &stream->data->buffer[readPtr];
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
inline void ByteStream::clear()
|
||||
{
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Lock();
|
||||
#endif
|
||||
|
||||
size = 0;
|
||||
|
||||
#if defined(USE_ARCHIVE_MUTEX)
|
||||
ByteStreamMutex.Unlock();
|
||||
#endif
|
||||
}
|
||||
|
||||
inline const unsigned char * const ByteStream::getBuffer() const
|
||||
{
|
||||
return data->buffer;
|
||||
}
|
||||
|
||||
inline const unsigned int ByteStream::getSize() const
|
||||
{
|
||||
return size;
|
||||
}
|
||||
|
||||
inline void ByteStream::growToAtLeast(const unsigned int targetSize)
|
||||
{
|
||||
if(allocatedSize < targetSize)
|
||||
{
|
||||
reAllocate(allocatedSize + allocatedSize + targetSize);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
class AutoVariableBase
|
||||
{
|
||||
public:
|
||||
AutoVariableBase();
|
||||
virtual ~AutoVariableBase();
|
||||
|
||||
virtual void pack(ByteStream & target) const = 0;
|
||||
virtual void unpack(ByteStream::ReadIterator & source) = 0;
|
||||
};
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
class AutoByteStream
|
||||
{
|
||||
public:
|
||||
AutoByteStream();
|
||||
virtual ~AutoByteStream();
|
||||
void addVariable(AutoVariableBase & newVariable);
|
||||
virtual const unsigned int getItemCount() const;
|
||||
virtual void pack(ByteStream & target) const;
|
||||
virtual void unpack(ByteStream::ReadIterator & source);
|
||||
protected:
|
||||
std::vector<AutoVariableBase *> members;
|
||||
private:
|
||||
AutoByteStream(const AutoByteStream & source);
|
||||
};
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
template<class ValueType>
|
||||
class AutoVariable : public AutoVariableBase
|
||||
{
|
||||
public:
|
||||
AutoVariable();
|
||||
explicit AutoVariable(const ValueType & source);
|
||||
virtual ~AutoVariable();
|
||||
|
||||
const ValueType & get() const;
|
||||
virtual void pack(ByteStream & target) const;
|
||||
void set(const ValueType & rhs);
|
||||
virtual void unpack(ByteStream::ReadIterator & source);
|
||||
|
||||
private:
|
||||
ValueType value;
|
||||
};
|
||||
|
||||
template<class ValueType>
|
||||
AutoVariable<ValueType>::AutoVariable() :
|
||||
AutoVariableBase(),
|
||||
value()
|
||||
{
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
AutoVariable<ValueType>::AutoVariable(const ValueType & source) :
|
||||
AutoVariableBase(),
|
||||
value(source)
|
||||
{
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
AutoVariable<ValueType>::~AutoVariable()
|
||||
{
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
const ValueType & AutoVariable<ValueType>::get() const
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
void AutoVariable<ValueType>::pack(ByteStream & target) const
|
||||
{
|
||||
Base::put(target, value);
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
void AutoVariable<ValueType>::set(const ValueType & rhs)
|
||||
{
|
||||
value = rhs;
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
void AutoVariable<ValueType>::unpack(ByteStream::ReadIterator & source)
|
||||
{
|
||||
Base::get(source, value);
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
template<class ValueType>
|
||||
class AutoArray : public AutoVariableBase
|
||||
{
|
||||
public:
|
||||
AutoArray();
|
||||
AutoArray(const AutoArray & source);
|
||||
~AutoArray();
|
||||
|
||||
const std::vector<ValueType> & get() const;
|
||||
void set(const std::vector<ValueType> & source);
|
||||
|
||||
virtual void pack(ByteStream & target) const;
|
||||
virtual void unpack(ByteStream::ReadIterator & source);
|
||||
|
||||
private:
|
||||
std::vector<ValueType> array;
|
||||
};
|
||||
|
||||
template<class ValueType>
|
||||
inline AutoArray<ValueType>::AutoArray()
|
||||
{
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
inline AutoArray<ValueType>::AutoArray(const AutoArray & source) :
|
||||
array(source.array)
|
||||
{
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
inline AutoArray<ValueType>::~AutoArray()
|
||||
{
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
inline const std::vector<ValueType> & AutoArray<ValueType>::get() const
|
||||
{
|
||||
return array;
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
inline void AutoArray<ValueType>::set(const std::vector<ValueType> & source)
|
||||
{
|
||||
array = source;
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
inline void AutoArray<ValueType>::pack(ByteStream & target) const
|
||||
{
|
||||
unsigned int arraySize = array.size();
|
||||
Base::put(target, arraySize);
|
||||
|
||||
typename std::vector<ValueType>::const_iterator i;
|
||||
for(i = array.begin(); i != array.end(); ++i)
|
||||
{
|
||||
ValueType v = (*i);
|
||||
Base::put(target, v);
|
||||
}
|
||||
}
|
||||
|
||||
template<class ValueType>
|
||||
inline void AutoArray<ValueType>::unpack(ByteStream::ReadIterator & source)
|
||||
{
|
||||
unsigned int arraySize;
|
||||
Base::get(source, arraySize);
|
||||
ValueType v;
|
||||
|
||||
if (arraySize > MAX_ARRAY_SIZE)
|
||||
arraySize = 0;
|
||||
|
||||
for(unsigned int i = 0; i < arraySize; ++i)
|
||||
{
|
||||
Base::get(source, v);
|
||||
array.push_back(v);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, ByteStream & target)
|
||||
{
|
||||
target.put(source.getBuffer(), source.getSize());
|
||||
source.advance(source.getSize());
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, double & target)
|
||||
{
|
||||
source.get(&target, 8);
|
||||
target = byteSwap(target);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, float & target)
|
||||
{
|
||||
source.get(&target, 4);
|
||||
target = byteSwap(target);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, uint64 & target)
|
||||
{
|
||||
source.get(&target, 8);
|
||||
target = byteSwap(target);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, int64 & target)
|
||||
{
|
||||
source.get(&target, 8);
|
||||
target = byteSwap(target);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, uint32 & target)
|
||||
{
|
||||
source.get(&target, 4);
|
||||
target = byteSwap(target);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, int32 & target)
|
||||
{
|
||||
source.get(&target, 4);
|
||||
target = byteSwap(target);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, uint16 & target)
|
||||
{
|
||||
source.get(&target, 2);
|
||||
target = byteSwap(target);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, int16 & target)
|
||||
{
|
||||
source.get(&target, 2);
|
||||
target = byteSwap(target);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, uint8 & target)
|
||||
{
|
||||
source.get(&target, 1);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, int8 & target)
|
||||
{
|
||||
source.get(&target, 1);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, unsigned char * const target, const unsigned int targetSize)
|
||||
{
|
||||
source.get(target, targetSize);
|
||||
}
|
||||
|
||||
inline void get(ByteStream::ReadIterator & source, bool & target)
|
||||
{
|
||||
source.get(&target, 1);
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
inline void put(ByteStream & target, ByteStream::ReadIterator & source)
|
||||
{
|
||||
target.put(source.getBuffer(), source.getSize());
|
||||
source.advance(source.getSize());
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const double value)
|
||||
{
|
||||
double temp = byteSwap(value);
|
||||
target.put(&temp, 8);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const float value)
|
||||
{
|
||||
float temp = byteSwap(value);
|
||||
target.put(&temp, 4);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const uint64 value)
|
||||
{
|
||||
uint64 temp = byteSwap(value);
|
||||
target.put(&temp, 8);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const int64 value)
|
||||
{
|
||||
int64 temp = byteSwap(value);
|
||||
target.put(&temp, 8);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const uint32 value)
|
||||
{
|
||||
uint32 temp = byteSwap(value);
|
||||
target.put(&temp, 4);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const int32 value)
|
||||
{
|
||||
int32 temp = byteSwap(value);
|
||||
target.put(&temp, 4);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const uint16 value)
|
||||
{
|
||||
uint16 temp = byteSwap(value);
|
||||
target.put(&temp, 2);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const int16 value)
|
||||
{
|
||||
int16 temp = byteSwap(value);
|
||||
target.put(&temp, 2);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const uint8 value)
|
||||
{
|
||||
target.put(&value, 1);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const int8 value)
|
||||
{
|
||||
target.put(&value, 1);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const bool & source)
|
||||
{
|
||||
target.put(&source, 1);
|
||||
}
|
||||
|
||||
|
||||
inline void put(ByteStream & target, const unsigned char * const source, const unsigned int sourceSize)
|
||||
{
|
||||
target.put(source, sourceSize);
|
||||
}
|
||||
|
||||
inline void put(ByteStream & target, const ByteStream & source)
|
||||
{
|
||||
target.put(source.begin().getBuffer(), source.begin().getSize());
|
||||
}
|
||||
|
||||
void get(ByteStream::ReadIterator & source, std::string & target);
|
||||
void put(ByteStream & target, const std::string & source);
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const double value)
|
||||
{
|
||||
double temp = byteSwap(value);
|
||||
return target.overwriteEnd(&temp, 8);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const float value)
|
||||
{
|
||||
float temp = byteSwap(value);
|
||||
return target.overwriteEnd(&temp, 4);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const uint64 value)
|
||||
{
|
||||
uint64 temp = byteSwap(value);
|
||||
return target.overwriteEnd(&temp, 8);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const int64 value)
|
||||
{
|
||||
int64 temp = byteSwap(value);
|
||||
return target.overwriteEnd(&temp, 8);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const uint32 value)
|
||||
{
|
||||
uint32 temp = byteSwap(value);
|
||||
return target.overwriteEnd(&temp, 4);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const int32 value)
|
||||
{
|
||||
int32 temp = byteSwap(value);
|
||||
return target.overwriteEnd(&temp, 4);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const uint16 value)
|
||||
{
|
||||
uint16 temp = byteSwap(value);
|
||||
return target.overwriteEnd(&temp, 2);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const int16 value)
|
||||
{
|
||||
int16 temp = byteSwap(value);
|
||||
return target.overwriteEnd(&temp, 2);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const uint8 value)
|
||||
{
|
||||
return target.overwriteEnd(&value, 1);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const int8 value)
|
||||
{
|
||||
return target.overwriteEnd(&value, 1);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const bool & source)
|
||||
{
|
||||
return target.overwriteEnd(&source, 1);
|
||||
}
|
||||
|
||||
inline bool overwriteEnd(ByteStream & target, const unsigned char * const source, const unsigned int sourceSize)
|
||||
{
|
||||
return target.overwriteEnd(source, sourceSize);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
};
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif
|
||||
BIN
Binary file not shown.
+105
@@ -0,0 +1,105 @@
|
||||
#ifndef BASE_PLATFORM_H
|
||||
#define BASE_PLATFORM_H
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
|
||||
#ifdef WIN32
|
||||
#include "win32/Platform.h"
|
||||
#elif linux
|
||||
#include "linux/Platform.h"
|
||||
#elif sparc
|
||||
#include "solaris/Platform.h"
|
||||
#else
|
||||
#error /Base/Platform.h: Undefine platform type
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
|
||||
|
||||
template <class T> inline T rotlFixed(T x, unsigned int y)
|
||||
{
|
||||
assert(y < sizeof(T)*8);
|
||||
return (T)((x<<y) | (x>>(sizeof(T)*8-y)));
|
||||
}
|
||||
|
||||
template <class T> inline T rotrFixed(T x, unsigned int y)
|
||||
{
|
||||
assert(y < sizeof(T)*8);
|
||||
return (x>>y) | (x<<(sizeof(T)*8-y));
|
||||
}
|
||||
|
||||
template <class T> inline T rotlMod(T x, unsigned int y)
|
||||
{
|
||||
y %= sizeof(T)*8;
|
||||
return (x<<y) | (x>>(sizeof(T)*8-y));
|
||||
}
|
||||
|
||||
template <class T> inline T rotrMod(T x, unsigned int y)
|
||||
{
|
||||
y %= sizeof(T)*8;
|
||||
return (x>>y) | (x<<(sizeof(T)*8-y));
|
||||
}
|
||||
|
||||
inline uint16 byteReverse16(void * data)
|
||||
{
|
||||
uint16 value = *static_cast<uint16 *>(data);
|
||||
return *static_cast<uint16 *>(data) = rotlFixed(value, 8U);
|
||||
// return rotlFixed(value, 8U);
|
||||
}
|
||||
|
||||
inline uint32 byteReverse32(void * data)
|
||||
{
|
||||
uint32 value = *static_cast<uint32 *>(data);
|
||||
return *static_cast<uint32 *>(data) = (rotrFixed(value, 8U) & 0xff00ff00) | (rotlFixed(value, 8U) & 0x00ff00ff);
|
||||
// return (rotrFixed(value, 8U) & 0xff00ff00) | (rotlFixed(value, 8U) & 0x00ff00ff);
|
||||
}
|
||||
inline uint64 byteReverse64(void * data)
|
||||
{
|
||||
uint64 value = *static_cast<uint64 *>(data);
|
||||
return *static_cast<uint64 *>(data) = (
|
||||
uint64((rotrFixed(uint32(value), 8U) & 0xff00ff00) | (rotlFixed(uint32(value), 8U) & 0x00ff00ff)) << 32) |
|
||||
(rotrFixed(uint32(value>>32), 8U) & 0xff00ff00) | (rotlFixed(uint32(value>>32), 8U) & 0x00ff00ff);
|
||||
// return (uint64(byteReverse(uint32(value))) << 32) | byteReverse(uint32(value>>32));
|
||||
}
|
||||
|
||||
inline uint32 strlen(const unsigned short * string)
|
||||
{
|
||||
if (string == 0)
|
||||
return 0;
|
||||
|
||||
uint32 length=0;
|
||||
while (*(string+length++) != 0);
|
||||
|
||||
return length-1;
|
||||
}
|
||||
|
||||
inline double getTimerLatency(Base::uint64 startTime, Base::uint64 finishTime=0)
|
||||
{
|
||||
Base::int64 requestAge;
|
||||
Base::int64 freq = Base::getTimerFrequency();
|
||||
Base::uint64 finish = (finishTime ? finishTime : Base::getTimer());
|
||||
if (finish < startTime)
|
||||
requestAge = (0 - 1) - startTime - finish;
|
||||
else
|
||||
requestAge = finish - startTime;
|
||||
return (double)requestAge/freq;
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
|
||||
#endif // BASE_PLATFORM_H
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#ifndef BASE_LINUX_ARCHIVE_H
|
||||
#define BASE_LINUX_ARCHIVE_H
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
|
||||
namespace Base
|
||||
{
|
||||
|
||||
|
||||
#ifdef PACK_BIG_ENDIAN
|
||||
|
||||
inline double byteSwap(double value) { byteReverse(&value); return value; }
|
||||
inline float byteSwap(float value) { byteReverse(&value); return value; }
|
||||
inline uint64 byteSwap(uint64 value) { byteReverse(&value); return value; }
|
||||
inline int64 byteSwap(int64 value) { byteReverse(&value); return value; }
|
||||
inline uint32 byteSwap(uint32 value) { byteReverse(&value); return value; }
|
||||
inline int32 byteSwap(int32 value) { byteReverse(&value); return value; }
|
||||
inline uint16 byteSwap(uint16 value) { byteReverse(&value); return value; }
|
||||
inline int16 byteSwap(int16 value) { byteReverse(&value); return value; }
|
||||
|
||||
#else
|
||||
|
||||
inline double byteSwap(double value) { return value; }
|
||||
inline float byteSwap(float value) { return value; }
|
||||
inline uint64 byteSwap(uint64 value) { return value; }
|
||||
inline int64 byteSwap(int64 value) { return value; }
|
||||
inline uint32 byteSwap(uint32 value) { return value; }
|
||||
inline int32 byteSwap(int32 value) { return value; }
|
||||
inline uint16 byteSwap(uint16 value) { return value; }
|
||||
inline int16 byteSwap(int16 value) { return value; }
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
}
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
////////////////////////////////////////
|
||||
// Mutex.cpp
|
||||
//
|
||||
// Purpose:
|
||||
// 1. Implementation of the CMutex class.
|
||||
//
|
||||
// Revisions:
|
||||
// 07/10/2001 Created
|
||||
//
|
||||
|
||||
#if defined(_REENTRANT)
|
||||
|
||||
|
||||
#include "Mutex.h"
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
|
||||
CMutex::CMutex()
|
||||
{
|
||||
mInitialized = (pthread_mutex_init(&mMutex, 0) == 0);
|
||||
}
|
||||
|
||||
CMutex::~CMutex()
|
||||
{
|
||||
if (mInitialized)
|
||||
pthread_mutex_destroy(&mMutex);
|
||||
}
|
||||
|
||||
}
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // #if defined(_REENTRANT)
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
////////////////////////////////////////
|
||||
// Mutex.h
|
||||
//
|
||||
// Purpose:
|
||||
// 1. Declair the CMutex class that encapsulates the functionality of a
|
||||
// mutually-exclusive device.
|
||||
//
|
||||
// Revisions:
|
||||
// 07/10/2001 Created
|
||||
//
|
||||
|
||||
#ifndef BASE_LINUX_MUTEX_H
|
||||
#define BASE_LINUX_MUTEX_H
|
||||
|
||||
#if !defined(_REENTRANT)
|
||||
# pragma message( "Excluding Base::CMutex - requires multi-threaded compile. (_REENTRANT)" )
|
||||
#else
|
||||
|
||||
|
||||
#include "Platform.h"
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
|
||||
////////////////////////////////////////
|
||||
// Class:
|
||||
// CMutex
|
||||
//
|
||||
// Purpose:
|
||||
// Encapsulates the functionality of a mutually-exclusive device.
|
||||
// This class is valuable for protecting against race conditions
|
||||
// within threaded applications. The CMutex class can be used to
|
||||
// only allow a single thread to run within a specified code
|
||||
// segment at a time.
|
||||
//
|
||||
// Public Methods:
|
||||
// Lock() : Locks the mutex. If the mutex is already locked, the
|
||||
// operating system will block the calling thread until another
|
||||
// thread has unlocked the mutex.
|
||||
// Unlock() : Unlocks the mutex.
|
||||
//
|
||||
class CMutex
|
||||
{
|
||||
public:
|
||||
CMutex();
|
||||
~CMutex();
|
||||
|
||||
void Lock();
|
||||
void Unlock();
|
||||
private:
|
||||
pthread_mutex_t mMutex;
|
||||
bool mInitialized;
|
||||
};
|
||||
|
||||
inline void CMutex::Lock(void)
|
||||
{
|
||||
if (mInitialized)
|
||||
pthread_mutex_lock(&mMutex);
|
||||
}
|
||||
|
||||
inline void CMutex::Unlock(void)
|
||||
{
|
||||
if (mInitialized)
|
||||
pthread_mutex_unlock(&mMutex);
|
||||
}
|
||||
|
||||
}
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
#endif // #if defined(_MT)
|
||||
|
||||
#endif // BASE_LINUX_MUTEX_H
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
////////////////////////////////////////
|
||||
// Platform.cpp
|
||||
//
|
||||
// Purpose:
|
||||
// 1. Implementation of the global functionality declaired in Platform.h.
|
||||
//
|
||||
// Revisions:
|
||||
// 07/10/2001 Created
|
||||
//
|
||||
|
||||
#include <ctype.h>
|
||||
#include "Platform.h"
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
|
||||
// Implementation of microsoft strlwr extension
|
||||
// This non-ANSI function is not supported under UNIX
|
||||
void strlwr(char * s)
|
||||
{
|
||||
while (*s)
|
||||
{
|
||||
*s = tolower(*s);
|
||||
s++;
|
||||
}
|
||||
}
|
||||
|
||||
// Implementation of microsoft strlwr extension
|
||||
// This non-ANSI function is not supported under UNIX
|
||||
void strupr(char * s)
|
||||
{
|
||||
while (*s)
|
||||
{
|
||||
*s = toupper(*s);
|
||||
s++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
CTimer::CTimer() :
|
||||
mTimer(0)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
////////////////////////////////////////
|
||||
// Platform.h
|
||||
//
|
||||
// Purpose:
|
||||
// 1. Include relevent system headers that are platform specific.
|
||||
// 2. Declair global platform specific functionality.
|
||||
// 3. Include primative type definitions
|
||||
//
|
||||
// Global Functions:
|
||||
// getTimer() : Return the current high resolution clock count.
|
||||
// getTimerFrequency() : Return the frequency of the high resolution clock.
|
||||
// sleep() : Voluntarily relinquish timeslice of the calling thread for a
|
||||
// specified number of milliseconds.
|
||||
// strlwr() : Alters the contents of a string, making it all lower-case.
|
||||
//
|
||||
// Revisions:
|
||||
// 07/10/2001 Created
|
||||
//
|
||||
|
||||
#ifndef BASE_LINUX_PLATFORM_H
|
||||
#define BASE_LINUX_PLATFORM_H
|
||||
|
||||
#include <errno.h>
|
||||
#include <assert.h>
|
||||
#include <sys/errno.h>
|
||||
#include <pthread.h>
|
||||
#include <resolv.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
#include "Types.h"
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
uint64 getTimer(void);
|
||||
uint64 getTimerFrequency(void);
|
||||
void sleep(uint32 ms);
|
||||
|
||||
inline uint64 getTimer(void)
|
||||
{
|
||||
uint64 t;
|
||||
struct timeval tv;
|
||||
|
||||
gettimeofday(&tv, 0);
|
||||
t = tv.tv_sec;
|
||||
t = t * 1000000;
|
||||
t += tv.tv_usec;
|
||||
return t;
|
||||
}
|
||||
|
||||
inline uint64 getTimerFrequency(void)
|
||||
{
|
||||
uint64 f = 1000000;
|
||||
return f;
|
||||
}
|
||||
|
||||
inline void sleep(uint32 ms)
|
||||
{
|
||||
usleep(static_cast<unsigned long>(ms * 1000));
|
||||
}
|
||||
|
||||
void strlwr(char * s);
|
||||
void strupr(char * s);
|
||||
|
||||
|
||||
class CTimer
|
||||
{
|
||||
public:
|
||||
CTimer();
|
||||
|
||||
void Set(uint32 seconds);
|
||||
void Signal();
|
||||
bool Expired();
|
||||
|
||||
private:
|
||||
uint32 mTimer;
|
||||
};
|
||||
|
||||
inline void CTimer::Set(uint32 interval)
|
||||
{
|
||||
mTimer = (uint32)time(0) + interval;
|
||||
}
|
||||
|
||||
inline void CTimer::Signal()
|
||||
{
|
||||
mTimer = 0;
|
||||
}
|
||||
|
||||
inline bool CTimer::Expired()
|
||||
{
|
||||
return (mTimer <= (uint32)time(0));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
#endif // BASE_LINUX_PLATFORM_H
|
||||
BIN
Binary file not shown.
+42
@@ -0,0 +1,42 @@
|
||||
////////////////////////////////////////
|
||||
// Types.h
|
||||
//
|
||||
// Purpose:
|
||||
// 1. Define integer types that are unambiguous with respect to size
|
||||
//
|
||||
// Revisions:
|
||||
// 07/10/2001 Created
|
||||
//
|
||||
|
||||
#ifndef BASE_LINUX_TYPES_H
|
||||
#define BASE_LINUX_TYPES_H
|
||||
|
||||
#include <sys/bitypes.h>
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
|
||||
namespace Base
|
||||
{
|
||||
#define INT32_MAX 0x7FFFFFFF
|
||||
#define INT32_MIN 0x80000000
|
||||
#define UINT32_MAX 0xFFFFFFFF
|
||||
|
||||
typedef signed char int8;
|
||||
typedef unsigned char uint8;
|
||||
typedef signed short int16;
|
||||
typedef unsigned short uint16;
|
||||
|
||||
typedef int32_t int32;
|
||||
typedef u_int32_t uint32;
|
||||
typedef int64_t int64;
|
||||
typedef u_int64_t uint64;
|
||||
}
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
#endif // BASE_LINUX_TYPES_H
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#ifndef BASE_WIN32_ARCHIVE_H
|
||||
#define BASE_WIN32_ARCHIVE_H
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
|
||||
|
||||
#ifdef PACK_BIG_ENDIAN
|
||||
|
||||
inline double byteSwap(double value) { byteReverse64(&value); return value; }
|
||||
inline float byteSwap(float value) { byteReverse32(&value); return value; }
|
||||
inline uint64 byteSwap(uint64 value) { byteReverse64(&value); return value; }
|
||||
inline int64 byteSwap(int64 value) { byteReverse64(&value); return value; }
|
||||
inline uint32 byteSwap(uint32 value) { byteReverse32(&value); return value; }
|
||||
inline int32 byteSwap(int32 value) { byteReverse32(&value); return value; }
|
||||
inline uint16 byteSwap(uint16 value) { byteReverse16(&value); return value; }
|
||||
inline int16 byteSwap(int16 value) { byteReverse16(&value); return value; }
|
||||
|
||||
#else
|
||||
|
||||
inline double byteSwap(double value) { return value; }
|
||||
inline float byteSwap(float value) { return value; }
|
||||
inline uint64 byteSwap(uint64 value) { return value; }
|
||||
inline int64 byteSwap(int64 value) { return value; }
|
||||
inline uint32 byteSwap(uint32 value) { return value; }
|
||||
inline int32 byteSwap(int32 value) { return value; }
|
||||
inline uint16 byteSwap(uint16 value) { return value; }
|
||||
inline int16 byteSwap(int16 value) { return value; }
|
||||
|
||||
#endif
|
||||
|
||||
};
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
////////////////////////////////////////
|
||||
// Platform.cpp
|
||||
//
|
||||
// Purpose:
|
||||
// 1. Implementation of the global functionality declaired in Platform.h.
|
||||
//
|
||||
// Revisions:
|
||||
// 07/10/2001 Created
|
||||
//
|
||||
|
||||
#include "Platform.h"
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
|
||||
|
||||
CTimer::CTimer() :
|
||||
mTimer(0)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
////////////////////////////////////////
|
||||
// Platform.h
|
||||
//
|
||||
// Purpose:
|
||||
// 1. Include relevent system headers that are platform specific.
|
||||
// 2. Declair global platform specific functionality.
|
||||
// 3. Include primative type definitions
|
||||
//
|
||||
// Global Functions:
|
||||
// getTimer() : Return the current high resolution clock count.
|
||||
// getTimerFrequency() : Return the frequency of the high resolution clock.
|
||||
// sleep() : Voluntarily relinquish timeslice of the calling thread for a
|
||||
// specified number of milliseconds.
|
||||
//
|
||||
// Revisions:
|
||||
// 07/10/2001 Created
|
||||
//
|
||||
|
||||
#ifndef BASE_WIN32_PLATFORM_H
|
||||
#define BASE_WIN32_PLATFORM_H
|
||||
|
||||
#include <memory.h>
|
||||
#include <winsock2.h>
|
||||
#include <time.h>
|
||||
#include <io.h>
|
||||
#include <fcntl.h>
|
||||
#include <direct.h>
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include "Types.h"
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
|
||||
uint64 getTimer(void);
|
||||
uint64 getTimerFrequency(void);
|
||||
|
||||
inline uint64 getTimer(void)
|
||||
{
|
||||
uint64 result;
|
||||
if (!QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER *>(&result)))
|
||||
result = 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
inline uint64 getTimerFrequency(void)
|
||||
{
|
||||
uint64 result;
|
||||
if (!QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER *>(&result)))
|
||||
result = 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
inline void sleep(uint32 ms)
|
||||
{
|
||||
Sleep(ms);
|
||||
}
|
||||
|
||||
|
||||
class CTimer
|
||||
{
|
||||
public:
|
||||
CTimer();
|
||||
|
||||
void Set(uint32 seconds);
|
||||
void Signal();
|
||||
bool Expired();
|
||||
|
||||
private:
|
||||
uint32 mTimer;
|
||||
};
|
||||
|
||||
inline void CTimer::Set(uint32 interval)
|
||||
{
|
||||
mTimer = (uint32)time(0) + interval;
|
||||
}
|
||||
|
||||
inline void CTimer::Signal()
|
||||
{
|
||||
mTimer = 0;
|
||||
}
|
||||
|
||||
inline bool CTimer::Expired()
|
||||
{
|
||||
return (mTimer <= (uint32)time(0));
|
||||
}
|
||||
};
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
|
||||
#endif BASE_WIN32_PLATFORM_H
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
////////////////////////////////////////
|
||||
// Types.h
|
||||
//
|
||||
// Purpose:
|
||||
// 1. Define integer types that are unambiguous with respect to size
|
||||
//
|
||||
// Revisions:
|
||||
// 07/10/2001 Created
|
||||
//
|
||||
|
||||
#ifndef BASE_WIN32_TYPES_H
|
||||
#define BASE_WIN32_TYPES_H
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
|
||||
#endif
|
||||
namespace Base
|
||||
{
|
||||
|
||||
#define INT32_MAX 0x7FFFFFFF
|
||||
#define INT32_MIN 0x80000000
|
||||
#define UINT32_MAX 0xFFFFFFFF
|
||||
|
||||
typedef signed char int8;
|
||||
typedef unsigned char uint8;
|
||||
typedef short int16;
|
||||
typedef unsigned short uint16;
|
||||
|
||||
typedef int int32;
|
||||
typedef unsigned uint32;
|
||||
typedef __int64 int64;
|
||||
typedef unsigned __int64 uint64;
|
||||
|
||||
};
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // BASE_WIN32_TYPES_H
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#include "Character.h"
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
|
||||
namespace Base
|
||||
{
|
||||
|
||||
void get(ByteStream::ReadIterator & source, AuctionTransfer::Character & target)
|
||||
{
|
||||
std::string tmpStr;
|
||||
unsigned tmpNum;
|
||||
|
||||
//name
|
||||
get(source, tmpStr);
|
||||
target.setName(tmpStr);
|
||||
|
||||
// id
|
||||
get(source, tmpNum);
|
||||
target.setID(tmpNum);
|
||||
|
||||
// data
|
||||
get(source, tmpStr);
|
||||
target.setData(tmpStr);
|
||||
}
|
||||
|
||||
void put(ByteStream & target, const AuctionTransfer::Character &source)
|
||||
{
|
||||
put(target, source.getName());
|
||||
put(target, source.getID());
|
||||
put(target, source.getData());
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
#ifndef CHARACTER_H
|
||||
#define CHARACTER_H
|
||||
|
||||
#include "Base/Archive.h"
|
||||
|
||||
namespace AuctionTransfer
|
||||
{
|
||||
|
||||
|
||||
class Character
|
||||
{
|
||||
public:
|
||||
// constructors
|
||||
Character()
|
||||
: m_name(""), m_id(0), m_XMLdata("")
|
||||
{
|
||||
}
|
||||
|
||||
Character(const std::string &name, unsigned id, const std::string &xmlData)
|
||||
: m_name(name), m_id(id), m_XMLdata(xmlData)
|
||||
{
|
||||
}
|
||||
|
||||
Character(const Character &character)
|
||||
: m_name(character.getName()), m_id(character.getID()), m_XMLdata(character.getData())
|
||||
{
|
||||
}
|
||||
|
||||
// destructor
|
||||
~Character()
|
||||
{
|
||||
}
|
||||
|
||||
// accessor methods
|
||||
std::string getName() const { return m_name; }
|
||||
unsigned getID() const { return m_id; }
|
||||
std::string getData() const { return m_XMLdata; }
|
||||
|
||||
void setName(const std::string name) { m_name = name; }
|
||||
void setID(unsigned id) { m_id = id; }
|
||||
void setData(const std::string data) { m_XMLdata = data; }
|
||||
|
||||
protected:
|
||||
std::string m_name;
|
||||
unsigned m_id;
|
||||
std::string m_XMLdata;
|
||||
};
|
||||
|
||||
}; // namespace AuctionTransfer
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
|
||||
namespace Base
|
||||
{
|
||||
|
||||
void get(ByteStream::ReadIterator & source, AuctionTransfer::Character & target);
|
||||
void put(ByteStream & target, const AuctionTransfer::Character & source);
|
||||
};
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif //CHARACTER_H
|
||||
|
||||
Binary file not shown.
+231
@@ -0,0 +1,231 @@
|
||||
#include "Request.h"
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
namespace AuctionTransfer
|
||||
{
|
||||
void put(Base::ByteStream &msg, const Blob &source);
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
Blob::Blob(const unsigned char *data, unsigned len)
|
||||
: m_data(NULL),
|
||||
m_len(len)
|
||||
{
|
||||
if (m_len > 0)
|
||||
{
|
||||
m_data = new unsigned char [m_len];
|
||||
memcpy(m_data, data, m_len);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
Blob::Blob(const Blob &cpy)
|
||||
: m_data(NULL),
|
||||
m_len(cpy.m_len)
|
||||
{
|
||||
if (m_len > 0)
|
||||
{
|
||||
m_data = new unsigned char [m_len];
|
||||
memcpy(m_data, cpy.m_data, m_len);
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
Blob::~Blob()
|
||||
{
|
||||
if (m_data)
|
||||
{
|
||||
delete [] m_data;
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
Blob & Blob::operator =(const Blob &cpy)
|
||||
{
|
||||
if (this != &cpy)
|
||||
{
|
||||
//copy
|
||||
if (m_data)
|
||||
{
|
||||
delete [] m_data;
|
||||
m_data = NULL;
|
||||
}
|
||||
|
||||
m_len = cpy.m_len;
|
||||
|
||||
if (m_len > 0)
|
||||
{
|
||||
m_data = new unsigned char [m_len];
|
||||
memcpy(m_data, cpy.m_data, m_len);
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
ReplyRequest::ReplyRequest( RequestTypes type, unsigned serverTrack, unsigned responseCode )
|
||||
: GenericRequest((short)type, serverTrack), m_responseCode(responseCode)
|
||||
{
|
||||
}
|
||||
|
||||
void ReplyRequest::pack(Base::ByteStream &msg)
|
||||
{
|
||||
put(msg, m_type);
|
||||
put(msg, m_track);
|
||||
put(msg, m_server_track);
|
||||
put(msg, m_responseCode);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
CommonRequest::CommonRequest( RequestTypes type, unsigned serverTrack, long long transactionID )
|
||||
: GenericRequest((short)type, serverTrack), m_transactionID(transactionID)
|
||||
{
|
||||
}
|
||||
|
||||
void CommonRequest::pack(Base::ByteStream &msg)
|
||||
{
|
||||
put(msg, m_type);
|
||||
put(msg, m_track);
|
||||
put(msg, m_transactionID);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
GetIDRequest::GetIDRequest( RequestTypes type, unsigned serverTrack )
|
||||
: GenericRequest((short)type, serverTrack)
|
||||
{
|
||||
}
|
||||
|
||||
void GetIDRequest::pack(Base::ByteStream &msg)
|
||||
{
|
||||
put(msg, m_type);
|
||||
put(msg, m_track);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
SendPrepareCompressedRequest::SendPrepareCompressedRequest(RequestTypes type, unsigned serverTrack, const char *serverID, long long transactionID, unsigned stationID, unsigned characterID, long long assetID, const unsigned char *xmlAsset, unsigned length)
|
||||
: GenericRequest((short)type, serverTrack),
|
||||
m_transactionID(transactionID),
|
||||
m_stationID(stationID),
|
||||
m_characterID(characterID),
|
||||
m_assetID(assetID),
|
||||
m_serverID(serverID),
|
||||
m_data(xmlAsset, length)
|
||||
{
|
||||
}
|
||||
|
||||
void SendPrepareCompressedRequest::pack(Base::ByteStream &msg)
|
||||
{
|
||||
put(msg, m_type);
|
||||
put(msg, m_track);
|
||||
put(msg, m_serverID);
|
||||
put(msg, m_transactionID);
|
||||
put(msg, m_stationID);
|
||||
put(msg, m_characterID);
|
||||
put(msg, m_assetID);
|
||||
put(msg, m_data);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
SendPrepareRequest::SendPrepareRequest( RequestTypes type, unsigned serverTrack, const char *serverID, long long transactionID, unsigned stationID, unsigned characterID, long long assetID, const char *xml )
|
||||
: GenericRequest((short)type, serverTrack),
|
||||
m_transactionID(transactionID),
|
||||
m_stationID(stationID),
|
||||
m_characterID(characterID),
|
||||
m_assetID(assetID),
|
||||
m_xml(xml),
|
||||
m_serverID(serverID)
|
||||
{
|
||||
}
|
||||
|
||||
void SendPrepareRequest::pack(Base::ByteStream &msg)
|
||||
{
|
||||
put(msg, m_type);
|
||||
put(msg, m_track);
|
||||
put(msg, m_serverID);
|
||||
put(msg, m_transactionID);
|
||||
put(msg, m_stationID);
|
||||
put(msg, m_characterID);
|
||||
put(msg, m_assetID);
|
||||
put(msg, m_xml);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
ReplyGetCharacterListRequest::ReplyGetCharacterListRequest(RequestTypes type, unsigned serverTrack, unsigned responseCode, const Character characters[], unsigned numCharacters)
|
||||
: GenericRequest((short)type, serverTrack), m_responseCode(responseCode)
|
||||
{
|
||||
for(unsigned i = 0; i < numCharacters; i++)
|
||||
{
|
||||
m_characters.push_back(characters[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void ReplyGetCharacterListRequest::pack(Base::ByteStream &msg)
|
||||
{
|
||||
put(msg, m_type);
|
||||
put(msg, m_track);
|
||||
put(msg, m_server_track);
|
||||
put(msg, m_responseCode);
|
||||
put(msg, (unsigned)m_characters.size());
|
||||
for(unsigned i = 0; i < m_characters.size(); i++)
|
||||
{
|
||||
put(msg, m_characters[i]);
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
IdentifyServerRequest::IdentifyServerRequest(RequestTypes type, unsigned serverTrack, const char *serverID[], unsigned numIDs)
|
||||
: GenericRequest((short)type, serverTrack)
|
||||
{
|
||||
for(unsigned i = 0; i < numIDs; i++)
|
||||
{
|
||||
m_serverIDs.push_back(serverID[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void IdentifyServerRequest::pack(Base::ByteStream &msg)
|
||||
{
|
||||
put(msg, m_type);
|
||||
put(msg, m_track);
|
||||
put(msg, (unsigned)m_serverIDs.size());
|
||||
for(unsigned i = 0; i < m_serverIDs.size(); i++)
|
||||
{
|
||||
put(msg, m_serverIDs[i]);
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
SendAuditRequest::SendAuditRequest( RequestTypes type, unsigned serverTrack, const char *gameCode, const char *serverCode,
|
||||
long long inGameAssetID, unsigned stationID, const char *event, const char *message)
|
||||
: GenericRequest((short)type, serverTrack), m_gameCode(gameCode), m_serverCode(serverCode), m_assetID(inGameAssetID),
|
||||
m_userID(stationID), m_event(event), m_message(message)
|
||||
{
|
||||
}
|
||||
|
||||
void SendAuditRequest::pack(Base::ByteStream &msg)
|
||||
{
|
||||
put(msg, m_type);
|
||||
put(msg, m_track);
|
||||
put(msg, m_gameCode);
|
||||
put(msg, m_serverCode);
|
||||
put(msg, m_assetID);
|
||||
put(msg, m_userID);
|
||||
put(msg, m_event);
|
||||
put(msg, m_message);
|
||||
}
|
||||
|
||||
void put(Base::ByteStream &msg, const Blob &source)
|
||||
{
|
||||
put(msg, source.getLen());
|
||||
|
||||
if (source.getLen() > 0)
|
||||
{
|
||||
put(msg, source.getData(), source.getLen());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}; // namespace
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
#ifndef REQUEST_H
|
||||
#define REQUEST_H
|
||||
|
||||
#include <ATGenericAPI/GenericMessage.h>
|
||||
#include <Base/Archive.h>
|
||||
#include "AuctionTransferEnum.h"
|
||||
#include "Character.h"
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
namespace AuctionTransfer
|
||||
{
|
||||
|
||||
class Blob
|
||||
{
|
||||
public:
|
||||
Blob() : m_data(0), m_len(0) {}
|
||||
Blob(const unsigned char *data, unsigned len);
|
||||
Blob(const Blob &cpy);
|
||||
~Blob();
|
||||
|
||||
Blob & operator =(const Blob &cpy);
|
||||
|
||||
const unsigned char *getData() const { return m_data; }
|
||||
unsigned getLen() const { return m_len; }
|
||||
|
||||
unsigned char *m_data;
|
||||
unsigned m_len;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class ReplyRequest: public GenericRequest
|
||||
{
|
||||
public:
|
||||
ReplyRequest(RequestTypes type, unsigned serverTrack, unsigned responseCode);
|
||||
virtual ~ReplyRequest() {};
|
||||
|
||||
void pack(Base::ByteStream &msg);
|
||||
private:
|
||||
unsigned m_responseCode;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class CommonRequest: public GenericRequest
|
||||
{
|
||||
public:
|
||||
CommonRequest(RequestTypes type, unsigned serverTrack, long long transactionID);
|
||||
virtual ~CommonRequest() {};
|
||||
|
||||
void pack(Base::ByteStream &msg);
|
||||
private:
|
||||
long long m_transactionID;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class GetIDRequest: public GenericRequest
|
||||
{
|
||||
public:
|
||||
GetIDRequest(RequestTypes type, unsigned serverTrack);
|
||||
virtual ~GetIDRequest() {};
|
||||
|
||||
void pack(Base::ByteStream &msg);
|
||||
private:
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class SendPrepareRequest: public GenericRequest
|
||||
{
|
||||
public:
|
||||
SendPrepareRequest(RequestTypes type, unsigned serverTrack, const char *serverID, long long transactionID, unsigned stationID, unsigned characterID, long long assetID, const char *xmlAsset);
|
||||
virtual ~SendPrepareRequest() {};
|
||||
|
||||
void pack(Base::ByteStream &msg);
|
||||
private:
|
||||
long long m_transactionID;
|
||||
unsigned m_stationID;
|
||||
unsigned m_characterID;
|
||||
long long m_assetID;
|
||||
std::string m_xml;
|
||||
std::string m_serverID;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class SendPrepareCompressedRequest: public GenericRequest
|
||||
{
|
||||
public:
|
||||
SendPrepareCompressedRequest(RequestTypes type, unsigned serverTrack, const char *serverID, long long transactionID, unsigned stationID, unsigned characterID, long long assetID, const unsigned char *xmlAsset, unsigned length);
|
||||
virtual ~SendPrepareCompressedRequest() {};
|
||||
|
||||
void pack(Base::ByteStream &msg);
|
||||
private:
|
||||
long long m_transactionID;
|
||||
unsigned m_stationID;
|
||||
unsigned m_characterID;
|
||||
long long m_assetID;
|
||||
//std::string m_xml;
|
||||
std::string m_serverID;
|
||||
Blob m_data;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class ReplyGetCharacterListRequest: public GenericRequest
|
||||
{
|
||||
public:
|
||||
ReplyGetCharacterListRequest(RequestTypes type, unsigned serverTrack, unsigned responseCode, const Character characters[], unsigned numCharacters);
|
||||
virtual ~ReplyGetCharacterListRequest() {};
|
||||
|
||||
void pack(Base::ByteStream &msg);
|
||||
private:
|
||||
unsigned m_responseCode;
|
||||
std::vector<Character> m_characters;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class IdentifyServerRequest: public GenericRequest
|
||||
{
|
||||
public:
|
||||
IdentifyServerRequest(RequestTypes type, unsigned serverTrack, const char *serverID[], unsigned numIDs);
|
||||
virtual ~IdentifyServerRequest() {};
|
||||
|
||||
void pack(Base::ByteStream &msg);
|
||||
private:
|
||||
std::vector<std::string> m_serverIDs;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class SendAuditRequest : public GenericRequest
|
||||
{
|
||||
public:
|
||||
SendAuditRequest( RequestTypes type, unsigned serverTrack, const char *gameCode, const char *serverCode,
|
||||
long long inGameAssetID, unsigned stationID, const char *event, const char *message);
|
||||
~SendAuditRequest() {};
|
||||
void pack(Base::ByteStream &msg);
|
||||
private:
|
||||
std::string m_gameCode;
|
||||
std::string m_serverCode;
|
||||
long long m_assetID;
|
||||
unsigned m_userID;
|
||||
std::string m_event;
|
||||
std::string m_message;
|
||||
|
||||
};
|
||||
}; // namespace
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
#endif //REQUEST_H
|
||||
|
||||
Binary file not shown.
+17
@@ -0,0 +1,17 @@
|
||||
#include "Response.h"
|
||||
|
||||
namespace AuctionTransfer
|
||||
{
|
||||
GetIDResponse::GetIDResponse(RequestTypes type, void *user)
|
||||
: GenericResponse( (short)type, TRANSFER_SERVER_TIME_OUT, user), m_transactionID(-1)
|
||||
{
|
||||
}
|
||||
|
||||
void GetIDResponse::unpack(Base::ByteStream::ReadIterator &iter)
|
||||
{
|
||||
get(iter, m_type);
|
||||
get(iter, m_track);
|
||||
get(iter, m_result);
|
||||
get(iter, m_transactionID);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
#ifndef RESPONSE_H
|
||||
#define RESPONSE_H
|
||||
|
||||
#include <Base/Archive.h>
|
||||
#include <ATGenericAPI/GenericMessage.h>
|
||||
#include "AuctionTransferEnum.h"
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
namespace AuctionTransfer
|
||||
{
|
||||
|
||||
class CommonResponse : public GenericResponse
|
||||
{
|
||||
public:
|
||||
CommonResponse(RequestTypes type, void *user) : GenericResponse((short)type, TRANSFER_SERVER_TIME_OUT, user) {}
|
||||
virtual ~CommonResponse() {}
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
class GetIDResponse : public GenericResponse
|
||||
{
|
||||
public:
|
||||
GetIDResponse(RequestTypes type, void *user);
|
||||
virtual ~GetIDResponse() {}
|
||||
long long getNewID() { return m_transactionID; }
|
||||
virtual void unpack(Base::ByteStream::ReadIterator &iter);
|
||||
private:
|
||||
long long m_transactionID;
|
||||
};
|
||||
|
||||
|
||||
}; // namespace AuctionTransfer
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#endif //RESPONSE_H
|
||||
Binary file not shown.
+119
@@ -0,0 +1,119 @@
|
||||
#include "Clock.h"
|
||||
|
||||
#include <time.h>
|
||||
|
||||
#ifdef WIN32
|
||||
#include <winsock.h>
|
||||
#else //WIN32
|
||||
#include <sys/stat.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
Clock::Clock()
|
||||
: m_lastStart(0),
|
||||
m_totalRunTime(0)
|
||||
{
|
||||
}
|
||||
|
||||
ClockStamp Clock::getCurTime()
|
||||
{
|
||||
#if defined(WIN32)
|
||||
static int sClockHigh = 0;
|
||||
static ClockStamp sClockLast = 0;
|
||||
|
||||
int high = sClockHigh;
|
||||
DWORD low = GetTickCount();
|
||||
ClockStamp holdLast = sClockLast; // this should be interlocked too
|
||||
ClockStamp ret = ((ClockStamp)high << 32) | low;
|
||||
|
||||
// crazy trick to allow threading to work, by putting in a 1000 second fudge factor, we effective say
|
||||
// that it is ok to time-slice us at a bad point and we will still handle it, provided that our thread
|
||||
// gets processing time again within 1000 seconds
|
||||
if (ret < holdLast - 1000000)
|
||||
{
|
||||
sClockHigh = high + 1;
|
||||
ret = ((ClockStamp)high << 32) | low;
|
||||
}
|
||||
|
||||
sClockLast = ret; // this really should be interlocked to be totally safe since it is a 64 bit value, but I don't see a way to do that and am not sure it would mess up anything but the one call anyways
|
||||
|
||||
return ret;
|
||||
#else
|
||||
struct timeval tv;
|
||||
int err;
|
||||
err = gettimeofday(&tv, NULL);
|
||||
return (static_cast<ClockStamp>(tv.tv_sec) * 1000 + static_cast<ClockStamp>(tv.tv_usec / 1000));
|
||||
#endif
|
||||
}
|
||||
|
||||
ClockStamp Clock::getElapsedSinceLastStart()
|
||||
{
|
||||
if (m_lastStart == 0)
|
||||
{
|
||||
//hasn't been started
|
||||
return 0;
|
||||
}
|
||||
|
||||
ClockStamp elapsed = getCurTime() - m_lastStart;
|
||||
|
||||
if (elapsed > 2000000000) // only time differences up to 23 days can be measured with this function
|
||||
elapsed = 2000000000;
|
||||
|
||||
return elapsed;
|
||||
}
|
||||
|
||||
void Clock::start()
|
||||
{
|
||||
if (m_lastStart != 0)
|
||||
{
|
||||
//already started
|
||||
return;
|
||||
}
|
||||
|
||||
//set last start to curtime
|
||||
m_lastStart = getCurTime();
|
||||
}
|
||||
|
||||
void Clock::stop()
|
||||
{
|
||||
if (m_lastStart == 0)
|
||||
{
|
||||
//need to start before stoping
|
||||
return;
|
||||
}
|
||||
|
||||
m_totalRunTime += (unsigned)getElapsedSinceLastStart(); //rlsmith - explicit cast to prevent compiler warning
|
||||
m_lastStart = 0;
|
||||
}
|
||||
|
||||
|
||||
bool Clock::isDone(unsigned runTime)
|
||||
{
|
||||
if (m_lastStart == 0)
|
||||
{
|
||||
//never started, so say no
|
||||
return false;
|
||||
}
|
||||
|
||||
ClockStamp totalElapsed = getElapsedSinceLastStart() + m_totalRunTime;
|
||||
|
||||
return (totalElapsed >= runTime);
|
||||
}
|
||||
|
||||
void Clock::reset()
|
||||
{
|
||||
m_lastStart = 0;
|
||||
m_totalRunTime = 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#ifndef CLOCK_H
|
||||
#define CLOCK_H
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(WIN32)
|
||||
typedef __int64 ClockStamp;
|
||||
#else
|
||||
typedef long long ClockStamp;
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief A Clock can be used as a millisecond timer.
|
||||
*/
|
||||
class Clock
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Creates a clock, must still be started with Clock::start method.
|
||||
*
|
||||
* Once created, a clock can be started, and stoped as often as possible.
|
||||
*/
|
||||
Clock();
|
||||
|
||||
|
||||
/**
|
||||
* @brief Starts the timer running.
|
||||
*/
|
||||
void start();
|
||||
|
||||
/**
|
||||
* @brief Stops the timer from running (note: can still be started again later).
|
||||
*/
|
||||
void stop();
|
||||
|
||||
/**
|
||||
* @brief Tells you if the timer has been in the started state for longer than runTime.
|
||||
*
|
||||
* @param runTime The amount of time to test if this timer has ran longer than.
|
||||
*
|
||||
* @return 'true' if timer has ran for longer than or equal to runTime, false otherwise.
|
||||
*/
|
||||
bool isDone(unsigned runTime);
|
||||
|
||||
/**
|
||||
* @brief Resets this clock (as if it were never started).
|
||||
*/
|
||||
void reset();
|
||||
|
||||
private:
|
||||
ClockStamp m_lastStart;
|
||||
unsigned m_totalRunTime;
|
||||
|
||||
ClockStamp getCurTime();
|
||||
ClockStamp getElapsedSinceLastStart();
|
||||
};
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
|
||||
#endif //CLOCK_H
|
||||
|
||||
|
||||
BIN
Binary file not shown.
+33
@@ -0,0 +1,33 @@
|
||||
#include "IPAddress.h"
|
||||
|
||||
#if defined(WIN32)
|
||||
#include <winsock.h>
|
||||
typedef int socklen_t;
|
||||
#else // for non-windows platforms (linux)
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/socket.h>
|
||||
#include <string.h>
|
||||
#endif
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
IPAddress::IPAddress(unsigned int ip)
|
||||
: m_IP(ip)
|
||||
{
|
||||
}
|
||||
|
||||
char *IPAddress::GetAddress(char *buffer) const
|
||||
{
|
||||
struct sockaddr_in addr;
|
||||
addr.sin_addr.s_addr = m_IP;
|
||||
strcpy(buffer, inet_ntoa(addr.sin_addr));
|
||||
return(buffer);
|
||||
}
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#ifndef TCPIPADDRESS_H
|
||||
#define TCPIPADDRESS_H
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Container object for IP Address.
|
||||
*/
|
||||
class IPAddress
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Constructor, sets the ip address if specified.
|
||||
*/
|
||||
IPAddress(unsigned int ip = 0);
|
||||
|
||||
/**
|
||||
* @brief Sets the ip address.
|
||||
*/
|
||||
void SetAddress(unsigned int ip){ m_IP = ip; }
|
||||
|
||||
/**
|
||||
* @brief Returns the unsigned int representation of this address.
|
||||
*/
|
||||
unsigned int GetAddress() const { return m_IP; }
|
||||
|
||||
/**
|
||||
* @brief Used to retreive the the dot-notation represenatatiion of this address.
|
||||
*
|
||||
* @param buffer A pointer to the buffer to place the ip address into.
|
||||
* Must be at least 17 characters long, will be null terminated.
|
||||
*
|
||||
* @return A pointer to the buffer the address was placed into.
|
||||
*/
|
||||
char *GetAddress(char *buffer) const;
|
||||
|
||||
private:
|
||||
unsigned int m_IP;
|
||||
};
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif //TCPIPADDRESS_H
|
||||
|
||||
|
||||
BIN
Binary file not shown.
+94
@@ -0,0 +1,94 @@
|
||||
#include "TcpBlockAllocator.h"
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
TcpBlockAllocator::TcpBlockAllocator(const unsigned initSize, const unsigned initCount)
|
||||
: m_freeHead(NULL), m_blockCount(initCount), m_blockSize(initSize), m_numAvailBlocks(0)
|
||||
{
|
||||
realloc();
|
||||
}
|
||||
|
||||
TcpBlockAllocator::~TcpBlockAllocator()
|
||||
{
|
||||
while(m_freeHead)
|
||||
{
|
||||
data_block *tmp = m_freeHead;
|
||||
m_freeHead = m_freeHead->m_next;
|
||||
delete[] tmp->m_data;
|
||||
delete tmp;m_numAvailBlocks--;
|
||||
}
|
||||
}
|
||||
|
||||
data_block *TcpBlockAllocator::getBlock()
|
||||
{
|
||||
data_block *tmp;
|
||||
|
||||
if(!m_freeHead)
|
||||
{
|
||||
realloc();
|
||||
}
|
||||
|
||||
tmp = m_freeHead;
|
||||
m_freeHead = m_freeHead->m_next;
|
||||
tmp->m_next = NULL;
|
||||
m_numAvailBlocks--;
|
||||
return(tmp);
|
||||
}
|
||||
|
||||
void TcpBlockAllocator::returnBlock(data_block *b)
|
||||
{
|
||||
b->m_usedSize = 0;
|
||||
b->m_sentSize = 0;
|
||||
|
||||
if (m_numAvailBlocks >= m_blockCount)
|
||||
{
|
||||
delete[] b->m_data;
|
||||
delete b;
|
||||
return;
|
||||
}
|
||||
|
||||
b->m_next = m_freeHead;
|
||||
m_freeHead = b; m_numAvailBlocks++;
|
||||
}
|
||||
|
||||
void TcpBlockAllocator::realloc()
|
||||
{
|
||||
data_block *tmp = NULL, *cursor = NULL;
|
||||
|
||||
tmp = new data_block; m_numAvailBlocks++;
|
||||
cursor = tmp;
|
||||
memset(cursor, 0, sizeof(data_block));
|
||||
cursor->m_data = new char[m_blockSize];
|
||||
cursor->m_totalSize = m_blockSize;
|
||||
|
||||
for(unsigned i = 1; i < m_blockCount; i++)
|
||||
{
|
||||
cursor->m_next = new data_block; m_numAvailBlocks++;
|
||||
cursor = cursor->m_next;
|
||||
memset(cursor, 0, sizeof(data_block));
|
||||
cursor->m_data = new char[m_blockSize];
|
||||
cursor->m_totalSize = m_blockSize;
|
||||
}
|
||||
|
||||
if(m_freeHead)
|
||||
{
|
||||
cursor->m_next = m_freeHead;
|
||||
m_freeHead = tmp;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_freeHead = tmp;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#ifndef TCPBLOCKALLOCATOR_H
|
||||
#define TCPBLOCKALLOCATOR_H
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
struct data_block
|
||||
{
|
||||
unsigned m_usedSize;
|
||||
unsigned m_sentSize;
|
||||
unsigned m_totalSize;
|
||||
char *m_data;
|
||||
data_block *m_next;
|
||||
};
|
||||
|
||||
class TcpBlockAllocator
|
||||
{
|
||||
public:
|
||||
TcpBlockAllocator(const unsigned initSize, const unsigned initCount);
|
||||
~TcpBlockAllocator();
|
||||
data_block *getBlock();
|
||||
void returnBlock(data_block *);
|
||||
|
||||
private:
|
||||
void realloc();
|
||||
data_block *m_freeHead;
|
||||
unsigned m_blockCount;
|
||||
unsigned m_blockSize;
|
||||
unsigned m_numAvailBlocks;
|
||||
};
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
#endif //TCPBLOCKALLOCATOR_H
|
||||
|
||||
|
||||
|
||||
|
||||
BIN
Binary file not shown.
+787
@@ -0,0 +1,787 @@
|
||||
#include "TcpConnection.h"
|
||||
#include "TcpManager.h"
|
||||
#include "Clock.h"
|
||||
#include <errno.h>
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
|
||||
//used when want to open new connection with this socket
|
||||
TcpConnection::TcpConnection(TcpManager *tcpManager, TcpBlockAllocator *sendAlloc, TcpManager::TcpParams ¶ms, const IPAddress &destIP, short destPort, unsigned timeout)
|
||||
: m_nextConnection(NULL),
|
||||
m_prevConnection(NULL),
|
||||
m_socket(INVALID_SOCKET),
|
||||
m_nextKeepAliveConnection(NULL),
|
||||
m_prevKeepAliveConnection(NULL),
|
||||
m_aliveListId(tcpManager->m_aliveList.m_listID),
|
||||
m_nextRecvDataConnection(NULL),
|
||||
m_prevRecvDataConnection(NULL),
|
||||
m_recvDataListId(tcpManager->m_dataList.m_listID),
|
||||
m_manager(tcpManager),
|
||||
m_status(StatusNegotiating),
|
||||
m_handler(NULL),
|
||||
m_destIP(destIP),
|
||||
m_destPort(destPort),
|
||||
m_refCount(0),
|
||||
m_sendAllocator(sendAlloc),
|
||||
m_head(NULL),
|
||||
m_tail(NULL),
|
||||
m_bytesRead(0),
|
||||
m_bytesNeeded(0),
|
||||
m_params(params),
|
||||
m_recvBuff(NULL),
|
||||
m_connectTimeout(timeout),
|
||||
m_connectTimer(),
|
||||
m_wasConRemovedFromMgr(false)
|
||||
{
|
||||
//start connection timer
|
||||
m_connectTimer.start();
|
||||
|
||||
memset(&m_addr, 0, sizeof(m_addr));
|
||||
if (m_params.maxRecvMessageSize != 0)
|
||||
{
|
||||
m_recvBuff = new char[m_params.maxRecvMessageSize];
|
||||
}
|
||||
|
||||
m_socket = socket(AF_INET, SOCK_STREAM, 0);
|
||||
|
||||
|
||||
setOptions();
|
||||
|
||||
|
||||
m_addr.sin_family = AF_INET;
|
||||
m_addr.sin_port = htons(m_destPort);
|
||||
m_addr.sin_addr.s_addr = m_destIP.GetAddress();
|
||||
|
||||
int err = connect(m_socket, (sockaddr *)&m_addr, sizeof(m_addr));
|
||||
|
||||
if(err == SOCKET_ERROR)
|
||||
{
|
||||
#ifdef WIN32
|
||||
int sockerr = WSAGetLastError();
|
||||
if(sockerr != WSAEWOULDBLOCK)
|
||||
{
|
||||
//a real error
|
||||
m_status = StatusDisconnected;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_status = StatusNegotiating;
|
||||
}
|
||||
|
||||
#else // UNIX
|
||||
|
||||
if (errno != EINPROGRESS)
|
||||
{
|
||||
m_status = StatusDisconnected;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_status = StatusNegotiating;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
//we are connected, wow
|
||||
m_status = StatusConnected;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//used when server mode creates new connection object representing a connect request
|
||||
TcpConnection::TcpConnection(TcpManager *tcpManager, TcpBlockAllocator *sendAlloc, TcpManager::TcpParams ¶ms, SOCKET socket, const IPAddress &destIP, short destPort)
|
||||
: m_nextConnection(NULL),
|
||||
m_prevConnection(NULL),
|
||||
m_socket(socket),
|
||||
m_nextKeepAliveConnection(NULL),
|
||||
m_prevKeepAliveConnection(NULL),
|
||||
m_aliveListId(tcpManager->m_aliveList.m_listID),
|
||||
m_nextRecvDataConnection(NULL),
|
||||
m_prevRecvDataConnection(NULL),
|
||||
m_recvDataListId(tcpManager->m_dataList.m_listID),
|
||||
m_manager(tcpManager),
|
||||
m_status(StatusConnected),
|
||||
m_handler(NULL),
|
||||
m_destIP(destIP),
|
||||
m_destPort(destPort),
|
||||
m_refCount(0),
|
||||
m_sendAllocator(sendAlloc),
|
||||
m_head(NULL),
|
||||
m_tail(NULL),
|
||||
m_bytesRead(0),
|
||||
m_bytesNeeded(0),
|
||||
m_params(params),
|
||||
m_recvBuff(NULL),
|
||||
m_connectTimeout(0),
|
||||
m_connectTimer(),
|
||||
m_wasConRemovedFromMgr(false)
|
||||
{
|
||||
memset(&m_addr, 0, sizeof(m_addr));
|
||||
if (m_params.maxRecvMessageSize != 0)
|
||||
{
|
||||
m_recvBuff = new char[m_params.maxRecvMessageSize];
|
||||
}
|
||||
|
||||
|
||||
setOptions();
|
||||
}
|
||||
|
||||
void TcpConnection::setOptions()
|
||||
{
|
||||
if (m_socket != INVALID_SOCKET)
|
||||
{
|
||||
#if defined(WIN32)
|
||||
unsigned long isNonBlocking = 1;
|
||||
int outBufSize = m_params.outgoingBufferSize;
|
||||
int inBufSize = m_params.incomingBufferSize;
|
||||
int keepAlive = 1;
|
||||
int reuseAddr = 1;
|
||||
struct linger ld;
|
||||
ld.l_onoff = 0;
|
||||
ld.l_linger = 0;
|
||||
|
||||
if (ioctlsocket(m_socket, FIONBIO, &isNonBlocking) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, (char *)&outBufSize, sizeof(outBufSize)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char *)&inBufSize, sizeof(inBufSize)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepAlive, sizeof(keepAlive)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuseAddr, sizeof(reuseAddr)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_LINGER, (char *)&ld, sizeof(ld)) != 0 )
|
||||
{
|
||||
//bummer, but no need to crash now.... ?
|
||||
}
|
||||
|
||||
#else // linux is to remain the default compile mode
|
||||
unsigned long isNonBlocking = 1;
|
||||
unsigned long keepAlive = 1;
|
||||
unsigned long outBufSize = m_params.outgoingBufferSize;
|
||||
unsigned long inBufSize = m_params.incomingBufferSize;
|
||||
unsigned long reuseAddr = 1;
|
||||
struct linger ld;
|
||||
ld.l_onoff = 0;
|
||||
ld.l_linger = 0;
|
||||
|
||||
if (ioctl(m_socket, FIONBIO, &isNonBlocking) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, &outBufSize, sizeof(outBufSize)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, &inBufSize, sizeof(inBufSize)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(keepAlive)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_LINGER, &ld, sizeof(ld)) != 0)
|
||||
{
|
||||
//bummer, but no need to crash now.... ?
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int TcpConnection::finishConnect()
|
||||
{
|
||||
AddRef();
|
||||
int returnVal = 0;
|
||||
/**< returns < 0 if fatal error and connect will not work, =0 if need more time, >0 if connect completed */
|
||||
switch (m_status)
|
||||
{
|
||||
case StatusDisconnected:
|
||||
{
|
||||
//something went wrong
|
||||
Disconnect(false);
|
||||
returnVal = -1;
|
||||
}
|
||||
break;
|
||||
case StatusNegotiating:
|
||||
{
|
||||
#ifdef WIN32
|
||||
//try to finish connection
|
||||
fd_set wrSet;
|
||||
FD_ZERO(&wrSet);
|
||||
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4127)
|
||||
FD_SET(m_socket, &wrSet);
|
||||
#pragma warning(pop)
|
||||
|
||||
timeval t;
|
||||
t.tv_sec = 0;
|
||||
t.tv_usec = 0;
|
||||
|
||||
int err = select(m_socket + 1, NULL, &wrSet, NULL, &t);
|
||||
|
||||
if (err == 0)
|
||||
{
|
||||
//needs more time
|
||||
returnVal = 0;
|
||||
}
|
||||
else if (err == SOCKET_ERROR)
|
||||
{
|
||||
//huhoh, let's hope it needs more time
|
||||
int sockerr = WSAGetLastError();
|
||||
if (sockerr == WSAEINPROGRESS
|
||||
|| sockerr == WSAEWOULDBLOCK
|
||||
|| sockerr == WSAEALREADY
|
||||
|| sockerr == WSAEINVAL)
|
||||
{
|
||||
//yep
|
||||
returnVal = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
Disconnect(false);
|
||||
returnVal = -1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//check if write bit set for socket
|
||||
if (FD_ISSET(m_socket, &wrSet))
|
||||
{
|
||||
//connection complete
|
||||
m_status = StatusConnected;
|
||||
returnVal = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//give it more time??
|
||||
returnVal = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#else // not WIN32
|
||||
int err = connect(m_socket, (sockaddr *)&m_addr, sizeof(m_addr));
|
||||
|
||||
if(err == SOCKET_ERROR)
|
||||
{
|
||||
if (errno != EINPROGRESS && errno != EALREADY)
|
||||
{
|
||||
Disconnect(false);
|
||||
returnVal = -1;//failure
|
||||
}
|
||||
else
|
||||
{
|
||||
returnVal = 0;//need to wait
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_status = StatusConnected;
|
||||
returnVal = 1;//connect success
|
||||
}
|
||||
#endif
|
||||
}
|
||||
break;
|
||||
case StatusConnected:
|
||||
{
|
||||
//wierd, shouldn't be trying to do this here
|
||||
Disconnect(true);
|
||||
returnVal = -1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (returnVal == 0 && m_connectTimeout != 0 && m_connectTimer.isDone(m_connectTimeout))
|
||||
{
|
||||
Disconnect(false);
|
||||
returnVal = -1;
|
||||
}
|
||||
else if (returnVal ==1/* && m_connectTimeout != 0*/)
|
||||
{
|
||||
//need to give, onConnect callback
|
||||
if (m_manager->m_handler)
|
||||
m_manager->m_handler->OnConnectRequest(this);
|
||||
}
|
||||
|
||||
Release();
|
||||
return returnVal;
|
||||
|
||||
}
|
||||
|
||||
|
||||
TcpConnection::~TcpConnection()
|
||||
{
|
||||
if (m_recvBuff != NULL)
|
||||
{
|
||||
delete [] m_recvBuff;
|
||||
}
|
||||
|
||||
while(m_head != NULL)
|
||||
{
|
||||
data_block *tmp = m_head;
|
||||
m_head = m_head->m_next;
|
||||
m_sendAllocator->returnBlock(tmp);
|
||||
}
|
||||
|
||||
//TODO: need to notify app if are currently connected
|
||||
}
|
||||
|
||||
void TcpConnection::Send(const char *data, unsigned int dataLen)
|
||||
{
|
||||
//add msg to buf
|
||||
int totalLen = dataLen + sizeof(int);
|
||||
|
||||
if(m_status == StatusDisconnected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_params.keepAliveDelay > 0 && m_aliveListId == m_manager->m_aliveList.m_listID)
|
||||
{
|
||||
m_aliveListId = m_manager->m_keepAliveList.m_listID;
|
||||
|
||||
if (m_prevKeepAliveConnection != NULL)
|
||||
m_prevKeepAliveConnection->m_nextKeepAliveConnection = m_nextKeepAliveConnection;
|
||||
if (m_nextKeepAliveConnection != NULL)
|
||||
m_nextKeepAliveConnection->m_prevKeepAliveConnection = m_prevKeepAliveConnection;
|
||||
if (m_manager->m_keepAliveList.m_beginList == this)
|
||||
m_manager->m_keepAliveList.m_beginList = m_nextKeepAliveConnection;
|
||||
|
||||
m_nextKeepAliveConnection = m_manager->m_aliveList.m_beginList;
|
||||
m_prevKeepAliveConnection = NULL;
|
||||
if (m_manager->m_aliveList.m_beginList != NULL)
|
||||
m_manager->m_aliveList.m_beginList->m_prevKeepAliveConnection = this;
|
||||
m_manager->m_aliveList.m_beginList = this;
|
||||
}
|
||||
|
||||
|
||||
data_block *work = NULL;
|
||||
|
||||
// this connection has no send buffer. Get a block
|
||||
if(!m_tail)
|
||||
{
|
||||
m_head = m_sendAllocator->getBlock();
|
||||
m_tail = m_head;
|
||||
}
|
||||
work = m_tail;
|
||||
|
||||
//send message len first
|
||||
unsigned nLen = htonl(totalLen);
|
||||
unsigned lenLength = sizeof(int);
|
||||
unsigned lenIndex = 0;
|
||||
while(lenIndex < lenLength)
|
||||
{
|
||||
if ((lenLength - lenIndex) <= (work->m_totalSize - work->m_usedSize))
|
||||
{
|
||||
//size will fit in this block
|
||||
memcpy(work->m_data + work->m_usedSize, (char *)(&nLen) + lenIndex, lenLength - lenIndex);
|
||||
work->m_usedSize += (lenLength - lenIndex);
|
||||
lenIndex += (lenLength - lenIndex);
|
||||
}
|
||||
else
|
||||
{
|
||||
//size will not fit in this block
|
||||
memcpy(work->m_data + work->m_usedSize, (char *)(&nLen) + lenIndex, work->m_totalSize - work->m_usedSize);
|
||||
lenIndex += work->m_totalSize - work->m_usedSize;
|
||||
work->m_usedSize += work->m_totalSize - work->m_usedSize;
|
||||
work->m_next = m_sendAllocator->getBlock();
|
||||
work = work->m_next;
|
||||
m_tail = work;
|
||||
}
|
||||
}
|
||||
|
||||
//now send message payload
|
||||
unsigned messageIndex = 0;
|
||||
while(messageIndex < dataLen)
|
||||
{
|
||||
if((dataLen - messageIndex) <= (work->m_totalSize - work->m_usedSize))
|
||||
{
|
||||
// data will fit in this block
|
||||
memcpy(work->m_data + work->m_usedSize, data + messageIndex, (dataLen - messageIndex));
|
||||
work->m_usedSize += (dataLen - messageIndex);
|
||||
messageIndex += (dataLen - messageIndex);
|
||||
}
|
||||
else
|
||||
{
|
||||
// data will not fit in this block. Fill this block and get another block
|
||||
memcpy(work->m_data + work->m_usedSize, data + messageIndex, work->m_totalSize - work->m_usedSize);
|
||||
messageIndex += work->m_totalSize - work->m_usedSize;
|
||||
work->m_usedSize += work->m_totalSize - work->m_usedSize;
|
||||
work->m_next = m_sendAllocator->getBlock();
|
||||
work = work->m_next;
|
||||
m_tail = work;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
void TcpConnection::Disconnect(bool notifyApplication)
|
||||
{
|
||||
AddRef();
|
||||
m_status = StatusDisconnected;
|
||||
if (!m_wasConRemovedFromMgr)
|
||||
{
|
||||
m_manager->removeConnection(this);
|
||||
m_wasConRemovedFromMgr = true;
|
||||
}
|
||||
|
||||
|
||||
if(m_socket != INVALID_SOCKET)
|
||||
{
|
||||
#if defined(WIN32)
|
||||
closesocket(m_socket);
|
||||
#else
|
||||
close(m_socket);
|
||||
#endif
|
||||
m_socket = INVALID_SOCKET;
|
||||
}
|
||||
|
||||
|
||||
if (notifyApplication && m_handler)
|
||||
m_handler->OnTerminated(this);
|
||||
|
||||
Release();
|
||||
}
|
||||
|
||||
|
||||
void TcpConnection::AddRef()
|
||||
{
|
||||
m_refCount++;
|
||||
}
|
||||
|
||||
|
||||
void TcpConnection::Release()
|
||||
{
|
||||
if (--m_refCount == 0)
|
||||
{
|
||||
//make sure manager knows I'm gone
|
||||
if (m_status != StatusDisconnected)
|
||||
Disconnect(false);
|
||||
delete this;
|
||||
}
|
||||
}
|
||||
|
||||
int TcpConnection::processIncoming()
|
||||
{
|
||||
/**< returns < 0 if fatal error and socket has been closed,
|
||||
=0 if read anything (full or partial message),
|
||||
>0 if nothing to read now, or would block so shouldn't try again immediately. */
|
||||
|
||||
if (m_status != StatusConnected)
|
||||
{
|
||||
//wait until connect succeeds
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (m_params.noDataTimeout > 0 && m_recvDataListId == m_manager->m_dataList.m_listID)
|
||||
{
|
||||
m_recvDataListId = m_manager->m_noDataList.m_listID;
|
||||
|
||||
if (m_prevRecvDataConnection != NULL)
|
||||
m_prevRecvDataConnection->m_nextRecvDataConnection = m_nextRecvDataConnection;
|
||||
if (m_nextRecvDataConnection != NULL)
|
||||
m_nextRecvDataConnection->m_prevRecvDataConnection = m_prevRecvDataConnection;
|
||||
if (m_manager->m_noDataList.m_beginList == this)
|
||||
m_manager->m_noDataList.m_beginList = m_nextRecvDataConnection;
|
||||
|
||||
m_nextRecvDataConnection = m_manager->m_dataList.m_beginList;
|
||||
m_prevRecvDataConnection = NULL;
|
||||
if (m_manager->m_dataList.m_beginList != NULL)
|
||||
m_manager->m_dataList.m_beginList->m_prevRecvDataConnection = this;
|
||||
m_manager->m_dataList.m_beginList = this;
|
||||
}
|
||||
|
||||
|
||||
int newMsg = 0;
|
||||
|
||||
|
||||
if (m_bytesRead < sizeof(int))
|
||||
{
|
||||
//new msg
|
||||
newMsg = 1;
|
||||
//printf("socket: %d\n", m_socket);
|
||||
int ret = recv(m_socket, ((char *)(&m_bytesNeeded) + m_bytesRead),
|
||||
4 - m_bytesRead, 0);
|
||||
//fprintf(stderr, "READ: %d\n", ret);
|
||||
if (ret == 0)
|
||||
{
|
||||
//We did a select, so there should be data. Socket was closed.
|
||||
Disconnect();
|
||||
return -1;
|
||||
}
|
||||
else if (ret == -1)
|
||||
{
|
||||
if (translateRecvSocketEror())
|
||||
{
|
||||
//fatal error
|
||||
return -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//need to wait
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_bytesRead += ret;
|
||||
if (m_bytesRead < 4)
|
||||
{
|
||||
return 1;//need to wait
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
m_bytesNeeded = ntohl(m_bytesNeeded);
|
||||
|
||||
//printf("m_bytesNeeded = %i\n", m_bytesNeeded);
|
||||
if (m_bytesNeeded == sizeof(int))
|
||||
{
|
||||
//keepalive, ignore
|
||||
m_bytesRead = 0;
|
||||
m_bytesNeeded = 0;
|
||||
return 0;
|
||||
}
|
||||
else if (m_bytesNeeded < sizeof(int))
|
||||
{
|
||||
//major protocol violation
|
||||
Disconnect();
|
||||
return -1;
|
||||
}
|
||||
else if (m_params.maxRecvMessageSize == 0)
|
||||
{
|
||||
if (m_recvBuff!=NULL)
|
||||
delete [] m_recvBuff;
|
||||
m_recvBuff = new char[m_bytesNeeded-4];
|
||||
}
|
||||
else if (m_params.maxRecvMessageSize != 0 && (m_bytesNeeded-4) > m_params.maxRecvMessageSize)
|
||||
{
|
||||
//error, maxRecvMeessageSize exceeded, Disconnect
|
||||
Disconnect();
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int msgBytesRead = m_bytesRead - 4;
|
||||
int msgBytesNeeded = m_bytesNeeded - 4;
|
||||
|
||||
int ret = recv(m_socket, (char *)(m_recvBuff + msgBytesRead),
|
||||
msgBytesNeeded - msgBytesRead, 0);
|
||||
if (ret == 0 && !newMsg)
|
||||
{
|
||||
//We did a select, so there should be data. Socket was closed.
|
||||
Disconnect();
|
||||
return -1;
|
||||
}
|
||||
if (ret == -1)
|
||||
{
|
||||
if (translateRecvSocketEror())
|
||||
{
|
||||
//fatal error
|
||||
return -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//need to wait
|
||||
return 1;
|
||||
}
|
||||
} else
|
||||
{
|
||||
m_bytesRead += ret;
|
||||
}
|
||||
|
||||
if (m_bytesRead == m_bytesNeeded)
|
||||
{
|
||||
m_bytesRead = 0;
|
||||
m_bytesNeeded = 0;
|
||||
if (m_handler)
|
||||
{
|
||||
AddRef();//could get deleted during this callback
|
||||
m_handler->OnRoutePacket(this, (unsigned char *)m_recvBuff, msgBytesNeeded);
|
||||
|
||||
if (m_status == StatusDisconnected)
|
||||
{
|
||||
Release();
|
||||
return -1;
|
||||
}
|
||||
Release();
|
||||
}
|
||||
|
||||
//entire message received
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
return 1;//couldn't get entire msg
|
||||
}
|
||||
}
|
||||
|
||||
int TcpConnection::processOutgoing()
|
||||
{
|
||||
/**< returns < 0 if fatal error and socket has been closed,
|
||||
=0 if sent data, call again immediately if want to,
|
||||
>0 may have sent data, but calling again would do no good because there is either no more data to send, or would block. */
|
||||
if (m_status != StatusConnected)
|
||||
{
|
||||
//wait until connect succeeds
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
int sendError = 1;
|
||||
|
||||
// If m_head is not null, then this connection has something to send
|
||||
|
||||
|
||||
if(m_head)
|
||||
{
|
||||
|
||||
|
||||
int amt = ::send(m_socket, m_head->m_data + m_head->m_sentSize, m_head->m_usedSize - m_head->m_sentSize, 0);
|
||||
if(amt < 0)
|
||||
{
|
||||
#ifdef WIN32
|
||||
switch(WSAGetLastError())
|
||||
{
|
||||
case WSAEWOULDBLOCK:
|
||||
case WSAEINTR:
|
||||
case WSAEINPROGRESS:
|
||||
case WSAEALREADY:
|
||||
case WSA_IO_PENDING:
|
||||
case WSA_NOT_ENOUGH_MEMORY:
|
||||
case WSATRY_AGAIN:
|
||||
//try again
|
||||
sendError = 1;
|
||||
break;
|
||||
default:
|
||||
//assume broken, Disconnect
|
||||
Disconnect();
|
||||
sendError = -1;
|
||||
break;
|
||||
}
|
||||
#else //not WIN32
|
||||
|
||||
// error condition, EAGAIN is recoverable, otherwise raise an error condition. Break from loop
|
||||
switch(errno)
|
||||
{
|
||||
case EAGAIN:
|
||||
//try again
|
||||
sendError = 1;
|
||||
break;
|
||||
default:
|
||||
//assume broken, Disconnect
|
||||
Disconnect();
|
||||
sendError = -1;
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
else if(static_cast<unsigned>(amt) < (m_head->m_usedSize - m_head->m_sentSize))
|
||||
{
|
||||
// partial send: trying to do anything more now would be a waste of time. Break from loop
|
||||
m_head->m_sentSize += amt;
|
||||
sendError = 1;
|
||||
}
|
||||
else if(amt == 0)
|
||||
{
|
||||
Disconnect();
|
||||
sendError = -1;
|
||||
// client closed connection
|
||||
}
|
||||
else
|
||||
{
|
||||
// everything was sent from this block. Return it to the pool, advance m_head. Attempt to continue
|
||||
// sending
|
||||
data_block *tmp = m_head;
|
||||
if(m_tail == m_head)
|
||||
{
|
||||
m_tail = m_tail->m_next;
|
||||
m_head = m_head->m_next;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_head = m_head->m_next;
|
||||
}
|
||||
m_sendAllocator->returnBlock(tmp);
|
||||
|
||||
sendError = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return sendError;
|
||||
}
|
||||
|
||||
|
||||
bool TcpConnection::translateRecvSocketEror()
|
||||
{
|
||||
/**< returns false if fatal error and socket has been closed,
|
||||
true if should try again. */
|
||||
bool fatalError=false;
|
||||
#ifdef WIN32
|
||||
|
||||
switch(WSAGetLastError())
|
||||
{
|
||||
case WSAENOBUFS:
|
||||
case WSAEINPROGRESS:
|
||||
case WSAEINTR:
|
||||
case WSAEWOULDBLOCK:
|
||||
case WSABASEERR:
|
||||
fatalError=false;
|
||||
break;
|
||||
|
||||
case WSANOTINITIALISED:
|
||||
case WSAENETDOWN:
|
||||
case WSAEFAULT:
|
||||
case WSAENOTCONN:
|
||||
case WSAENETRESET:
|
||||
case WSAENOTSOCK:
|
||||
case WSAEOPNOTSUPP:
|
||||
case WSAESHUTDOWN:
|
||||
case WSAEMSGSIZE:
|
||||
case WSAEINVAL:
|
||||
case WSAECONNABORTED:
|
||||
case WSAETIMEDOUT:
|
||||
case WSAECONNRESET:
|
||||
default:
|
||||
//fatal
|
||||
fatalError=true;
|
||||
Disconnect();
|
||||
break;
|
||||
}
|
||||
|
||||
#else //not WIN32
|
||||
|
||||
switch(errno)
|
||||
{
|
||||
case EWOULDBLOCK:
|
||||
case EINTR:
|
||||
case ETIMEDOUT:
|
||||
case ENOBUFS:
|
||||
//try later
|
||||
fatalError=false;
|
||||
break;
|
||||
|
||||
case EBADF:
|
||||
case ECONNRESET:
|
||||
case EFAULT:
|
||||
case EINVAL:
|
||||
case ENOTCONN:
|
||||
case ENOTSOCK:
|
||||
case EOPNOTSUPP:
|
||||
case EPIPE:
|
||||
case EIO:
|
||||
case ENOMEM:
|
||||
case ENOSR:
|
||||
default:
|
||||
//fatal
|
||||
fatalError=true;
|
||||
Disconnect();
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
return fatalError;
|
||||
}
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
#ifndef TCPCONNECTION_H
|
||||
#define TCPCONNECTION_H
|
||||
|
||||
|
||||
#include "TcpHandlers.h"
|
||||
#include "TcpManager.h"
|
||||
#include "IPAddress.h"
|
||||
#include "TcpBlockAllocator.h"
|
||||
#include "Clock.h"
|
||||
|
||||
#if defined(WIN32)
|
||||
#include <winsock2.h>
|
||||
typedef int socklen_t;
|
||||
#else // for non-windows platforms (linux)
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
|
||||
/**
|
||||
* @brief Manages a single connection.
|
||||
*/
|
||||
class TcpConnection
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief The connection status.
|
||||
*/
|
||||
enum Status {
|
||||
StatusNegotiating, /**< Currently attempting to connect. */
|
||||
StatusConnected, /**< Currently connected. */
|
||||
StatusDisconnected /**< Currently disconnected. */
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Sets the handler object which will receive callback methods.
|
||||
*
|
||||
* To have the TcpConnection call your object directly when packets are received, and when the
|
||||
* connection is disconnected, you simply need to derive your class
|
||||
* (multiply if necessary) from TcpConnectionHandler, then you can use
|
||||
* this method to set the object the TcpConnection will call as appropriate.
|
||||
* default = NULL (no callbacks made)
|
||||
*
|
||||
* @param handler The object which will be called for notifications.
|
||||
*/
|
||||
void SetHandler(TcpConnectionHandler *handler){ m_handler = handler; }
|
||||
|
||||
/**
|
||||
* @brief Returns the handler associated with this object.
|
||||
*/
|
||||
TcpConnectionHandler *GetHandler(){ return m_handler; }
|
||||
|
||||
/**
|
||||
* @brief Returns the current status of this connection.
|
||||
*/
|
||||
Status GetStatus(){ return m_status; }
|
||||
|
||||
/**
|
||||
* @brief Queues a message to be sent on this connection.
|
||||
*/
|
||||
void Send(const char *data, unsigned dataLen);
|
||||
|
||||
/**
|
||||
* @brief Disconnects and recycles the socket.
|
||||
*
|
||||
* @param notifyApplication primarily used internally, but when set to 'true', it will cause the application
|
||||
* to be called back via the onTerminated handler due to this call (the callback will not occur if the connection was
|
||||
* already disconnected)
|
||||
*/
|
||||
void Disconnect(bool notifyApplication=true);
|
||||
|
||||
/**
|
||||
* @brief Returns the ip on the other side of this connection.
|
||||
*/
|
||||
IPAddress GetDestinationIp(){ return m_destIP; }
|
||||
|
||||
/**
|
||||
* @brief Returns the port on the other side of this conection.
|
||||
*/
|
||||
short GetDestinationPort(){ return m_destPort; }
|
||||
|
||||
/**
|
||||
* @brief Standard AddRef/Release scheme
|
||||
*/
|
||||
void AddRef();
|
||||
|
||||
/**
|
||||
* @brief Standard AddRef/Release scheme
|
||||
*/
|
||||
void Release();
|
||||
|
||||
bool wasRemovedFromMgr() { return m_wasConRemovedFromMgr; }
|
||||
void setRemovedFromMgr() { m_wasConRemovedFromMgr = true; }
|
||||
|
||||
protected:
|
||||
friend class TcpManager;
|
||||
TcpConnection(TcpManager *tcpManager, TcpBlockAllocator *sendAlloc, TcpManager::TcpParams ¶ms, const IPAddress &destIP, short destPort, unsigned timeout);
|
||||
int finishConnect();/**< returns < 0 if fatal error and connect will not work, =0 if need more time, >0 if connect completed */
|
||||
TcpConnection(TcpManager *tcpManager, TcpBlockAllocator *sendAlloc, TcpManager::TcpParams ¶ms, SOCKET socket, const IPAddress &destIP, short destPort);
|
||||
TcpConnection *m_nextConnection; /**< Double linked list imp. */
|
||||
TcpConnection *m_prevConnection; /**< Double linked list imp. */
|
||||
SOCKET m_socket;
|
||||
int processOutgoing();/**< returns < 0 if fatal error and socket has been closed, =0 if sent data, call again immediately if want to, >0 may have sent data, but calling again would do no good because there is either no more data to send, or would block. */
|
||||
int processIncoming();/**< returns < 0 if fatal error and socket has been closed, =0 if read anything (full or partial message), >0 if nothing to read now, or would block so shouldn't try again immediately. */
|
||||
|
||||
|
||||
TcpConnection *m_nextKeepAliveConnection; /**< Double linked list imp. */
|
||||
TcpConnection *m_prevKeepAliveConnection; /**< Double linked list imp. */
|
||||
int m_aliveListId;
|
||||
|
||||
TcpConnection *m_nextRecvDataConnection;
|
||||
TcpConnection *m_prevRecvDataConnection;
|
||||
int m_recvDataListId;
|
||||
|
||||
private:
|
||||
~TcpConnection();
|
||||
void setOptions();
|
||||
TcpManager *m_manager;
|
||||
bool translateRecvSocketEror();
|
||||
Status m_status;
|
||||
TcpConnectionHandler *m_handler;
|
||||
IPAddress m_destIP;
|
||||
short m_destPort;
|
||||
unsigned m_refCount;
|
||||
TcpBlockAllocator *m_sendAllocator;
|
||||
data_block *m_head;
|
||||
data_block *m_tail;
|
||||
unsigned m_bytesRead;
|
||||
unsigned m_bytesNeeded;
|
||||
TcpManager::TcpParams m_params;
|
||||
char *m_recvBuff;
|
||||
sockaddr_in m_addr;
|
||||
unsigned m_connectTimeout;
|
||||
Clock m_connectTimer;
|
||||
|
||||
bool m_wasConRemovedFromMgr;
|
||||
};
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif //TCPCONNECTION_H
|
||||
|
||||
|
||||
|
||||
BIN
Binary file not shown.
+50
@@ -0,0 +1,50 @@
|
||||
#ifndef TCPHANDLERS_H
|
||||
#define TCPHANDLERS_H
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
class TcpConnection;
|
||||
|
||||
/**
|
||||
* @brief Interface used by TcpManager class for notification to application of connection state/etc.
|
||||
*
|
||||
* Note: these callbacks will only be made when during a call to TcpManager::giveTime.
|
||||
*/
|
||||
class TcpManagerHandler
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Callback made when a new connection has been established by the manager.
|
||||
*/
|
||||
virtual void OnConnectRequest(TcpConnection *con)=0;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Interface used by TcpConnection class for notification to application of connection state/etc.
|
||||
*
|
||||
* Note: these callbacks will only be made when during a call to TcpManager::giveTime.
|
||||
*/
|
||||
class TcpConnectionHandler
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Callback made when a new message has been received on the specified connection.
|
||||
*/
|
||||
virtual void OnRoutePacket(TcpConnection *con, const unsigned char *data, int dataLen)=0;
|
||||
|
||||
/**
|
||||
* @brief Callback made when the specified connection has closed, or been closed.
|
||||
*/
|
||||
virtual void OnTerminated(TcpConnection *con)=0;
|
||||
};
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
#endif //TCPHANDLERS_H
|
||||
|
||||
+746
@@ -0,0 +1,746 @@
|
||||
#include "TcpManager.h"
|
||||
#include <assert.h>
|
||||
#include "IPAddress.h"
|
||||
#include "TcpConnection.h"
|
||||
|
||||
#ifndef WIN32
|
||||
#include <sys/poll.h>
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
TcpManager::TcpParams::TcpParams()
|
||||
: port(0),
|
||||
maxConnections(10),
|
||||
incomingBufferSize(64*1024),
|
||||
outgoingBufferSize(64*1024),
|
||||
allocatorBlockSize(8*1024),
|
||||
allocatorBlockCount(16),
|
||||
maxRecvMessageSize(0),
|
||||
keepAliveDelay(0),
|
||||
noDataTimeout(0)
|
||||
{
|
||||
memset(bindAddress, 0, sizeof(bindAddress));
|
||||
}
|
||||
|
||||
TcpManager::TcpParams::TcpParams(const TcpParams &cpy)
|
||||
: port(cpy.port),
|
||||
maxConnections(cpy.maxConnections),
|
||||
incomingBufferSize(cpy.incomingBufferSize),
|
||||
outgoingBufferSize(cpy.outgoingBufferSize),
|
||||
allocatorBlockSize(cpy.allocatorBlockSize),
|
||||
allocatorBlockCount(cpy.allocatorBlockCount),
|
||||
maxRecvMessageSize(cpy.maxRecvMessageSize),
|
||||
keepAliveDelay(cpy.keepAliveDelay),
|
||||
noDataTimeout(cpy.noDataTimeout)
|
||||
{
|
||||
}
|
||||
|
||||
TcpManager::TcpManager(const TcpParams ¶ms)
|
||||
: m_handler(NULL),
|
||||
m_keepAliveList(NULL, 1),
|
||||
m_aliveList(NULL, 2),
|
||||
m_noDataList(NULL, 1),
|
||||
m_dataList(NULL, 2),
|
||||
m_params(params),
|
||||
m_refCount(1),
|
||||
m_connectionList(NULL),
|
||||
m_connectionListCount(0),
|
||||
m_socket(INVALID_SOCKET),
|
||||
m_boundAsServer(false),
|
||||
m_allocator(params.allocatorBlockSize, params.allocatorBlockCount),
|
||||
m_keepAliveTimer(),
|
||||
m_noDataTimer()
|
||||
{
|
||||
if (params.keepAliveDelay > 0)
|
||||
m_keepAliveTimer.start();
|
||||
|
||||
if (params.noDataTimeout > 0)
|
||||
m_noDataTimer.start();
|
||||
|
||||
#if defined(WIN32)
|
||||
WSADATA wsaData;
|
||||
WSAStartup(MAKEWORD(1,1), &wsaData);
|
||||
|
||||
FD_ZERO(&m_permfds);//select only used on win32
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
|
||||
TcpManager::~TcpManager()
|
||||
{
|
||||
#if defined(WIN32)
|
||||
WSACleanup();
|
||||
#endif
|
||||
|
||||
if (m_boundAsServer)
|
||||
{
|
||||
#if defined(WIN32)
|
||||
closesocket(m_socket);
|
||||
#else
|
||||
close(m_socket);
|
||||
#endif
|
||||
}
|
||||
while (m_connectionList != NULL)
|
||||
{
|
||||
TcpConnection *con = m_connectionList;
|
||||
m_connectionList = m_connectionList->m_nextConnection;
|
||||
con->Release();
|
||||
m_connectionListCount--;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool TcpManager::BindAsServer()
|
||||
{
|
||||
|
||||
m_socket = socket(AF_INET, SOCK_STREAM, 0);
|
||||
|
||||
if (m_socket != INVALID_SOCKET)
|
||||
{
|
||||
#if defined(WIN32)
|
||||
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4127)
|
||||
FD_SET(m_socket, &m_permfds);//the socket this server is listening on
|
||||
#pragma warning(pop)
|
||||
|
||||
unsigned long isNonBlocking = 1;
|
||||
int outBufSize = m_params.outgoingBufferSize;
|
||||
int inBufSize = m_params.incomingBufferSize;
|
||||
int keepAlive = 1;
|
||||
int reuseAddr = 1;
|
||||
struct linger ld;
|
||||
ld.l_onoff = 0;
|
||||
ld.l_linger = 0;
|
||||
|
||||
if (ioctlsocket(m_socket, FIONBIO, &isNonBlocking) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, (char *)&outBufSize, sizeof(outBufSize)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char *)&inBufSize, sizeof(inBufSize)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepAlive, sizeof(keepAlive)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuseAddr, sizeof(reuseAddr)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_LINGER, (char *)&ld, sizeof(ld)) != 0 )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
#else // linux is to remain the default compile mode
|
||||
unsigned long isNonBlocking = 1;
|
||||
unsigned long keepAlive = 1;
|
||||
unsigned long outBufSize = m_params.outgoingBufferSize;
|
||||
unsigned long inBufSize = m_params.incomingBufferSize;
|
||||
unsigned long reuseAddr = 1;
|
||||
struct linger ld;
|
||||
ld.l_onoff = 0;
|
||||
ld.l_linger = 0;
|
||||
|
||||
if (ioctl(m_socket, FIONBIO, &isNonBlocking) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, &outBufSize, sizeof(outBufSize)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, &inBufSize, sizeof(inBufSize)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(keepAlive)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) != 0
|
||||
|| setsockopt(m_socket, SOL_SOCKET, SO_LINGER, &ld, sizeof(ld)) != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
struct sockaddr_in addr_loc;
|
||||
addr_loc.sin_family = AF_INET;
|
||||
addr_loc.sin_port = htons(m_params.port);
|
||||
addr_loc.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
if (m_params.bindAddress[0] != 0)
|
||||
{
|
||||
unsigned long address = inet_addr(m_params.bindAddress);
|
||||
if (address == INADDR_NONE)
|
||||
{
|
||||
struct hostent * lphp;
|
||||
lphp = gethostbyname(m_params.bindAddress);
|
||||
if (lphp != NULL)
|
||||
addr_loc.sin_addr.s_addr = ((struct in_addr *)(lphp->h_addr))->s_addr;
|
||||
}
|
||||
else
|
||||
{
|
||||
addr_loc.sin_addr.s_addr = address;
|
||||
}
|
||||
}
|
||||
|
||||
if (bind(m_socket, (struct sockaddr *)&addr_loc, sizeof(addr_loc)) != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (listen(m_socket, 1000) != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
m_boundAsServer = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
TcpConnection *TcpManager::acceptClient()
|
||||
{
|
||||
TcpConnection *newConn = NULL;
|
||||
|
||||
if (m_boundAsServer && m_connectionListCount < m_params.maxConnections)
|
||||
{
|
||||
|
||||
sockaddr_in addr;
|
||||
int addrLength = sizeof(addr);
|
||||
SOCKET sock = ::accept(m_socket, (sockaddr *) &addr, (socklen_t *) &addrLength);
|
||||
|
||||
|
||||
if (sock != INVALID_SOCKET)
|
||||
{
|
||||
newConn = new TcpConnection(this, &m_allocator, m_params, sock, IPAddress(addr.sin_addr.s_addr), ntohs(addr.sin_port));
|
||||
addNewConnection(newConn);
|
||||
if (m_handler != NULL)
|
||||
{
|
||||
m_handler->OnConnectRequest(newConn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newConn;
|
||||
}
|
||||
|
||||
void TcpManager::SetHandler(TcpManagerHandler *handler)
|
||||
{
|
||||
m_handler = handler;
|
||||
}
|
||||
|
||||
SOCKET TcpManager::getMaxFD()
|
||||
{
|
||||
#ifdef WIN32
|
||||
return 0;//this param is not used on win32 for select, only on unix
|
||||
#else
|
||||
SOCKET maxfd = 0;
|
||||
|
||||
if (m_boundAsServer)
|
||||
maxfd = m_socket+1;
|
||||
|
||||
TcpConnection *next = NULL;
|
||||
for (TcpConnection *con = m_connectionList ; con != NULL ; con = next)
|
||||
{
|
||||
next = con->m_nextConnection;
|
||||
if (con->GetStatus() != TcpConnection::StatusDisconnected && con->m_socket > maxfd)
|
||||
{
|
||||
maxfd = con->m_socket + 1;
|
||||
}
|
||||
}
|
||||
return maxfd;
|
||||
#endif
|
||||
}
|
||||
|
||||
TcpConnection *TcpManager::getConnection(SOCKET fd)
|
||||
{
|
||||
TcpConnection *next = NULL;
|
||||
for (TcpConnection *con = m_connectionList ; con != NULL ; con = next)
|
||||
{
|
||||
next = con->m_nextConnection;
|
||||
if (con->m_socket == fd)
|
||||
{
|
||||
return con;
|
||||
}
|
||||
}
|
||||
//if get here ,couldn't find it
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bool TcpManager::GiveTime(unsigned maxTimeAcceptingConnections,unsigned maxSendTimePerConnection, unsigned maxRecvTimePerConnection)
|
||||
{
|
||||
bool processedIncoming = false;
|
||||
|
||||
if (maxTimeAcceptingConnections == 0 && maxSendTimePerConnection==0 && maxRecvTimePerConnection==0)
|
||||
{
|
||||
//they don't want to do anything now
|
||||
return processedIncoming;
|
||||
}
|
||||
|
||||
AddRef(); //keep a reference to ourself in case we callback to the application and the application releases us.
|
||||
|
||||
|
||||
|
||||
//first process outgoing on each connection, and finish establishing connections, if params say to
|
||||
if (m_connectionListCount != 0 && maxSendTimePerConnection != 0)
|
||||
{
|
||||
|
||||
// Send output from last heartbeat
|
||||
TcpConnection *next = NULL;
|
||||
for (TcpConnection *con = m_connectionList ; con != NULL ; con = next)
|
||||
{
|
||||
con->AddRef();
|
||||
if (next) next->Release();
|
||||
next = con->m_nextConnection;
|
||||
if (next) next->AddRef();
|
||||
if(con->GetStatus() == TcpConnection::StatusConnected)
|
||||
{
|
||||
Clock timer;
|
||||
timer.start();
|
||||
while(!timer.isDone(maxSendTimePerConnection))
|
||||
{
|
||||
int err = con->processOutgoing();
|
||||
|
||||
if (err > 0)
|
||||
{
|
||||
//couldn't finish processing last request, don't try more
|
||||
break;
|
||||
}
|
||||
else if (err < 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
con->Release();
|
||||
}
|
||||
else if (con->GetStatus() == TcpConnection::StatusNegotiating)
|
||||
{
|
||||
if (con->finishConnect() < 0)
|
||||
{
|
||||
con->Release();
|
||||
continue;
|
||||
}
|
||||
con->Release();
|
||||
}
|
||||
else //inactive client in client list????
|
||||
{
|
||||
removeConnection(con);
|
||||
con->Release();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//process incoming messages (including connect requests)
|
||||
if ((
|
||||
m_boundAsServer //if in server mode and want to spend time accepting clients
|
||||
&& maxTimeAcceptingConnections != 0
|
||||
)
|
||||
||
|
||||
(
|
||||
m_connectionListCount != 0 //if there are connections and want to spend time receiving on them
|
||||
&& maxRecvTimePerConnection != 0
|
||||
)
|
||||
)
|
||||
{
|
||||
#ifdef WIN32
|
||||
SOCKET maxfd = getMaxFD(); //re-calc maxfd every time select on WIN32
|
||||
|
||||
//select on all fd's
|
||||
struct timeval timeout;
|
||||
|
||||
fd_set tmpfds;
|
||||
tmpfds = m_permfds;
|
||||
timeout.tv_sec = 0;
|
||||
timeout.tv_usec = 0;
|
||||
int cnt = select(maxfd, &tmpfds, NULL, NULL, &timeout); // blocks for timeout
|
||||
|
||||
|
||||
if (cnt > 0)
|
||||
{
|
||||
if (m_boundAsServer && maxTimeAcceptingConnections != 0)
|
||||
{//activity on our socket means connect requests
|
||||
|
||||
//see if are new incoming clients
|
||||
if (FD_ISSET(m_socket, &tmpfds))
|
||||
{
|
||||
//yep
|
||||
Clock timer;
|
||||
timer.start();
|
||||
while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections))
|
||||
{
|
||||
//loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//process incoming client messages
|
||||
if (maxRecvTimePerConnection != 0)
|
||||
{
|
||||
TcpConnection *next = NULL;
|
||||
for (TcpConnection *con = m_connectionList ; con != NULL ; con = next)
|
||||
{
|
||||
con->AddRef();
|
||||
if (next) next->Release();
|
||||
next = con->m_nextConnection;
|
||||
if (next) next->AddRef();
|
||||
|
||||
SOCKET fd = con->m_socket;
|
||||
if (fd == INVALID_SOCKET)
|
||||
{
|
||||
//invalid socket in list?, check if is connecting, otherwise, Disconnect and discard
|
||||
if (con->GetStatus() != TcpConnection::StatusNegotiating)
|
||||
{
|
||||
removeConnection(con);
|
||||
con->Release();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (FD_ISSET(fd, &tmpfds))
|
||||
{
|
||||
Clock timer;
|
||||
timer.start();
|
||||
while(!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected)
|
||||
{
|
||||
int err = con->processIncoming();
|
||||
if (err >= 0)
|
||||
{
|
||||
processedIncoming = true;
|
||||
}
|
||||
|
||||
if (err > 0)
|
||||
{
|
||||
//couldn't finish processing last request, don't try more
|
||||
break;
|
||||
}
|
||||
else if (err < 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
}//while(!timer...)
|
||||
}//if (FD_ISSET...)
|
||||
con->Release();
|
||||
}//for (...)
|
||||
} //maxRecvTimePerConnection != 0
|
||||
}//cnt > 0
|
||||
#else //on UNIX use poll
|
||||
|
||||
int numfds = m_connectionListCount;
|
||||
int idx = 0;
|
||||
if (m_boundAsServer)
|
||||
{
|
||||
numfds++;
|
||||
idx++;
|
||||
}
|
||||
|
||||
struct pollfd pollfds[numfds];
|
||||
|
||||
if (m_boundAsServer)
|
||||
{
|
||||
pollfds[0].fd = m_socket;
|
||||
pollfds[0].events |= POLLIN;
|
||||
}
|
||||
|
||||
TcpConnection *next = NULL;
|
||||
for (TcpConnection *con = m_connectionList ; con != NULL ; con = next, idx++)
|
||||
{
|
||||
next = con->m_nextConnection;
|
||||
pollfds[idx].fd = con->m_socket;
|
||||
pollfds[idx].events |= POLLIN;
|
||||
pollfds[idx].events |= POLLHUP;
|
||||
}
|
||||
|
||||
|
||||
int cnt = poll(pollfds, numfds, 1);
|
||||
|
||||
if(cnt == SOCKET_ERROR)
|
||||
{
|
||||
//poll not working?
|
||||
//TODO: need to notify client somehow, don't think we can assume a fatal error here
|
||||
}
|
||||
else if (cnt > 0)
|
||||
{
|
||||
for (idx = 0; idx < numfds; idx++)
|
||||
{
|
||||
//find corresponding TcpConnection
|
||||
//TODO: optimize, seriously, this is takes linear time, every time
|
||||
TcpConnection *con = getConnection(pollfds[idx].fd);
|
||||
|
||||
if (pollfds[idx].revents & POLLIN)
|
||||
{
|
||||
if (m_boundAsServer && maxTimeAcceptingConnections != 0 && pollfds[idx].fd == m_socket)
|
||||
{
|
||||
//new incoming clients
|
||||
Clock timer;
|
||||
timer.start();
|
||||
while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections))
|
||||
{
|
||||
//loop
|
||||
}
|
||||
|
||||
continue;//don't try to readmsgs from listening fd
|
||||
}
|
||||
|
||||
//process regular msg(s)
|
||||
if (con == NULL)
|
||||
{
|
||||
close(pollfds[idx].fd);
|
||||
continue;
|
||||
}
|
||||
|
||||
Clock timer;
|
||||
timer.start();
|
||||
con->AddRef();//so it can't get deleted while we are checking it's status
|
||||
while(!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected)
|
||||
{
|
||||
int err = con->processIncoming();
|
||||
if (err >= 0)
|
||||
{
|
||||
processedIncoming = true;
|
||||
}
|
||||
|
||||
if (err > 0)
|
||||
{
|
||||
//couldn't finish processing last request, don't try more
|
||||
break;
|
||||
}
|
||||
else if (err < 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
}//while(!timer....)
|
||||
con->Release();
|
||||
}//if(pollfds[...
|
||||
else if (pollfds[idx].revents & POLLHUP)
|
||||
{
|
||||
if (con == NULL)
|
||||
{
|
||||
close(pollfds[idx].fd);
|
||||
continue;
|
||||
}
|
||||
|
||||
//Disconnect client
|
||||
con->Disconnect();
|
||||
}
|
||||
}//for (idx=0....
|
||||
}//else if (cnt > 0)
|
||||
|
||||
#endif
|
||||
}//wanted to process incoming messages or connect requests
|
||||
|
||||
//now process any keepalives, if time to do that
|
||||
if (m_params.keepAliveDelay > 0 && m_keepAliveTimer.isDone(m_params.keepAliveDelay))
|
||||
{
|
||||
TcpConnection *next = NULL;
|
||||
for (TcpConnection *con = m_keepAliveList.m_beginList ; con != NULL ; con = next)
|
||||
{
|
||||
con->AddRef();
|
||||
if (next) next->Release();
|
||||
next = con->m_nextKeepAliveConnection;
|
||||
if (next) next->AddRef();
|
||||
|
||||
con->Send(NULL, 0); //note: this request will move the connection from the keepAliveList to the aliveList
|
||||
con->Release();
|
||||
}
|
||||
|
||||
//now move the complete alive list over to the keepalive list to reset those timers
|
||||
m_keepAliveList.m_beginList = m_aliveList.m_beginList;
|
||||
m_aliveList.m_beginList = NULL;
|
||||
|
||||
//switch id's for those connections that were in the alive list last go - around
|
||||
int tmpID = m_aliveList.m_listID;
|
||||
m_aliveList.m_listID = m_keepAliveList.m_listID;
|
||||
m_keepAliveList.m_listID = tmpID;
|
||||
|
||||
m_keepAliveTimer.reset();
|
||||
m_keepAliveTimer.start();
|
||||
}
|
||||
|
||||
//now process any noDataCons, if time to do that
|
||||
if (m_params.noDataTimeout > 0 && m_noDataTimer.isDone(m_params.noDataTimeout))
|
||||
{
|
||||
TcpConnection *next = NULL;
|
||||
for (TcpConnection *con = m_noDataList.m_beginList ; con != NULL ; con = next)
|
||||
{
|
||||
con->AddRef();
|
||||
if (next) next->Release();
|
||||
next = con->m_nextRecvDataConnection;
|
||||
if (next) next->AddRef();
|
||||
|
||||
//time to disconnect this guy
|
||||
con->Disconnect();
|
||||
con->Release();
|
||||
}
|
||||
|
||||
//now move the complete data list over to the nodata list to reset those timers
|
||||
m_noDataList.m_beginList = m_dataList.m_beginList;
|
||||
m_dataList.m_beginList = NULL;
|
||||
|
||||
//switch id's for those connections that were in the data list last go - around
|
||||
int tmpID = m_dataList.m_listID;
|
||||
m_dataList.m_listID = m_noDataList.m_listID;
|
||||
m_noDataList.m_listID = tmpID;
|
||||
|
||||
m_noDataTimer.reset();
|
||||
m_noDataTimer.start();
|
||||
}
|
||||
|
||||
Release();
|
||||
|
||||
return processedIncoming;
|
||||
}
|
||||
|
||||
TcpConnection *TcpManager::EstablishConnection(const char *serverAddress, unsigned short serverPort, unsigned timeout)
|
||||
{
|
||||
if (m_boundAsServer)
|
||||
{
|
||||
//can't open outgoing connections when in server mode
|
||||
// use a different TcpManager to do that
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (m_connectionListCount >= m_params.maxConnections)
|
||||
return(NULL);
|
||||
|
||||
// get server address
|
||||
unsigned long address = inet_addr(serverAddress);
|
||||
if (address == INADDR_NONE)
|
||||
{
|
||||
struct hostent * lphp;
|
||||
lphp = gethostbyname(serverAddress);
|
||||
if (lphp == NULL)
|
||||
return(NULL);
|
||||
address = ((struct in_addr *)(lphp->h_addr))->s_addr;
|
||||
}
|
||||
IPAddress destIP(address);
|
||||
|
||||
TcpConnection *con = new TcpConnection(this, &m_allocator, m_params, destIP, serverPort, timeout);
|
||||
con->AddRef();//for the client - to conform to UdpLibrary method
|
||||
addNewConnection(con);
|
||||
|
||||
return con;
|
||||
}
|
||||
|
||||
void TcpManager::addNewConnection(TcpConnection *con)
|
||||
{
|
||||
con->AddRef();
|
||||
#ifdef WIN32 //uses select
|
||||
if (con->m_socket != INVALID_SOCKET)
|
||||
{
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4127)
|
||||
FD_SET(con->m_socket, &m_permfds);
|
||||
#pragma warning(pop)
|
||||
}
|
||||
#endif
|
||||
con->m_nextConnection = m_connectionList;
|
||||
con->m_prevConnection = NULL;
|
||||
if (m_connectionList != NULL)
|
||||
m_connectionList->m_prevConnection = con;
|
||||
m_connectionList = con;
|
||||
m_connectionListCount++;
|
||||
|
||||
con->m_nextKeepAliveConnection = m_aliveList.m_beginList;
|
||||
con->m_prevKeepAliveConnection = NULL;
|
||||
if (m_aliveList.m_beginList != NULL)
|
||||
m_aliveList.m_beginList->m_prevKeepAliveConnection = con;
|
||||
m_aliveList.m_beginList = con;
|
||||
con->m_aliveListId = m_keepAliveList.m_listID;//start it out thinking it's already in the alive list, since it is
|
||||
|
||||
con->m_nextRecvDataConnection = m_dataList.m_beginList;
|
||||
con->m_prevRecvDataConnection = NULL;
|
||||
if (m_dataList.m_beginList != NULL)
|
||||
m_dataList.m_beginList->m_prevRecvDataConnection = con;
|
||||
m_dataList.m_beginList = con;
|
||||
con->m_recvDataListId = m_noDataList.m_listID;//start it out thinking it's already in the data list, since it is
|
||||
}
|
||||
|
||||
void TcpManager::removeConnection(TcpConnection *con)
|
||||
{
|
||||
if (!con->wasRemovedFromMgr())
|
||||
{
|
||||
con->setRemovedFromMgr();
|
||||
m_connectionListCount--;
|
||||
#ifdef WIN32 //select only used on win32
|
||||
if (con->m_socket != INVALID_SOCKET)
|
||||
{
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4127)
|
||||
FD_CLR(con->m_socket, &m_permfds);
|
||||
#pragma warning(pop)
|
||||
}
|
||||
#endif
|
||||
if (con->m_prevConnection != NULL)
|
||||
con->m_prevConnection->m_nextConnection = con->m_nextConnection;
|
||||
if (con->m_nextConnection != NULL)
|
||||
con->m_nextConnection->m_prevConnection = con->m_prevConnection;
|
||||
if (m_connectionList == con)
|
||||
m_connectionList = con->m_nextConnection;
|
||||
con->m_nextConnection = NULL;
|
||||
con->m_prevConnection = NULL;
|
||||
|
||||
if (con->m_prevKeepAliveConnection != NULL)
|
||||
con->m_prevKeepAliveConnection->m_nextKeepAliveConnection = con->m_nextKeepAliveConnection;
|
||||
if (con->m_nextKeepAliveConnection != NULL)
|
||||
con->m_nextKeepAliveConnection->m_prevKeepAliveConnection = con->m_prevKeepAliveConnection;
|
||||
|
||||
if (m_aliveList.m_beginList == con)
|
||||
m_aliveList.m_beginList = con->m_nextKeepAliveConnection;
|
||||
else if (m_keepAliveList.m_beginList == con)
|
||||
m_keepAliveList.m_beginList = con->m_nextKeepAliveConnection;
|
||||
con->m_nextKeepAliveConnection = NULL;
|
||||
con->m_prevKeepAliveConnection = NULL;
|
||||
|
||||
|
||||
|
||||
if (con->m_prevRecvDataConnection != NULL)
|
||||
con->m_prevRecvDataConnection->m_nextRecvDataConnection = con->m_nextRecvDataConnection;
|
||||
if (con->m_nextRecvDataConnection != NULL)
|
||||
con->m_nextRecvDataConnection->m_prevRecvDataConnection = con->m_prevRecvDataConnection;
|
||||
|
||||
if (m_dataList.m_beginList == con)
|
||||
m_dataList.m_beginList = con->m_nextRecvDataConnection;
|
||||
else if (m_noDataList.m_beginList == con)
|
||||
m_noDataList.m_beginList = con->m_nextRecvDataConnection;
|
||||
con->m_nextRecvDataConnection = NULL;
|
||||
con->m_prevRecvDataConnection = NULL;
|
||||
|
||||
|
||||
|
||||
con->Release();
|
||||
}
|
||||
}
|
||||
|
||||
void TcpManager::AddRef()
|
||||
{
|
||||
m_refCount++;
|
||||
}
|
||||
|
||||
void TcpManager::Release()
|
||||
{
|
||||
if (--m_refCount == 0)
|
||||
delete this;
|
||||
}
|
||||
|
||||
IPAddress TcpManager::GetLocalIp() const
|
||||
{
|
||||
struct sockaddr_in addr_self;
|
||||
memset(&addr_self, 0, sizeof(addr_self));
|
||||
socklen_t len = sizeof(addr_self);
|
||||
getsockname(m_socket, (struct sockaddr *)&addr_self, &len);
|
||||
return(IPAddress(addr_self.sin_addr.s_addr));
|
||||
|
||||
}
|
||||
|
||||
unsigned int TcpManager::GetLocalPort() const
|
||||
{
|
||||
struct sockaddr_in addr_self;
|
||||
memset(&addr_self, 0, sizeof(addr_self));
|
||||
socklen_t len = sizeof(addr_self);
|
||||
getsockname(m_socket, (struct sockaddr *)&addr_self, &len);
|
||||
return(ntohs(addr_self.sin_port));
|
||||
}
|
||||
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
#ifndef TCPMANAGER_H
|
||||
#define TCPMANAGER_H
|
||||
|
||||
#include "TcpHandlers.h"
|
||||
|
||||
#include "TcpBlockAllocator.h"
|
||||
#include "IPAddress.h"
|
||||
#include "Clock.h"
|
||||
|
||||
#if defined(WIN32)
|
||||
#include <winsock2.h>
|
||||
typedef int socklen_t;
|
||||
#else // for non-windows platforms (linux)
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
const int INVALID_SOCKET = 0xFFFFFFFF;
|
||||
const int SOCKET_ERROR = 0xFFFFFFFF;
|
||||
typedef int SOCKET;
|
||||
#endif
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
namespace NAMESPACE
|
||||
{
|
||||
#endif
|
||||
|
||||
class TcpConnection;
|
||||
|
||||
struct ConnectionList
|
||||
{
|
||||
ConnectionList(TcpConnection *con, int id) : m_beginList(con), m_listID(id) {}
|
||||
|
||||
TcpConnection *m_beginList;
|
||||
int m_listID;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The purpose of the TcpManager is to manage a set of connections that are coming in on a particular port.
|
||||
*
|
||||
*/
|
||||
class TcpManager
|
||||
{
|
||||
public:
|
||||
|
||||
/** @brief Parameters for the TcpManager. */
|
||||
struct TcpParams
|
||||
{
|
||||
/** @brief Simple constructor sets default values for members. */
|
||||
TcpParams();
|
||||
|
||||
/** @brief Simple copy constructor. */
|
||||
TcpParams(const TcpParams &cpy);
|
||||
|
||||
/**
|
||||
* @brief Connection port number.
|
||||
*
|
||||
* this is the port number that this manager will use for all incoming and outgoing data. On the client side
|
||||
* this is typically set to 0, which causes the manager object to randomly pick an available port. On the server
|
||||
* side, this port should be set to a specific value as it will represent the port number that clients will use
|
||||
* to connect to the server (ie. the listening port). It's generally a good idea to give the user on the client
|
||||
* side the option of fixing this port number at a specific value as well as it is often necessary for them to
|
||||
* do so in order to navigate company firewalls which may have specific port numbers open to them for this purpose.
|
||||
* default = 0
|
||||
*/
|
||||
unsigned short port;
|
||||
|
||||
/**
|
||||
* @ brief Server bind ip.
|
||||
*
|
||||
*/
|
||||
char bindAddress[64];
|
||||
|
||||
|
||||
/**
|
||||
* @brief Maximum number of connections that can be established by this manager.
|
||||
*
|
||||
* this is the maximum number of connections that can be established by this manager, any incoming/outgoing connections
|
||||
* over this limit will be refused. On the client side, this typically only needs to be set to 1, though there
|
||||
* is little harm in setting this number larger.
|
||||
* default = 10
|
||||
*/
|
||||
unsigned maxConnections;
|
||||
|
||||
/**
|
||||
* @brief The size of the incoming socket buffer.
|
||||
*
|
||||
* The client will want to set this fairly small (32k or so), but the server
|
||||
* will want to set this fairly large (512k)
|
||||
* default = 64k
|
||||
*/
|
||||
unsigned incomingBufferSize;
|
||||
|
||||
/**
|
||||
* @brief The size of the outgoing socket buffer.
|
||||
*
|
||||
* The client will want to set this fairly small (32k or so), but the server
|
||||
* will want to set this fairly large (512k)
|
||||
* default = 64k
|
||||
*/
|
||||
unsigned outgoingBufferSize;
|
||||
|
||||
/**
|
||||
* @brief The block size of a single outgoing buffer memory allocator block.
|
||||
*
|
||||
* This param should allways be set at least as high as the maximum message size you
|
||||
* expect to send (performance will suffer otherwise).
|
||||
* default = 8K
|
||||
*/
|
||||
unsigned allocatorBlockSize;
|
||||
|
||||
/**
|
||||
* @brief The number of block memory allocator 'blocks' created at a time.
|
||||
*
|
||||
* This is the number of blocks created for the buffer allocator for each
|
||||
* TcpConnection opened by this manager. Since the block size should be
|
||||
* the max size of an outgoing message, the recommended setting is: greater
|
||||
* than the number of concurrent connections you expect to normally have open.
|
||||
* default = 1024
|
||||
*/
|
||||
unsigned allocatorBlockCount;
|
||||
|
||||
/**
|
||||
* @brief The maximum size that a recvd message is allowed to be.
|
||||
*
|
||||
* Really only here for protection, not required. If you set this, you can safeguard
|
||||
* your client/server from receiving stray oversized messages. If a message on the socket
|
||||
* specifies it's length at larger than this value, then the message is not read, and the connection
|
||||
* is terminated. If the value is set to 0, then there is no max message size checking
|
||||
* on incoming messages (this will also cary a performance hit, since every new message
|
||||
* recieved will have to have a new buffer created if you don't specify a value here). Be careful
|
||||
* not to set this too small, if you have messages that could exceed the value you set here
|
||||
* they will be discarded, and the connection will be terminated without warning.
|
||||
* default = 0
|
||||
*/
|
||||
unsigned maxRecvMessageSize;
|
||||
|
||||
unsigned keepAliveDelay;
|
||||
|
||||
unsigned noDataTimeout;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @brief
|
||||
*/
|
||||
TcpManager(const TcpParams ¶ms);
|
||||
|
||||
/**
|
||||
* @brief Use to specify a handler object to receive callbacks.
|
||||
*
|
||||
* To have the TcpManager call your object directly when connection requests come in, you
|
||||
* simply need to derive your class (multiply if necessary) from TcpManagerHandler, then you can use
|
||||
* this method to set the object the TcpManager will call as appropriate. The TcpConnection object
|
||||
* also has a handler mechanism that replaces the other callback functions below, see TcpConnection::SetHandler
|
||||
* default = NULL (no callbacks made)
|
||||
*
|
||||
* @param handler The object which will be called for manager related notifications.
|
||||
*/
|
||||
void SetHandler(TcpManagerHandler *handler);
|
||||
|
||||
/**
|
||||
* @brief This function MUST be called on a regular basis in order to give the manager object time to service the socket and give time to various connection objects that may need processing time, etc.
|
||||
*
|
||||
* @param maxTimeAcceptingConnections The max amount of time in milliseconds to spend accepting new client connections.
|
||||
* This parameter is only used if this manager has been bound as a server (bindAsServer).
|
||||
* If you set this param to 0, it will not attempt to accept any new connections.
|
||||
*
|
||||
* @param giveConnectionsTime
|
||||
* True if every connection opened on this manager is given time in this call, false if
|
||||
* no connections are given time.
|
||||
*
|
||||
* @param maxSendTimePerConnection Max amount of time in milliseconds to spend on each client processing outgoing messages.
|
||||
* A max of the specified amount of time will be spent on each and every individual connection. If you set
|
||||
* this parametrer to 0, it will not process any outgoing messages on any clients. Note also that when attempting
|
||||
* to establish new connections (via the EstablishConnection method), this parameter must be > 0 in order to
|
||||
* complete the connection process for any connections that were still negotiating.
|
||||
*
|
||||
* @param maxRecvTimePerConnection Max amount of time in milliseconds to spend on each client processing incoming messages.
|
||||
* A max of the specified amount of time will be spent on each and every individual connection. If you set
|
||||
* this param to 0, it will not process any incoming messages on any clients.
|
||||
* This is a good way to give the manager processing time for outgoing packets in situations
|
||||
* where the application does not want to have to worry about processing incoming packets.
|
||||
*
|
||||
* @return true if any incoming packets were processed during this time slice, otherwise returns false
|
||||
*/
|
||||
bool GiveTime(unsigned maxTimeAcceptingConnections = 5, unsigned maxSendTimePerConnection = 5, unsigned maxRecvTimePerConnection = 5);
|
||||
|
||||
/**
|
||||
* @brief Used to establish a connection to a server that is listening at the specified address and port.
|
||||
*
|
||||
* The serverAddress will do a DNS lookup as appropriate. This call will block long enough to resolve
|
||||
* the DNS lookup, but then will return a TcpConnection object that will be in a StatusNegotiating
|
||||
* state until the connection is actually established. The application must give the manager
|
||||
* object time after calling EstablishConnection or else the negotiation process to establish the
|
||||
* connection will never have time to actually occur. Typically the client establishing the connection
|
||||
* will call EstablishConnection, then sit in a loop calling TcpManager::GiveTime and checking to see
|
||||
* if the status of the returned TcpConnection object is changed from StatusNegotiating. This allows
|
||||
* the application to look for the ESC key or timeout an attempted connection.
|
||||
*
|
||||
* @param serverAddress The address of the server to open a connection to.
|
||||
*
|
||||
* @param serverPort The port of the server to open a connection to.
|
||||
*
|
||||
* @param timeout How long to attempt connecting to the server (in milliseconds).
|
||||
* Setting the timeout value to something greater than 0 will cause the TcpConnection object to change
|
||||
* from a StatusNegotiating state to a StatusDisconnected state after the timeout has expired. It will also cause
|
||||
* the connect-complete callback to be called if the connection is succesfull.
|
||||
*
|
||||
* @return A pointer to a TcpConnection object.
|
||||
* NULL if the manager object has exceeded its maximum number of connections
|
||||
* or if the serverAddress cannot be resolved to an IP address.
|
||||
*/
|
||||
TcpConnection *EstablishConnection(const char *serverAddress, unsigned short serverPort, unsigned timeout = 0);
|
||||
|
||||
/**
|
||||
* @brief Binds this manager as a server which will listen for and accept incoming connections.
|
||||
*
|
||||
* @return 'true' if manager is able to bind succesfully, false otherwise.
|
||||
*/
|
||||
bool BindAsServer();
|
||||
|
||||
/**
|
||||
* @brief Standard AddRef/Release scheme
|
||||
*/
|
||||
void AddRef();
|
||||
|
||||
/**
|
||||
* @brief Standard AddRef/Release scheme
|
||||
*/
|
||||
void Release();
|
||||
|
||||
/**
|
||||
* @brief Returns the ip address of this machine. If the machine is multi-homed, this value may be blank.
|
||||
*/
|
||||
IPAddress GetLocalIp() const;
|
||||
|
||||
|
||||
/**
|
||||
* @brief Returns the port the manager is actually using. This value will be the same as is specified in
|
||||
* Params::port (or if Params::port was set to 0, this will be the dynamically assigned port number)
|
||||
*/
|
||||
unsigned int GetLocalPort() const;
|
||||
|
||||
protected:
|
||||
friend class TcpConnection;
|
||||
void removeConnection(TcpConnection *con);
|
||||
TcpManagerHandler *m_handler;
|
||||
|
||||
ConnectionList m_keepAliveList;
|
||||
ConnectionList m_aliveList;
|
||||
|
||||
ConnectionList m_noDataList;
|
||||
ConnectionList m_dataList;
|
||||
|
||||
private:
|
||||
~TcpManager();
|
||||
TcpParams m_params;
|
||||
int m_refCount;
|
||||
TcpConnection *m_connectionList;
|
||||
unsigned m_connectionListCount;
|
||||
#ifdef WIN32
|
||||
fd_set m_permfds; /**< Used for select on WIN32 if we are in server mode. Keeps track of all clients connected to us. */
|
||||
#endif //WIN32
|
||||
SOCKET m_socket;
|
||||
bool m_boundAsServer;
|
||||
TcpBlockAllocator m_allocator;
|
||||
Clock m_keepAliveTimer;
|
||||
Clock m_noDataTimer;
|
||||
|
||||
void addNewConnection(TcpConnection *con);
|
||||
SOCKET getMaxFD();
|
||||
TcpConnection *getConnection(SOCKET fd);
|
||||
TcpConnection *acceptClient();
|
||||
};
|
||||
|
||||
#ifdef EXTERNAL_DISTRO
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif //TCPMANAGER_H
|
||||
|
||||
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
+472
@@ -0,0 +1,472 @@
|
||||
/* version: 1.0, Feb, 2003
|
||||
Author : Gao Dasheng
|
||||
Copyright (C) 1995-2002 Gao Dasheng([email protected])
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
Introduce:
|
||||
This file includes two classes CA2GZIP and CGZIP2A which do compressing and
|
||||
uncompressing in memory. and It 's very easy to use for small data compressing.
|
||||
Some compress and uncompress codes came from gzip unzip function of zlib 1.1.x.
|
||||
|
||||
Usage:
|
||||
these two classes work used with zlib 1.1.x (http://www.gzip.org/zlib/).
|
||||
They were tested in Window OS.
|
||||
Exmaple:
|
||||
#include "GZipHelper.h"
|
||||
void main()
|
||||
{
|
||||
char plainText[]="Plain text here";
|
||||
CA2GZIP gzip(plainText,strlen(plainText)); // do compressing here;
|
||||
LPGZIP pgzip=gzip.pgzip; // pgzip is zipped data pointer, you can use it directly
|
||||
int len=gzip.Length; // Length is length of zipped data;
|
||||
|
||||
CGZIP2A plain(pgzip,len); // do decompressing here
|
||||
|
||||
char *pplain=plain.psz; // psz is plain data pointer
|
||||
int aLen=plain.Length; // Length is length of unzipped data.
|
||||
}
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
*/
|
||||
|
||||
|
||||
#ifndef __GZipHelper__
|
||||
#define __GZipHelper__
|
||||
|
||||
#include "Zip/zutil.h"
|
||||
|
||||
|
||||
#define ALLOC(size) malloc(size)
|
||||
#define TRYFREE(p) {if (p) free(p);}
|
||||
#define Z_BUFSIZE 4096
|
||||
#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
|
||||
#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
|
||||
#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
|
||||
#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
|
||||
#define COMMENT 0x10 /* bit 4 set: file comment present */
|
||||
#define RESERVED 0xE0 /* bits 5..7: reserved */
|
||||
|
||||
typedef unsigned char GZIP;
|
||||
typedef GZIP* LPGZIP;
|
||||
|
||||
static const int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
|
||||
|
||||
template< int t_nBufferLength = 1024 ,int t_nLevel=Z_DEFAULT_COMPRESSION,int t_nStrategy=Z_DEFAULT_STRATEGY>
|
||||
class CA2GZIPT
|
||||
{
|
||||
public:
|
||||
LPGZIP pgzip;
|
||||
int Length;
|
||||
public:
|
||||
CA2GZIPT(char* lpsz,int len=-1):pgzip(0),Length(0)
|
||||
{
|
||||
Init(lpsz,len);
|
||||
}
|
||||
~CA2GZIPT()
|
||||
{
|
||||
if(pgzip!=m_buffer) TRYFREE(pgzip);
|
||||
}
|
||||
void Init(char *lpsz,int len=-1)
|
||||
{
|
||||
if(lpsz==0)
|
||||
{
|
||||
pgzip=0;
|
||||
Length=0;
|
||||
return ;
|
||||
}
|
||||
if(len==-1)
|
||||
{
|
||||
len=(int)strlen(lpsz);
|
||||
}
|
||||
m_CurrentBufferSize=t_nBufferLength;
|
||||
pgzip=m_buffer;
|
||||
|
||||
|
||||
m_zstream.zalloc = (alloc_func)0;
|
||||
m_zstream.zfree = (free_func)0;
|
||||
m_zstream.opaque = (voidpf)0;
|
||||
m_zstream.next_in = Z_NULL;
|
||||
m_zstream.next_out = Z_NULL;
|
||||
m_zstream.avail_in = 0;
|
||||
m_zstream.avail_out = 0;
|
||||
m_z_err = Z_OK;
|
||||
m_crc = crc32(0L, Z_NULL, 0);
|
||||
int err = deflateInit2(&(m_zstream), t_nLevel,Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, t_nStrategy);
|
||||
m_outbuf = (Byte*)ALLOC(Z_BUFSIZE);
|
||||
m_zstream.next_out = m_outbuf;
|
||||
if (err != Z_OK || m_outbuf == Z_NULL)
|
||||
{
|
||||
destroy();
|
||||
return ;
|
||||
}
|
||||
m_zstream.avail_out = Z_BUFSIZE;
|
||||
GZIP header[10]={0x1f,0x8b,Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE};
|
||||
write(header,10);
|
||||
|
||||
m_zstream.next_in = (Bytef*)lpsz;
|
||||
m_zstream.avail_in = len;
|
||||
while (m_zstream.avail_in != 0)
|
||||
{
|
||||
if (m_zstream.avail_out == 0)
|
||||
{
|
||||
m_zstream.next_out = m_outbuf;
|
||||
this->write(m_outbuf,Z_BUFSIZE);
|
||||
m_zstream.avail_out = Z_BUFSIZE;
|
||||
}
|
||||
m_z_err = deflate(&m_zstream,Z_NO_FLUSH);
|
||||
if (m_z_err != Z_OK) break;
|
||||
}
|
||||
m_crc = crc32(m_crc, (const Bytef *)lpsz, len);
|
||||
if (finish() != Z_OK) { destroy(); return ;}
|
||||
putLong(m_crc);
|
||||
putLong (m_zstream.total_in);
|
||||
destroy();
|
||||
}
|
||||
private:
|
||||
GZIP m_buffer[t_nBufferLength];
|
||||
int m_CurrentBufferSize;
|
||||
z_stream m_zstream;
|
||||
int m_z_err; /* error code for last stream operation */
|
||||
Byte *m_outbuf; /* output buffer */
|
||||
uLong m_crc; /* crc32 of uncompressed data */
|
||||
|
||||
int write(LPGZIP buf,int count)
|
||||
{
|
||||
if(buf==0) return 0;
|
||||
if(Length+count>m_CurrentBufferSize)
|
||||
{
|
||||
int nTimes=(Length+count)/t_nBufferLength +1;
|
||||
LPGZIP pTemp=pgzip;
|
||||
pgzip=static_cast<LPGZIP>( malloc(nTimes*t_nBufferLength));
|
||||
m_CurrentBufferSize=nTimes*t_nBufferLength;
|
||||
memcpy(pgzip,pTemp,Length);
|
||||
if(pTemp!=m_buffer) free(pTemp);
|
||||
}
|
||||
memcpy(pgzip+Length,buf,count);
|
||||
Length+=count;
|
||||
return count;
|
||||
}
|
||||
|
||||
int finish()
|
||||
{
|
||||
uInt len;
|
||||
int done = 0;
|
||||
m_zstream.avail_in = 0;
|
||||
for (;;)
|
||||
{
|
||||
len = Z_BUFSIZE - m_zstream.avail_out;
|
||||
if (len != 0)
|
||||
{
|
||||
write(m_outbuf,len);
|
||||
m_zstream.next_out = m_outbuf;
|
||||
m_zstream.avail_out = Z_BUFSIZE;
|
||||
}
|
||||
if (done) break;
|
||||
m_z_err = deflate(&(m_zstream), Z_FINISH);
|
||||
if (len == 0 && m_z_err == Z_BUF_ERROR) m_z_err = Z_OK;
|
||||
|
||||
done = (m_zstream.avail_out != 0 || m_z_err == Z_STREAM_END);
|
||||
if (m_z_err != Z_OK && m_z_err != Z_STREAM_END) break;
|
||||
}
|
||||
return m_z_err == Z_STREAM_END ? Z_OK : m_z_err;
|
||||
}
|
||||
int destroy()
|
||||
{
|
||||
int err = Z_OK;
|
||||
if (m_zstream.state != NULL) {
|
||||
err = deflateEnd(&(m_zstream));
|
||||
}
|
||||
if (m_z_err < 0) err = m_z_err;
|
||||
TRYFREE(m_outbuf);
|
||||
return err;
|
||||
}
|
||||
|
||||
void putLong (uLong x)
|
||||
{
|
||||
for(int n = 0; n < 4; n++) {
|
||||
unsigned char c=(unsigned char)(x & 0xff);
|
||||
write(&c,1);
|
||||
x >>= 8;
|
||||
}
|
||||
}
|
||||
};
|
||||
typedef CA2GZIPT<10> CA2GZIP;
|
||||
|
||||
|
||||
template< int t_nBufferLength = 1024>
|
||||
class CGZIP2AT
|
||||
{
|
||||
public:
|
||||
char *psz;
|
||||
int Length;
|
||||
CGZIP2AT(LPGZIP pgzip,int len):m_gzip(pgzip),m_gziplen(len),psz(0),Length(0),m_pos(0)
|
||||
{
|
||||
Init();
|
||||
}
|
||||
~CGZIP2AT()
|
||||
{
|
||||
if(psz!=m_buffer) TRYFREE(psz);
|
||||
}
|
||||
void Init()
|
||||
{
|
||||
if(m_gzip==0)
|
||||
{
|
||||
psz=0;
|
||||
Length=0;
|
||||
return ;
|
||||
}
|
||||
m_CurrentBufferSize=t_nBufferLength;
|
||||
psz=m_buffer;
|
||||
memset(psz,0,m_CurrentBufferSize+1);
|
||||
|
||||
m_zstream.zalloc = (alloc_func)0;
|
||||
m_zstream.zfree = (free_func)0;
|
||||
m_zstream.opaque = (voidpf)0;
|
||||
m_zstream.next_in = m_inbuf = Z_NULL;
|
||||
m_zstream.next_out = Z_NULL;
|
||||
m_zstream.avail_in = m_zstream.avail_out = 0;
|
||||
m_z_err = Z_OK;
|
||||
m_z_eof = 0;
|
||||
m_transparent = 0;
|
||||
m_crc = crc32(0L, Z_NULL, 0);
|
||||
|
||||
m_zstream.next_in =m_inbuf = (Byte*)ALLOC(Z_BUFSIZE);
|
||||
int err = inflateInit2(&(m_zstream), -MAX_WBITS);
|
||||
if (err != Z_OK || m_inbuf == Z_NULL)
|
||||
{
|
||||
destroy();
|
||||
return;
|
||||
}
|
||||
m_zstream.avail_out = Z_BUFSIZE;
|
||||
check_header();
|
||||
char outbuf[Z_BUFSIZE];
|
||||
int nRead;
|
||||
while(true)
|
||||
{
|
||||
nRead=gzread(outbuf,Z_BUFSIZE);
|
||||
if(nRead<=0) break;
|
||||
write(outbuf,nRead);
|
||||
}
|
||||
destroy();
|
||||
}
|
||||
private:
|
||||
char m_buffer[t_nBufferLength+1];
|
||||
int m_CurrentBufferSize;
|
||||
z_stream m_zstream;
|
||||
int m_z_err; /* error code for last stream operation */
|
||||
Byte *m_inbuf; /* output buffer */
|
||||
uLong m_crc; /* crc32 of uncompressed data */
|
||||
int m_z_eof;
|
||||
int m_transparent;
|
||||
|
||||
int m_pos;
|
||||
LPGZIP m_gzip;
|
||||
int m_gziplen;
|
||||
|
||||
void check_header()
|
||||
{
|
||||
int method; /* method byte */
|
||||
int flags; /* flags byte */
|
||||
uInt len;
|
||||
int c;
|
||||
|
||||
/* Check the gzip magic header */
|
||||
for (len = 0; len < 2; len++) {
|
||||
c = get_byte();
|
||||
if (c != gz_magic[len]) {
|
||||
if (len != 0) m_zstream.avail_in++, m_zstream.next_in--;
|
||||
if (c != EOF) {
|
||||
m_zstream.avail_in++, m_zstream.next_in--;
|
||||
m_transparent = 1;
|
||||
}
|
||||
m_z_err =m_zstream.avail_in != 0 ? Z_OK : Z_STREAM_END;
|
||||
return;
|
||||
}
|
||||
}
|
||||
method = get_byte();
|
||||
flags = get_byte();
|
||||
if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
|
||||
m_z_err = Z_DATA_ERROR;
|
||||
return;
|
||||
}
|
||||
/* Discard time, xflags and OS code: */
|
||||
for (len = 0; len < 6; len++) (void)get_byte();
|
||||
|
||||
if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
|
||||
len = (uInt)get_byte();
|
||||
len += ((uInt)get_byte())<<8;
|
||||
/* len is garbage if EOF but the loop below will quit anyway */
|
||||
while (len-- != 0 && get_byte() != EOF) ;
|
||||
}
|
||||
if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
|
||||
while ((c = get_byte()) != 0 && c != EOF) ;
|
||||
}
|
||||
if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
|
||||
while ((c = get_byte()) != 0 && c != EOF) ;
|
||||
}
|
||||
if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
|
||||
for (len = 0; len < 2; len++) (void)get_byte();
|
||||
}
|
||||
m_z_err = m_z_eof ? Z_DATA_ERROR : Z_OK;
|
||||
}
|
||||
|
||||
int get_byte()
|
||||
{
|
||||
if (m_z_eof) return EOF;
|
||||
if (m_zstream.avail_in == 0)
|
||||
{
|
||||
errno = 0;
|
||||
m_zstream.avail_in =read(m_inbuf,Z_BUFSIZE);
|
||||
if(m_zstream.avail_in == 0)
|
||||
{
|
||||
m_z_eof = 1;
|
||||
return EOF;
|
||||
}
|
||||
m_zstream.next_in = m_inbuf;
|
||||
}
|
||||
m_zstream.avail_in--;
|
||||
return *(m_zstream.next_in)++;
|
||||
}
|
||||
int read(LPGZIP buf,int size)
|
||||
{
|
||||
int nRead=size;
|
||||
if(m_pos+size>=m_gziplen)
|
||||
{
|
||||
nRead=m_gziplen-m_pos;
|
||||
}
|
||||
if(nRead<=0) return 0;
|
||||
memcpy(buf,m_gzip+m_pos,nRead);
|
||||
m_pos+=nRead;
|
||||
return nRead;
|
||||
}
|
||||
|
||||
int gzread(char* buf,int len)
|
||||
{
|
||||
Bytef *start = (Bytef*)buf; /* starting point for crc computation */
|
||||
Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */
|
||||
|
||||
|
||||
if (m_z_err == Z_DATA_ERROR || m_z_err == Z_ERRNO) return -1;
|
||||
if (m_z_err == Z_STREAM_END) return 0; /* EOF */
|
||||
|
||||
next_out = (Byte*)buf;
|
||||
m_zstream.next_out = (Bytef*)buf;
|
||||
m_zstream.avail_out = len;
|
||||
while (m_zstream.avail_out != 0) {
|
||||
if (m_transparent)
|
||||
{
|
||||
/* Copy first the lookahead bytes: */
|
||||
uInt n = m_zstream.avail_in;
|
||||
if (n > m_zstream.avail_out) n = m_zstream.avail_out;
|
||||
if (n > 0)
|
||||
{
|
||||
zmemcpy(m_zstream.next_out,m_zstream.next_in, n);
|
||||
next_out += n;
|
||||
m_zstream.next_out = next_out;
|
||||
m_zstream.next_in += n;
|
||||
m_zstream.avail_out -= n;
|
||||
m_zstream.avail_in -= n;
|
||||
}
|
||||
if (m_zstream.avail_out > 0) {
|
||||
m_zstream.avail_out -=read(next_out,m_zstream.avail_out);
|
||||
}
|
||||
len -= m_zstream.avail_out;
|
||||
m_zstream.total_in += (uLong)len;
|
||||
m_zstream.total_out += (uLong)len;
|
||||
if (len == 0) m_z_eof = 1;
|
||||
return (int)len;
|
||||
}
|
||||
if (m_zstream.avail_in == 0 && !m_z_eof)
|
||||
{
|
||||
errno = 0;
|
||||
m_zstream.avail_in = read(m_inbuf,Z_BUFSIZE);
|
||||
if (m_zstream.avail_in == 0)
|
||||
{
|
||||
m_z_eof = 1;
|
||||
}
|
||||
m_zstream.next_in = m_inbuf;
|
||||
}
|
||||
m_z_err = inflate(&(m_zstream), Z_NO_FLUSH);
|
||||
if (m_z_err == Z_STREAM_END)
|
||||
{
|
||||
/* Check CRC and original size */
|
||||
m_crc = crc32(m_crc, start, (uInt)(m_zstream.next_out - start));
|
||||
start = m_zstream.next_out;
|
||||
if (getLong() != m_crc) {
|
||||
m_z_err = Z_DATA_ERROR;
|
||||
}else
|
||||
{
|
||||
(void)getLong();
|
||||
check_header();
|
||||
if (m_z_err == Z_OK)
|
||||
{
|
||||
uLong total_in = m_zstream.total_in;
|
||||
uLong total_out = m_zstream.total_out;
|
||||
inflateReset(&(m_zstream));
|
||||
m_zstream.total_in = total_in;
|
||||
m_zstream.total_out = total_out;
|
||||
m_crc = crc32(0L, Z_NULL, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (m_z_err != Z_OK || m_z_eof) break;
|
||||
}
|
||||
m_crc = crc32(m_crc, start, (uInt)(m_zstream.next_out - start));
|
||||
return (int)(len - m_zstream.avail_out);
|
||||
}
|
||||
uLong getLong()
|
||||
{
|
||||
uLong x = (uLong)get_byte();
|
||||
int c;
|
||||
x += ((uLong)get_byte())<<8;
|
||||
x += ((uLong)get_byte())<<16;
|
||||
c = get_byte();
|
||||
if (c == EOF) m_z_err = Z_DATA_ERROR;
|
||||
x += ((uLong)c)<<24;
|
||||
return x;
|
||||
}
|
||||
int write(char* buf,int count)
|
||||
{
|
||||
if(buf==0) return 0;
|
||||
if(Length+count>m_CurrentBufferSize)
|
||||
{
|
||||
int nTimes=(Length+count)/t_nBufferLength +1;
|
||||
char *pTemp=psz;
|
||||
psz=static_cast<char*>( malloc(nTimes*t_nBufferLength+1));
|
||||
m_CurrentBufferSize=nTimes*t_nBufferLength;
|
||||
memset(psz,0,m_CurrentBufferSize+1);
|
||||
memcpy(psz,pTemp,Length);
|
||||
if(pTemp!=m_buffer) free(pTemp);
|
||||
}
|
||||
memcpy(psz+Length,buf,count);
|
||||
Length+=count;
|
||||
return count;
|
||||
}
|
||||
int destroy()
|
||||
{
|
||||
int err = Z_OK;
|
||||
if (m_zstream.state != NULL) {
|
||||
err = inflateEnd(&(m_zstream));
|
||||
}
|
||||
if (m_z_err < 0) err = m_z_err;
|
||||
TRYFREE(m_inbuf);
|
||||
return err;
|
||||
}
|
||||
|
||||
};
|
||||
typedef CGZIP2AT<> CGZIP2A;
|
||||
#endif
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/* adler32.c -- compute the Adler-32 checksum of a data stream
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* @(#) $Id$ */
|
||||
|
||||
#include "zlib.h"
|
||||
|
||||
#define BASE 65521L /* largest prime smaller than 65536 */
|
||||
#define NMAX 5552
|
||||
/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
|
||||
|
||||
#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
|
||||
#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
|
||||
#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
|
||||
#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
|
||||
#define DO16(buf) DO8(buf,0); DO8(buf,8);
|
||||
|
||||
/* ========================================================================= */
|
||||
uLong ZEXPORT adler32(adler, buf, len)
|
||||
uLong adler;
|
||||
const Bytef *buf;
|
||||
uInt len;
|
||||
{
|
||||
unsigned long s1 = adler & 0xffff;
|
||||
unsigned long s2 = (adler >> 16) & 0xffff;
|
||||
int k;
|
||||
|
||||
if (buf == Z_NULL) return 1L;
|
||||
|
||||
while (len > 0) {
|
||||
k = len < NMAX ? len : NMAX;
|
||||
len -= k;
|
||||
while (k >= 16) {
|
||||
DO16(buf);
|
||||
buf += 16;
|
||||
k -= 16;
|
||||
}
|
||||
if (k != 0) do {
|
||||
s1 += *buf++;
|
||||
s2 += s1;
|
||||
} while (--k);
|
||||
s1 %= BASE;
|
||||
s2 %= BASE;
|
||||
}
|
||||
return (s2 << 16) | s1;
|
||||
}
|
||||
BIN
Binary file not shown.
+68
@@ -0,0 +1,68 @@
|
||||
/* compress.c -- compress a memory buffer
|
||||
* Copyright (C) 1995-2002 Jean-loup Gailly.
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* @(#) $Id$ */
|
||||
|
||||
#include "zlib.h"
|
||||
|
||||
/* ===========================================================================
|
||||
Compresses the source buffer into the destination buffer. The level
|
||||
parameter has the same meaning as in deflateInit. sourceLen is the byte
|
||||
length of the source buffer. Upon entry, destLen is the total size of the
|
||||
destination buffer, which must be at least 0.1% larger than sourceLen plus
|
||||
12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
|
||||
|
||||
compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
|
||||
memory, Z_BUF_ERROR if there was not enough room in the output buffer,
|
||||
Z_STREAM_ERROR if the level parameter is invalid.
|
||||
*/
|
||||
int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
|
||||
Bytef *dest;
|
||||
uLongf *destLen;
|
||||
const Bytef *source;
|
||||
uLong sourceLen;
|
||||
int level;
|
||||
{
|
||||
z_stream stream;
|
||||
int err;
|
||||
|
||||
stream.next_in = (Bytef*)source;
|
||||
stream.avail_in = (uInt)sourceLen;
|
||||
#ifdef MAXSEG_64K
|
||||
/* Check for source > 64K on 16-bit machine: */
|
||||
if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
|
||||
#endif
|
||||
stream.next_out = dest;
|
||||
stream.avail_out = (uInt)*destLen;
|
||||
if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
|
||||
|
||||
stream.zalloc = (alloc_func)0;
|
||||
stream.zfree = (free_func)0;
|
||||
stream.opaque = (voidpf)0;
|
||||
|
||||
err = deflateInit(&stream, level);
|
||||
if (err != Z_OK) return err;
|
||||
|
||||
err = deflate(&stream, Z_FINISH);
|
||||
if (err != Z_STREAM_END) {
|
||||
deflateEnd(&stream);
|
||||
return err == Z_OK ? Z_BUF_ERROR : err;
|
||||
}
|
||||
*destLen = stream.total_out;
|
||||
|
||||
err = deflateEnd(&stream);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
*/
|
||||
int ZEXPORT compress (dest, destLen, source, sourceLen)
|
||||
Bytef *dest;
|
||||
uLongf *destLen;
|
||||
const Bytef *source;
|
||||
uLong sourceLen;
|
||||
{
|
||||
return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
|
||||
}
|
||||
BIN
Binary file not shown.
+162
@@ -0,0 +1,162 @@
|
||||
/* crc32.c -- compute the CRC-32 of a data stream
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* @(#) $Id$ */
|
||||
|
||||
#include "zlib.h"
|
||||
|
||||
#define local static
|
||||
|
||||
#ifdef DYNAMIC_CRC_TABLE
|
||||
|
||||
local int crc_table_empty = 1;
|
||||
local uLongf crc_table[256];
|
||||
local void make_crc_table OF((void));
|
||||
|
||||
/*
|
||||
Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
|
||||
x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
|
||||
|
||||
Polynomials over GF(2) are represented in binary, one bit per coefficient,
|
||||
with the lowest powers in the most significant bit. Then adding polynomials
|
||||
is just exclusive-or, and multiplying a polynomial by x is a right shift by
|
||||
one. If we call the above polynomial p, and represent a byte as the
|
||||
polynomial q, also with the lowest power in the most significant bit (so the
|
||||
byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
|
||||
where a mod b means the remainder after dividing a by b.
|
||||
|
||||
This calculation is done using the shift-register method of multiplying and
|
||||
taking the remainder. The register is initialized to zero, and for each
|
||||
incoming bit, x^32 is added mod p to the register if the bit is a one (where
|
||||
x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
|
||||
x (which is shifting right by one and adding x^32 mod p if the bit shifted
|
||||
out is a one). We start with the highest power (least significant bit) of
|
||||
q and repeat for all eight bits of q.
|
||||
|
||||
The table is simply the CRC of all possible eight bit values. This is all
|
||||
the information needed to generate CRC's on data a byte at a time for all
|
||||
combinations of CRC register values and incoming bytes.
|
||||
*/
|
||||
local void make_crc_table()
|
||||
{
|
||||
uLong c;
|
||||
int n, k;
|
||||
uLong poly; /* polynomial exclusive-or pattern */
|
||||
/* terms of polynomial defining this crc (except x^32): */
|
||||
static const Byte p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
|
||||
|
||||
/* make exclusive-or pattern from polynomial (0xedb88320L) */
|
||||
poly = 0L;
|
||||
for (n = 0; n < sizeof(p)/sizeof(Byte); n++)
|
||||
poly |= 1L << (31 - p[n]);
|
||||
|
||||
for (n = 0; n < 256; n++)
|
||||
{
|
||||
c = (uLong)n;
|
||||
for (k = 0; k < 8; k++)
|
||||
c = c & 1 ? poly ^ (c >> 1) : c >> 1;
|
||||
crc_table[n] = c;
|
||||
}
|
||||
crc_table_empty = 0;
|
||||
}
|
||||
#else
|
||||
/* ========================================================================
|
||||
* Table of CRC-32's of all single-byte values (made by make_crc_table)
|
||||
*/
|
||||
local const uLongf crc_table[256] = {
|
||||
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
|
||||
0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
|
||||
0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
|
||||
0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
|
||||
0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
|
||||
0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
|
||||
0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
|
||||
0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
|
||||
0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
|
||||
0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
|
||||
0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
|
||||
0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
|
||||
0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
|
||||
0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
|
||||
0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
|
||||
0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
|
||||
0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
|
||||
0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
|
||||
0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
|
||||
0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
|
||||
0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
|
||||
0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
|
||||
0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
|
||||
0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
|
||||
0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
|
||||
0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
|
||||
0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
|
||||
0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
|
||||
0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
|
||||
0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
|
||||
0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
|
||||
0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
|
||||
0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
|
||||
0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
|
||||
0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
|
||||
0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
|
||||
0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
|
||||
0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
|
||||
0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
|
||||
0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
|
||||
0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
|
||||
0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
|
||||
0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
|
||||
0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
|
||||
0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
|
||||
0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
|
||||
0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
|
||||
0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
|
||||
0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
|
||||
0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
|
||||
0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
|
||||
0x2d02ef8dL
|
||||
};
|
||||
#endif
|
||||
|
||||
/* =========================================================================
|
||||
* This function can be used by asm versions of crc32()
|
||||
*/
|
||||
const uLongf * ZEXPORT get_crc_table()
|
||||
{
|
||||
#ifdef DYNAMIC_CRC_TABLE
|
||||
if (crc_table_empty) make_crc_table();
|
||||
#endif
|
||||
return (const uLongf *)crc_table;
|
||||
}
|
||||
|
||||
/* ========================================================================= */
|
||||
#define DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8);
|
||||
#define DO2(buf) DO1(buf); DO1(buf);
|
||||
#define DO4(buf) DO2(buf); DO2(buf);
|
||||
#define DO8(buf) DO4(buf); DO4(buf);
|
||||
|
||||
/* ========================================================================= */
|
||||
uLong ZEXPORT crc32(crc, buf, len)
|
||||
uLong crc;
|
||||
const Bytef *buf;
|
||||
uInt len;
|
||||
{
|
||||
if (buf == Z_NULL) return 0L;
|
||||
#ifdef DYNAMIC_CRC_TABLE
|
||||
if (crc_table_empty)
|
||||
make_crc_table();
|
||||
#endif
|
||||
crc = crc ^ 0xffffffffL;
|
||||
while (len >= 8)
|
||||
{
|
||||
DO8(buf);
|
||||
len -= 8;
|
||||
}
|
||||
if (len) do {
|
||||
DO1(buf);
|
||||
} while (--len);
|
||||
return crc ^ 0xffffffffL;
|
||||
}
|
||||
BIN
Binary file not shown.
+1350
File diff suppressed because it is too large
Load Diff
+318
@@ -0,0 +1,318 @@
|
||||
/* deflate.h -- internal compression state
|
||||
* Copyright (C) 1995-2002 Jean-loup Gailly
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* WARNING: this file should *not* be used by applications. It is
|
||||
part of the implementation of the compression library and is
|
||||
subject to change. Applications should only use zlib.h.
|
||||
*/
|
||||
|
||||
/* @(#) $Id$ */
|
||||
|
||||
#ifndef _DEFLATE_H
|
||||
#define _DEFLATE_H
|
||||
|
||||
#include "zutil.h"
|
||||
|
||||
/* ===========================================================================
|
||||
* Internal compression state.
|
||||
*/
|
||||
|
||||
#define LENGTH_CODES 29
|
||||
/* number of length codes, not counting the special END_BLOCK code */
|
||||
|
||||
#define LITERALS 256
|
||||
/* number of literal bytes 0..255 */
|
||||
|
||||
#define L_CODES (LITERALS+1+LENGTH_CODES)
|
||||
/* number of Literal or Length codes, including the END_BLOCK code */
|
||||
|
||||
#define D_CODES 30
|
||||
/* number of distance codes */
|
||||
|
||||
#define BL_CODES 19
|
||||
/* number of codes used to transfer the bit lengths */
|
||||
|
||||
#define HEAP_SIZE (2*L_CODES+1)
|
||||
/* maximum heap size */
|
||||
|
||||
#define MAX_BITS 15
|
||||
/* All codes must not exceed MAX_BITS bits */
|
||||
|
||||
#define INIT_STATE 42
|
||||
#define BUSY_STATE 113
|
||||
#define FINISH_STATE 666
|
||||
/* Stream status */
|
||||
|
||||
|
||||
/* Data structure describing a single value and its code string. */
|
||||
typedef struct ct_data_s {
|
||||
union {
|
||||
ush freq; /* frequency count */
|
||||
ush code; /* bit string */
|
||||
} fc;
|
||||
union {
|
||||
ush dad; /* father node in Huffman tree */
|
||||
ush len; /* length of bit string */
|
||||
} dl;
|
||||
} FAR ct_data;
|
||||
|
||||
#define Freq fc.freq
|
||||
#define Code fc.code
|
||||
#define Dad dl.dad
|
||||
#define Len dl.len
|
||||
|
||||
typedef struct static_tree_desc_s static_tree_desc;
|
||||
|
||||
typedef struct tree_desc_s {
|
||||
ct_data *dyn_tree; /* the dynamic tree */
|
||||
int max_code; /* largest code with non zero frequency */
|
||||
static_tree_desc *stat_desc; /* the corresponding static tree */
|
||||
} FAR tree_desc;
|
||||
|
||||
typedef ush Pos;
|
||||
typedef Pos FAR Posf;
|
||||
typedef unsigned IPos;
|
||||
|
||||
/* A Pos is an index in the character window. We use short instead of int to
|
||||
* save space in the various tables. IPos is used only for parameter passing.
|
||||
*/
|
||||
|
||||
typedef struct internal_state {
|
||||
z_streamp strm; /* pointer back to this zlib stream */
|
||||
int status; /* as the name implies */
|
||||
Bytef *pending_buf; /* output still pending */
|
||||
ulg pending_buf_size; /* size of pending_buf */
|
||||
Bytef *pending_out; /* next pending byte to output to the stream */
|
||||
int pending; /* nb of bytes in the pending buffer */
|
||||
int noheader; /* suppress zlib header and adler32 */
|
||||
Byte data_type; /* UNKNOWN, BINARY or ASCII */
|
||||
Byte method; /* STORED (for zip only) or DEFLATED */
|
||||
int last_flush; /* value of flush param for previous deflate call */
|
||||
|
||||
/* used by deflate.c: */
|
||||
|
||||
uInt w_size; /* LZ77 window size (32K by default) */
|
||||
uInt w_bits; /* log2(w_size) (8..16) */
|
||||
uInt w_mask; /* w_size - 1 */
|
||||
|
||||
Bytef *window;
|
||||
/* Sliding window. Input bytes are read into the second half of the window,
|
||||
* and move to the first half later to keep a dictionary of at least wSize
|
||||
* bytes. With this organization, matches are limited to a distance of
|
||||
* wSize-MAX_MATCH bytes, but this ensures that IO is always
|
||||
* performed with a length multiple of the block size. Also, it limits
|
||||
* the window size to 64K, which is quite useful on MSDOS.
|
||||
* To do: use the user input buffer as sliding window.
|
||||
*/
|
||||
|
||||
ulg window_size;
|
||||
/* Actual size of window: 2*wSize, except when the user input buffer
|
||||
* is directly used as sliding window.
|
||||
*/
|
||||
|
||||
Posf *prev;
|
||||
/* Link to older string with same hash index. To limit the size of this
|
||||
* array to 64K, this link is maintained only for the last 32K strings.
|
||||
* An index in this array is thus a window index modulo 32K.
|
||||
*/
|
||||
|
||||
Posf *head; /* Heads of the hash chains or NIL. */
|
||||
|
||||
uInt ins_h; /* hash index of string to be inserted */
|
||||
uInt hash_size; /* number of elements in hash table */
|
||||
uInt hash_bits; /* log2(hash_size) */
|
||||
uInt hash_mask; /* hash_size-1 */
|
||||
|
||||
uInt hash_shift;
|
||||
/* Number of bits by which ins_h must be shifted at each input
|
||||
* step. It must be such that after MIN_MATCH steps, the oldest
|
||||
* byte no longer takes part in the hash key, that is:
|
||||
* hash_shift * MIN_MATCH >= hash_bits
|
||||
*/
|
||||
|
||||
long block_start;
|
||||
/* Window position at the beginning of the current output block. Gets
|
||||
* negative when the window is moved backwards.
|
||||
*/
|
||||
|
||||
uInt match_length; /* length of best match */
|
||||
IPos prev_match; /* previous match */
|
||||
int match_available; /* set if previous match exists */
|
||||
uInt strstart; /* start of string to insert */
|
||||
uInt match_start; /* start of matching string */
|
||||
uInt lookahead; /* number of valid bytes ahead in window */
|
||||
|
||||
uInt prev_length;
|
||||
/* Length of the best match at previous step. Matches not greater than this
|
||||
* are discarded. This is used in the lazy match evaluation.
|
||||
*/
|
||||
|
||||
uInt max_chain_length;
|
||||
/* To speed up deflation, hash chains are never searched beyond this
|
||||
* length. A higher limit improves compression ratio but degrades the
|
||||
* speed.
|
||||
*/
|
||||
|
||||
uInt max_lazy_match;
|
||||
/* Attempt to find a better match only when the current match is strictly
|
||||
* smaller than this value. This mechanism is used only for compression
|
||||
* levels >= 4.
|
||||
*/
|
||||
# define max_insert_length max_lazy_match
|
||||
/* Insert new strings in the hash table only if the match length is not
|
||||
* greater than this length. This saves time but degrades compression.
|
||||
* max_insert_length is used only for compression levels <= 3.
|
||||
*/
|
||||
|
||||
int level; /* compression level (1..9) */
|
||||
int strategy; /* favor or force Huffman coding*/
|
||||
|
||||
uInt good_match;
|
||||
/* Use a faster search when the previous match is longer than this */
|
||||
|
||||
int nice_match; /* Stop searching when current match exceeds this */
|
||||
|
||||
/* used by trees.c: */
|
||||
/* Didn't use ct_data typedef below to supress compiler warning */
|
||||
struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
|
||||
struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
|
||||
struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
|
||||
|
||||
struct tree_desc_s l_desc; /* desc. for literal tree */
|
||||
struct tree_desc_s d_desc; /* desc. for distance tree */
|
||||
struct tree_desc_s bl_desc; /* desc. for bit length tree */
|
||||
|
||||
ush bl_count[MAX_BITS+1];
|
||||
/* number of codes at each bit length for an optimal tree */
|
||||
|
||||
int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
|
||||
int heap_len; /* number of elements in the heap */
|
||||
int heap_max; /* element of largest frequency */
|
||||
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
|
||||
* The same heap array is used to build all trees.
|
||||
*/
|
||||
|
||||
uch depth[2*L_CODES+1];
|
||||
/* Depth of each subtree used as tie breaker for trees of equal frequency
|
||||
*/
|
||||
|
||||
uchf *l_buf; /* buffer for literals or lengths */
|
||||
|
||||
uInt lit_bufsize;
|
||||
/* Size of match buffer for literals/lengths. There are 4 reasons for
|
||||
* limiting lit_bufsize to 64K:
|
||||
* - frequencies can be kept in 16 bit counters
|
||||
* - if compression is not successful for the first block, all input
|
||||
* data is still in the window so we can still emit a stored block even
|
||||
* when input comes from standard input. (This can also be done for
|
||||
* all blocks if lit_bufsize is not greater than 32K.)
|
||||
* - if compression is not successful for a file smaller than 64K, we can
|
||||
* even emit a stored file instead of a stored block (saving 5 bytes).
|
||||
* This is applicable only for zip (not gzip or zlib).
|
||||
* - creating new Huffman trees less frequently may not provide fast
|
||||
* adaptation to changes in the input data statistics. (Take for
|
||||
* example a binary file with poorly compressible code followed by
|
||||
* a highly compressible string table.) Smaller buffer sizes give
|
||||
* fast adaptation but have of course the overhead of transmitting
|
||||
* trees more frequently.
|
||||
* - I can't count above 4
|
||||
*/
|
||||
|
||||
uInt last_lit; /* running index in l_buf */
|
||||
|
||||
ushf *d_buf;
|
||||
/* Buffer for distances. To simplify the code, d_buf and l_buf have
|
||||
* the same number of elements. To use different lengths, an extra flag
|
||||
* array would be necessary.
|
||||
*/
|
||||
|
||||
ulg opt_len; /* bit length of current block with optimal trees */
|
||||
ulg static_len; /* bit length of current block with static trees */
|
||||
uInt matches; /* number of string matches in current block */
|
||||
int last_eob_len; /* bit length of EOB code for last block */
|
||||
|
||||
#ifdef DEBUG
|
||||
ulg compressed_len; /* total bit length of compressed file mod 2^32 */
|
||||
ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
|
||||
#endif
|
||||
|
||||
ush bi_buf;
|
||||
/* Output buffer. bits are inserted starting at the bottom (least
|
||||
* significant bits).
|
||||
*/
|
||||
int bi_valid;
|
||||
/* Number of valid bits in bi_buf. All bits above the last valid bit
|
||||
* are always zero.
|
||||
*/
|
||||
|
||||
} FAR deflate_state;
|
||||
|
||||
/* Output a byte on the stream.
|
||||
* IN assertion: there is enough room in pending_buf.
|
||||
*/
|
||||
#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
|
||||
|
||||
|
||||
#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
|
||||
/* Minimum amount of lookahead, except at the end of the input file.
|
||||
* See deflate.c for comments about the MIN_MATCH+1.
|
||||
*/
|
||||
|
||||
#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
|
||||
/* In order to simplify the code, particularly on 16 bit machines, match
|
||||
* distances are limited to MAX_DIST instead of WSIZE.
|
||||
*/
|
||||
|
||||
/* in trees.c */
|
||||
void _tr_init OF((deflate_state *s));
|
||||
int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
|
||||
void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
|
||||
int eof));
|
||||
void _tr_align OF((deflate_state *s));
|
||||
void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
|
||||
int eof));
|
||||
|
||||
#define d_code(dist) \
|
||||
((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
|
||||
/* Mapping from a distance to a distance code. dist is the distance - 1 and
|
||||
* must not have side effects. _dist_code[256] and _dist_code[257] are never
|
||||
* used.
|
||||
*/
|
||||
|
||||
#ifndef DEBUG
|
||||
/* Inline versions of _tr_tally for speed: */
|
||||
|
||||
#if defined(GEN_TREES_H) || !defined(STDC)
|
||||
extern uch _length_code[];
|
||||
extern uch _dist_code[];
|
||||
#else
|
||||
extern const uch _length_code[];
|
||||
extern const uch _dist_code[];
|
||||
#endif
|
||||
|
||||
# define _tr_tally_lit(s, c, flush) \
|
||||
{ uch cc = (c); \
|
||||
s->d_buf[s->last_lit] = 0; \
|
||||
s->l_buf[s->last_lit++] = cc; \
|
||||
s->dyn_ltree[cc].Freq++; \
|
||||
flush = (s->last_lit == s->lit_bufsize-1); \
|
||||
}
|
||||
# define _tr_tally_dist(s, distance, length, flush) \
|
||||
{ uch len = (length); \
|
||||
ush dist = (distance); \
|
||||
s->d_buf[s->last_lit] = dist; \
|
||||
s->l_buf[s->last_lit++] = len; \
|
||||
dist--; \
|
||||
s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
|
||||
s->dyn_dtree[d_code(dist)].Freq++; \
|
||||
flush = (s->last_lit == s->lit_bufsize-1); \
|
||||
}
|
||||
#else
|
||||
# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
|
||||
# define _tr_tally_dist(s, distance, length, flush) \
|
||||
flush = _tr_tally(s, distance, length)
|
||||
#endif
|
||||
|
||||
#endif
|
||||
BIN
Binary file not shown.
+875
@@ -0,0 +1,875 @@
|
||||
/* gzio.c -- IO on .gz files
|
||||
* Copyright (C) 1995-2002 Jean-loup Gailly.
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*
|
||||
* Compile this file with -DNO_DEFLATE to avoid the compression code.
|
||||
*/
|
||||
|
||||
/* @(#) $Id$ */
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#include "zutil.h"
|
||||
|
||||
struct internal_state {int dummy;}; /* for buggy compilers */
|
||||
|
||||
#ifndef Z_BUFSIZE
|
||||
# ifdef MAXSEG_64K
|
||||
# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */
|
||||
# else
|
||||
# define Z_BUFSIZE 16384
|
||||
# endif
|
||||
#endif
|
||||
#ifndef Z_PRINTF_BUFSIZE
|
||||
# define Z_PRINTF_BUFSIZE 4096
|
||||
#endif
|
||||
|
||||
#define ALLOC(size) malloc(size)
|
||||
#define TRYFREE(p) {if (p) free(p);}
|
||||
|
||||
static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
|
||||
|
||||
/* gzip flag byte */
|
||||
#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
|
||||
#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
|
||||
#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
|
||||
#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
|
||||
#define COMMENT 0x10 /* bit 4 set: file comment present */
|
||||
#define RESERVED 0xE0 /* bits 5..7: reserved */
|
||||
|
||||
typedef struct gz_stream {
|
||||
z_stream stream;
|
||||
int z_err; /* error code for last stream operation */
|
||||
int z_eof; /* set if end of input file */
|
||||
FILE *file; /* .gz file */
|
||||
Byte *inbuf; /* input buffer */
|
||||
Byte *outbuf; /* output buffer */
|
||||
uLong crc; /* crc32 of uncompressed data */
|
||||
char *msg; /* error message */
|
||||
char *path; /* path name for debugging only */
|
||||
int transparent; /* 1 if input file is not a .gz file */
|
||||
char mode; /* 'w' or 'r' */
|
||||
long startpos; /* start of compressed data in file (header skipped) */
|
||||
} gz_stream;
|
||||
|
||||
|
||||
local gzFile gz_open OF((const char *path, const char *mode, int fd));
|
||||
local int do_flush OF((gzFile file, int flush));
|
||||
local int get_byte OF((gz_stream *s));
|
||||
local void check_header OF((gz_stream *s));
|
||||
local int destroy OF((gz_stream *s));
|
||||
local void putLong OF((FILE *file, uLong x));
|
||||
local uLong getLong OF((gz_stream *s));
|
||||
|
||||
/* ===========================================================================
|
||||
Opens a gzip (.gz) file for reading or writing. The mode parameter
|
||||
is as in fopen ("rb" or "wb"). The file is given either by file descriptor
|
||||
or path name (if fd == -1).
|
||||
gz_open return NULL if the file could not be opened or if there was
|
||||
insufficient memory to allocate the (de)compression state; errno
|
||||
can be checked to distinguish the two cases (if errno is zero, the
|
||||
zlib error is Z_MEM_ERROR).
|
||||
*/
|
||||
local gzFile gz_open (path, mode, fd)
|
||||
const char *path;
|
||||
const char *mode;
|
||||
int fd;
|
||||
{
|
||||
int err;
|
||||
int level = Z_DEFAULT_COMPRESSION; /* compression level */
|
||||
int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */
|
||||
char *p = (char*)mode;
|
||||
gz_stream *s;
|
||||
char fmode[80]; /* copy of mode, without the compression level */
|
||||
char *m = fmode;
|
||||
|
||||
if (!path || !mode) return Z_NULL;
|
||||
|
||||
s = (gz_stream *)ALLOC(sizeof(gz_stream));
|
||||
if (!s) return Z_NULL;
|
||||
|
||||
s->stream.zalloc = (alloc_func)0;
|
||||
s->stream.zfree = (free_func)0;
|
||||
s->stream.opaque = (voidpf)0;
|
||||
s->stream.next_in = s->inbuf = Z_NULL;
|
||||
s->stream.next_out = s->outbuf = Z_NULL;
|
||||
s->stream.avail_in = s->stream.avail_out = 0;
|
||||
s->file = NULL;
|
||||
s->z_err = Z_OK;
|
||||
s->z_eof = 0;
|
||||
s->crc = crc32(0L, Z_NULL, 0);
|
||||
s->msg = NULL;
|
||||
s->transparent = 0;
|
||||
|
||||
s->path = (char*)ALLOC(strlen(path)+1);
|
||||
if (s->path == NULL) {
|
||||
return destroy(s), (gzFile)Z_NULL;
|
||||
}
|
||||
strcpy(s->path, path); /* do this early for debugging */
|
||||
|
||||
s->mode = '\0';
|
||||
do {
|
||||
if (*p == 'r') s->mode = 'r';
|
||||
if (*p == 'w' || *p == 'a') s->mode = 'w';
|
||||
if (*p >= '0' && *p <= '9') {
|
||||
level = *p - '0';
|
||||
} else if (*p == 'f') {
|
||||
strategy = Z_FILTERED;
|
||||
} else if (*p == 'h') {
|
||||
strategy = Z_HUFFMAN_ONLY;
|
||||
} else {
|
||||
*m++ = *p; /* copy the mode */
|
||||
}
|
||||
} while (*p++ && m != fmode + sizeof(fmode));
|
||||
if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
|
||||
|
||||
if (s->mode == 'w') {
|
||||
#ifdef NO_DEFLATE
|
||||
err = Z_STREAM_ERROR;
|
||||
#else
|
||||
err = deflateInit2(&(s->stream), level,
|
||||
Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy);
|
||||
/* windowBits is passed < 0 to suppress zlib header */
|
||||
|
||||
s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
|
||||
#endif
|
||||
if (err != Z_OK || s->outbuf == Z_NULL) {
|
||||
return destroy(s), (gzFile)Z_NULL;
|
||||
}
|
||||
} else {
|
||||
s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
|
||||
|
||||
err = inflateInit2(&(s->stream), -MAX_WBITS);
|
||||
/* windowBits is passed < 0 to tell that there is no zlib header.
|
||||
* Note that in this case inflate *requires* an extra "dummy" byte
|
||||
* after the compressed stream in order to complete decompression and
|
||||
* return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are
|
||||
* present after the compressed stream.
|
||||
*/
|
||||
if (err != Z_OK || s->inbuf == Z_NULL) {
|
||||
return destroy(s), (gzFile)Z_NULL;
|
||||
}
|
||||
}
|
||||
s->stream.avail_out = Z_BUFSIZE;
|
||||
|
||||
errno = 0;
|
||||
s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode);
|
||||
|
||||
if (s->file == NULL) {
|
||||
return destroy(s), (gzFile)Z_NULL;
|
||||
}
|
||||
if (s->mode == 'w') {
|
||||
/* Write a very simple .gz header:
|
||||
*/
|
||||
fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
|
||||
Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
|
||||
s->startpos = 10L;
|
||||
/* We use 10L instead of ftell(s->file) to because ftell causes an
|
||||
* fflush on some systems. This version of the library doesn't use
|
||||
* startpos anyway in write mode, so this initialization is not
|
||||
* necessary.
|
||||
*/
|
||||
} else {
|
||||
check_header(s); /* skip the .gz header */
|
||||
s->startpos = (ftell(s->file) - s->stream.avail_in);
|
||||
}
|
||||
|
||||
return (gzFile)s;
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Opens a gzip (.gz) file for reading or writing.
|
||||
*/
|
||||
gzFile ZEXPORT gzopen (path, mode)
|
||||
const char *path;
|
||||
const char *mode;
|
||||
{
|
||||
return gz_open (path, mode, -1);
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Associate a gzFile with the file descriptor fd. fd is not dup'ed here
|
||||
to mimic the behavio(u)r of fdopen.
|
||||
*/
|
||||
gzFile ZEXPORT gzdopen (fd, mode)
|
||||
int fd;
|
||||
const char *mode;
|
||||
{
|
||||
char name[20];
|
||||
|
||||
if (fd < 0) return (gzFile)Z_NULL;
|
||||
sprintf(name, "<fd:%d>", fd); /* for debugging */
|
||||
|
||||
return gz_open (name, mode, fd);
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
* Update the compression level and strategy
|
||||
*/
|
||||
int ZEXPORT gzsetparams (file, level, strategy)
|
||||
gzFile file;
|
||||
int level;
|
||||
int strategy;
|
||||
{
|
||||
gz_stream *s = (gz_stream*)file;
|
||||
|
||||
if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
|
||||
|
||||
/* Make room to allow flushing */
|
||||
if (s->stream.avail_out == 0) {
|
||||
|
||||
s->stream.next_out = s->outbuf;
|
||||
if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
|
||||
s->z_err = Z_ERRNO;
|
||||
}
|
||||
s->stream.avail_out = Z_BUFSIZE;
|
||||
}
|
||||
|
||||
return deflateParams (&(s->stream), level, strategy);
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Read a byte from a gz_stream; update next_in and avail_in. Return EOF
|
||||
for end of file.
|
||||
IN assertion: the stream s has been sucessfully opened for reading.
|
||||
*/
|
||||
local int get_byte(s)
|
||||
gz_stream *s;
|
||||
{
|
||||
if (s->z_eof) return EOF;
|
||||
if (s->stream.avail_in == 0) {
|
||||
errno = 0;
|
||||
s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file);
|
||||
if (s->stream.avail_in == 0) {
|
||||
s->z_eof = 1;
|
||||
if (ferror(s->file)) s->z_err = Z_ERRNO;
|
||||
return EOF;
|
||||
}
|
||||
s->stream.next_in = s->inbuf;
|
||||
}
|
||||
s->stream.avail_in--;
|
||||
return *(s->stream.next_in)++;
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Check the gzip header of a gz_stream opened for reading. Set the stream
|
||||
mode to transparent if the gzip magic header is not present; set s->err
|
||||
to Z_DATA_ERROR if the magic header is present but the rest of the header
|
||||
is incorrect.
|
||||
IN assertion: the stream s has already been created sucessfully;
|
||||
s->stream.avail_in is zero for the first time, but may be non-zero
|
||||
for concatenated .gz files.
|
||||
*/
|
||||
local void check_header(s)
|
||||
gz_stream *s;
|
||||
{
|
||||
int method; /* method byte */
|
||||
int flags; /* flags byte */
|
||||
uInt len;
|
||||
int c;
|
||||
|
||||
/* Check the gzip magic header */
|
||||
for (len = 0; len < 2; len++) {
|
||||
c = get_byte(s);
|
||||
if (c != gz_magic[len]) {
|
||||
if (len != 0) s->stream.avail_in++, s->stream.next_in--;
|
||||
if (c != EOF) {
|
||||
s->stream.avail_in++, s->stream.next_in--;
|
||||
s->transparent = 1;
|
||||
}
|
||||
s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END;
|
||||
return;
|
||||
}
|
||||
}
|
||||
method = get_byte(s);
|
||||
flags = get_byte(s);
|
||||
if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
|
||||
s->z_err = Z_DATA_ERROR;
|
||||
return;
|
||||
}
|
||||
|
||||
/* Discard time, xflags and OS code: */
|
||||
for (len = 0; len < 6; len++) (void)get_byte(s);
|
||||
|
||||
if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
|
||||
len = (uInt)get_byte(s);
|
||||
len += ((uInt)get_byte(s))<<8;
|
||||
/* len is garbage if EOF but the loop below will quit anyway */
|
||||
while (len-- != 0 && get_byte(s) != EOF) ;
|
||||
}
|
||||
if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
|
||||
while ((c = get_byte(s)) != 0 && c != EOF) ;
|
||||
}
|
||||
if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
|
||||
while ((c = get_byte(s)) != 0 && c != EOF) ;
|
||||
}
|
||||
if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
|
||||
for (len = 0; len < 2; len++) (void)get_byte(s);
|
||||
}
|
||||
s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
* Cleanup then free the given gz_stream. Return a zlib error code.
|
||||
Try freeing in the reverse order of allocations.
|
||||
*/
|
||||
local int destroy (s)
|
||||
gz_stream *s;
|
||||
{
|
||||
int err = Z_OK;
|
||||
|
||||
if (!s) return Z_STREAM_ERROR;
|
||||
|
||||
TRYFREE(s->msg);
|
||||
|
||||
if (s->stream.state != NULL) {
|
||||
if (s->mode == 'w') {
|
||||
#ifdef NO_DEFLATE
|
||||
err = Z_STREAM_ERROR;
|
||||
#else
|
||||
err = deflateEnd(&(s->stream));
|
||||
#endif
|
||||
} else if (s->mode == 'r') {
|
||||
err = inflateEnd(&(s->stream));
|
||||
}
|
||||
}
|
||||
if (s->file != NULL && fclose(s->file)) {
|
||||
#ifdef ESPIPE
|
||||
if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */
|
||||
#endif
|
||||
err = Z_ERRNO;
|
||||
}
|
||||
if (s->z_err < 0) err = s->z_err;
|
||||
|
||||
TRYFREE(s->inbuf);
|
||||
TRYFREE(s->outbuf);
|
||||
TRYFREE(s->path);
|
||||
TRYFREE(s);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Reads the given number of uncompressed bytes from the compressed file.
|
||||
gzread returns the number of bytes actually read (0 for end of file).
|
||||
*/
|
||||
int ZEXPORT gzread (file, buf, len)
|
||||
gzFile file;
|
||||
voidp buf;
|
||||
unsigned len;
|
||||
{
|
||||
gz_stream *s = (gz_stream*)file;
|
||||
Bytef *start = (Bytef*)buf; /* starting point for crc computation */
|
||||
Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */
|
||||
|
||||
if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
|
||||
|
||||
if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
|
||||
if (s->z_err == Z_STREAM_END) return 0; /* EOF */
|
||||
|
||||
next_out = (Byte*)buf;
|
||||
s->stream.next_out = (Bytef*)buf;
|
||||
s->stream.avail_out = len;
|
||||
|
||||
while (s->stream.avail_out != 0) {
|
||||
|
||||
if (s->transparent) {
|
||||
/* Copy first the lookahead bytes: */
|
||||
uInt n = s->stream.avail_in;
|
||||
if (n > s->stream.avail_out) n = s->stream.avail_out;
|
||||
if (n > 0) {
|
||||
zmemcpy(s->stream.next_out, s->stream.next_in, n);
|
||||
next_out += n;
|
||||
s->stream.next_out = next_out;
|
||||
s->stream.next_in += n;
|
||||
s->stream.avail_out -= n;
|
||||
s->stream.avail_in -= n;
|
||||
}
|
||||
if (s->stream.avail_out > 0) {
|
||||
s->stream.avail_out -= fread(next_out, 1, s->stream.avail_out,
|
||||
s->file);
|
||||
}
|
||||
len -= s->stream.avail_out;
|
||||
s->stream.total_in += (uLong)len;
|
||||
s->stream.total_out += (uLong)len;
|
||||
if (len == 0) s->z_eof = 1;
|
||||
return (int)len;
|
||||
}
|
||||
if (s->stream.avail_in == 0 && !s->z_eof) {
|
||||
|
||||
errno = 0;
|
||||
s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file);
|
||||
if (s->stream.avail_in == 0) {
|
||||
s->z_eof = 1;
|
||||
if (ferror(s->file)) {
|
||||
s->z_err = Z_ERRNO;
|
||||
break;
|
||||
}
|
||||
}
|
||||
s->stream.next_in = s->inbuf;
|
||||
}
|
||||
s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
|
||||
|
||||
if (s->z_err == Z_STREAM_END) {
|
||||
/* Check CRC and original size */
|
||||
s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
|
||||
start = s->stream.next_out;
|
||||
|
||||
if (getLong(s) != s->crc) {
|
||||
s->z_err = Z_DATA_ERROR;
|
||||
} else {
|
||||
(void)getLong(s);
|
||||
/* The uncompressed length returned by above getlong() may
|
||||
* be different from s->stream.total_out) in case of
|
||||
* concatenated .gz files. Check for such files:
|
||||
*/
|
||||
check_header(s);
|
||||
if (s->z_err == Z_OK) {
|
||||
uLong total_in = s->stream.total_in;
|
||||
uLong total_out = s->stream.total_out;
|
||||
|
||||
inflateReset(&(s->stream));
|
||||
s->stream.total_in = total_in;
|
||||
s->stream.total_out = total_out;
|
||||
s->crc = crc32(0L, Z_NULL, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s->z_err != Z_OK || s->z_eof) break;
|
||||
}
|
||||
s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
|
||||
|
||||
return (int)(len - s->stream.avail_out);
|
||||
}
|
||||
|
||||
|
||||
/* ===========================================================================
|
||||
Reads one byte from the compressed file. gzgetc returns this byte
|
||||
or -1 in case of end of file or error.
|
||||
*/
|
||||
int ZEXPORT gzgetc(file)
|
||||
gzFile file;
|
||||
{
|
||||
unsigned char c;
|
||||
|
||||
return gzread(file, &c, 1) == 1 ? c : -1;
|
||||
}
|
||||
|
||||
|
||||
/* ===========================================================================
|
||||
Reads bytes from the compressed file until len-1 characters are
|
||||
read, or a newline character is read and transferred to buf, or an
|
||||
end-of-file condition is encountered. The string is then terminated
|
||||
with a null character.
|
||||
gzgets returns buf, or Z_NULL in case of error.
|
||||
|
||||
The current implementation is not optimized at all.
|
||||
*/
|
||||
char * ZEXPORT gzgets(file, buf, len)
|
||||
gzFile file;
|
||||
char *buf;
|
||||
int len;
|
||||
{
|
||||
char *b = buf;
|
||||
if (buf == Z_NULL || len <= 0) return Z_NULL;
|
||||
|
||||
while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ;
|
||||
*buf = '\0';
|
||||
return b == buf && len > 0 ? Z_NULL : b;
|
||||
}
|
||||
|
||||
|
||||
#ifndef NO_DEFLATE
|
||||
/* ===========================================================================
|
||||
Writes the given number of uncompressed bytes into the compressed file.
|
||||
gzwrite returns the number of bytes actually written (0 in case of error).
|
||||
*/
|
||||
int ZEXPORT gzwrite (file, buf, len)
|
||||
gzFile file;
|
||||
const voidp buf;
|
||||
unsigned len;
|
||||
{
|
||||
gz_stream *s = (gz_stream*)file;
|
||||
|
||||
if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
|
||||
|
||||
s->stream.next_in = (Bytef*)buf;
|
||||
s->stream.avail_in = len;
|
||||
|
||||
while (s->stream.avail_in != 0) {
|
||||
|
||||
if (s->stream.avail_out == 0) {
|
||||
|
||||
s->stream.next_out = s->outbuf;
|
||||
if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
|
||||
s->z_err = Z_ERRNO;
|
||||
break;
|
||||
}
|
||||
s->stream.avail_out = Z_BUFSIZE;
|
||||
}
|
||||
s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
|
||||
if (s->z_err != Z_OK) break;
|
||||
}
|
||||
s->crc = crc32(s->crc, (const Bytef *)buf, len);
|
||||
|
||||
return (int)(len - s->stream.avail_in);
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Converts, formats, and writes the args to the compressed file under
|
||||
control of the format string, as in fprintf. gzprintf returns the number of
|
||||
uncompressed bytes actually written (0 in case of error).
|
||||
*/
|
||||
#ifdef STDC
|
||||
#include <stdarg.h>
|
||||
|
||||
int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...)
|
||||
{
|
||||
char buf[Z_PRINTF_BUFSIZE];
|
||||
va_list va;
|
||||
int len;
|
||||
|
||||
va_start(va, format);
|
||||
#ifdef HAS_vsnprintf
|
||||
(void)vsnprintf(buf, sizeof(buf), format, va);
|
||||
#else
|
||||
(void)vsprintf(buf, format, va);
|
||||
#endif
|
||||
va_end(va);
|
||||
len = strlen(buf); /* some *sprintf don't return the nb of bytes written */
|
||||
if (len <= 0) return 0;
|
||||
|
||||
return gzwrite(file, buf, (unsigned)len);
|
||||
}
|
||||
#else /* not ANSI C */
|
||||
|
||||
int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
|
||||
a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
|
||||
gzFile file;
|
||||
const char *format;
|
||||
int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
|
||||
a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
|
||||
{
|
||||
char buf[Z_PRINTF_BUFSIZE];
|
||||
int len;
|
||||
|
||||
#ifdef HAS_snprintf
|
||||
snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
|
||||
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
|
||||
#else
|
||||
sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
|
||||
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
|
||||
#endif
|
||||
len = strlen(buf); /* old sprintf doesn't return the nb of bytes written */
|
||||
if (len <= 0) return 0;
|
||||
|
||||
return gzwrite(file, buf, len);
|
||||
}
|
||||
#endif
|
||||
|
||||
/* ===========================================================================
|
||||
Writes c, converted to an unsigned char, into the compressed file.
|
||||
gzputc returns the value that was written, or -1 in case of error.
|
||||
*/
|
||||
int ZEXPORT gzputc(file, c)
|
||||
gzFile file;
|
||||
int c;
|
||||
{
|
||||
unsigned char cc = (unsigned char) c; /* required for big endian systems */
|
||||
|
||||
return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1;
|
||||
}
|
||||
|
||||
|
||||
/* ===========================================================================
|
||||
Writes the given null-terminated string to the compressed file, excluding
|
||||
the terminating null character.
|
||||
gzputs returns the number of characters written, or -1 in case of error.
|
||||
*/
|
||||
int ZEXPORT gzputs(file, s)
|
||||
gzFile file;
|
||||
const char *s;
|
||||
{
|
||||
return gzwrite(file, (char*)s, (unsigned)strlen(s));
|
||||
}
|
||||
|
||||
|
||||
/* ===========================================================================
|
||||
Flushes all pending output into the compressed file. The parameter
|
||||
flush is as in the deflate() function.
|
||||
*/
|
||||
local int do_flush (file, flush)
|
||||
gzFile file;
|
||||
int flush;
|
||||
{
|
||||
uInt len;
|
||||
int done = 0;
|
||||
gz_stream *s = (gz_stream*)file;
|
||||
|
||||
if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
|
||||
|
||||
s->stream.avail_in = 0; /* should be zero already anyway */
|
||||
|
||||
for (;;) {
|
||||
len = Z_BUFSIZE - s->stream.avail_out;
|
||||
|
||||
if (len != 0) {
|
||||
if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) {
|
||||
s->z_err = Z_ERRNO;
|
||||
return Z_ERRNO;
|
||||
}
|
||||
s->stream.next_out = s->outbuf;
|
||||
s->stream.avail_out = Z_BUFSIZE;
|
||||
}
|
||||
if (done) break;
|
||||
s->z_err = deflate(&(s->stream), flush);
|
||||
|
||||
/* Ignore the second of two consecutive flushes: */
|
||||
if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK;
|
||||
|
||||
/* deflate has finished flushing only when it hasn't used up
|
||||
* all the available space in the output buffer:
|
||||
*/
|
||||
done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
|
||||
|
||||
if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
|
||||
}
|
||||
return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
|
||||
}
|
||||
|
||||
int ZEXPORT gzflush (file, flush)
|
||||
gzFile file;
|
||||
int flush;
|
||||
{
|
||||
gz_stream *s = (gz_stream*)file;
|
||||
int err = do_flush (file, flush);
|
||||
|
||||
if (err) return err;
|
||||
fflush(s->file);
|
||||
return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
|
||||
}
|
||||
#endif /* NO_DEFLATE */
|
||||
|
||||
/* ===========================================================================
|
||||
Sets the starting position for the next gzread or gzwrite on the given
|
||||
compressed file. The offset represents a number of bytes in the
|
||||
gzseek returns the resulting offset location as measured in bytes from
|
||||
the beginning of the uncompressed stream, or -1 in case of error.
|
||||
SEEK_END is not implemented, returns error.
|
||||
In this version of the library, gzseek can be extremely slow.
|
||||
*/
|
||||
z_off_t ZEXPORT gzseek (file, offset, whence)
|
||||
gzFile file;
|
||||
z_off_t offset;
|
||||
int whence;
|
||||
{
|
||||
gz_stream *s = (gz_stream*)file;
|
||||
|
||||
if (s == NULL || whence == SEEK_END ||
|
||||
s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) {
|
||||
return -1L;
|
||||
}
|
||||
|
||||
if (s->mode == 'w') {
|
||||
#ifdef NO_DEFLATE
|
||||
return -1L;
|
||||
#else
|
||||
if (whence == SEEK_SET) {
|
||||
offset -= s->stream.total_in;
|
||||
}
|
||||
if (offset < 0) return -1L;
|
||||
|
||||
/* At this point, offset is the number of zero bytes to write. */
|
||||
if (s->inbuf == Z_NULL) {
|
||||
s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */
|
||||
zmemzero(s->inbuf, Z_BUFSIZE);
|
||||
}
|
||||
while (offset > 0) {
|
||||
uInt size = Z_BUFSIZE;
|
||||
if (offset < Z_BUFSIZE) size = (uInt)offset;
|
||||
|
||||
size = gzwrite(file, s->inbuf, size);
|
||||
if (size == 0) return -1L;
|
||||
|
||||
offset -= size;
|
||||
}
|
||||
return (z_off_t)s->stream.total_in;
|
||||
#endif
|
||||
}
|
||||
/* Rest of function is for reading only */
|
||||
|
||||
/* compute absolute position */
|
||||
if (whence == SEEK_CUR) {
|
||||
offset += s->stream.total_out;
|
||||
}
|
||||
if (offset < 0) return -1L;
|
||||
|
||||
if (s->transparent) {
|
||||
/* map to fseek */
|
||||
s->stream.avail_in = 0;
|
||||
s->stream.next_in = s->inbuf;
|
||||
if (fseek(s->file, offset, SEEK_SET) < 0) return -1L;
|
||||
|
||||
s->stream.total_in = s->stream.total_out = (uLong)offset;
|
||||
return offset;
|
||||
}
|
||||
|
||||
/* For a negative seek, rewind and use positive seek */
|
||||
if ((uLong)offset >= s->stream.total_out) {
|
||||
offset -= s->stream.total_out;
|
||||
} else if (gzrewind(file) < 0) {
|
||||
return -1L;
|
||||
}
|
||||
/* offset is now the number of bytes to skip. */
|
||||
|
||||
if (offset != 0 && s->outbuf == Z_NULL) {
|
||||
s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
|
||||
}
|
||||
while (offset > 0) {
|
||||
int size = Z_BUFSIZE;
|
||||
if (offset < Z_BUFSIZE) size = (int)offset;
|
||||
|
||||
size = gzread(file, s->outbuf, (uInt)size);
|
||||
if (size <= 0) return -1L;
|
||||
offset -= size;
|
||||
}
|
||||
return (z_off_t)s->stream.total_out;
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Rewinds input file.
|
||||
*/
|
||||
int ZEXPORT gzrewind (file)
|
||||
gzFile file;
|
||||
{
|
||||
gz_stream *s = (gz_stream*)file;
|
||||
|
||||
if (s == NULL || s->mode != 'r') return -1;
|
||||
|
||||
s->z_err = Z_OK;
|
||||
s->z_eof = 0;
|
||||
s->stream.avail_in = 0;
|
||||
s->stream.next_in = s->inbuf;
|
||||
s->crc = crc32(0L, Z_NULL, 0);
|
||||
|
||||
if (s->startpos == 0) { /* not a compressed file */
|
||||
rewind(s->file);
|
||||
return 0;
|
||||
}
|
||||
|
||||
(void) inflateReset(&s->stream);
|
||||
return fseek(s->file, s->startpos, SEEK_SET);
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Returns the starting position for the next gzread or gzwrite on the
|
||||
given compressed file. This position represents a number of bytes in the
|
||||
uncompressed data stream.
|
||||
*/
|
||||
z_off_t ZEXPORT gztell (file)
|
||||
gzFile file;
|
||||
{
|
||||
return gzseek(file, 0L, SEEK_CUR);
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Returns 1 when EOF has previously been detected reading the given
|
||||
input stream, otherwise zero.
|
||||
*/
|
||||
int ZEXPORT gzeof (file)
|
||||
gzFile file;
|
||||
{
|
||||
gz_stream *s = (gz_stream*)file;
|
||||
|
||||
return (s == NULL || s->mode != 'r') ? 0 : s->z_eof;
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Outputs a long in LSB order to the given file
|
||||
*/
|
||||
local void putLong (file, x)
|
||||
FILE *file;
|
||||
uLong x;
|
||||
{
|
||||
int n;
|
||||
for (n = 0; n < 4; n++) {
|
||||
fputc((int)(x & 0xff), file);
|
||||
x >>= 8;
|
||||
}
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Reads a long in LSB order from the given gz_stream. Sets z_err in case
|
||||
of error.
|
||||
*/
|
||||
local uLong getLong (s)
|
||||
gz_stream *s;
|
||||
{
|
||||
uLong x = (uLong)get_byte(s);
|
||||
int c;
|
||||
|
||||
x += ((uLong)get_byte(s))<<8;
|
||||
x += ((uLong)get_byte(s))<<16;
|
||||
c = get_byte(s);
|
||||
if (c == EOF) s->z_err = Z_DATA_ERROR;
|
||||
x += ((uLong)c)<<24;
|
||||
return x;
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Flushes all pending output if necessary, closes the compressed file
|
||||
and deallocates all the (de)compression state.
|
||||
*/
|
||||
int ZEXPORT gzclose (file)
|
||||
gzFile file;
|
||||
{
|
||||
int err;
|
||||
gz_stream *s = (gz_stream*)file;
|
||||
|
||||
if (s == NULL) return Z_STREAM_ERROR;
|
||||
|
||||
if (s->mode == 'w') {
|
||||
#ifdef NO_DEFLATE
|
||||
return Z_STREAM_ERROR;
|
||||
#else
|
||||
err = do_flush (file, Z_FINISH);
|
||||
if (err != Z_OK) return destroy((gz_stream*)file);
|
||||
|
||||
putLong (s->file, s->crc);
|
||||
putLong (s->file, s->stream.total_in);
|
||||
#endif
|
||||
}
|
||||
return destroy((gz_stream*)file);
|
||||
}
|
||||
|
||||
/* ===========================================================================
|
||||
Returns the error message for the last error which occured on the
|
||||
given compressed file. errnum is set to zlib error number. If an
|
||||
error occured in the file system and not in the compression library,
|
||||
errnum is set to Z_ERRNO and the application may consult errno
|
||||
to get the exact error code.
|
||||
*/
|
||||
const char* ZEXPORT gzerror (file, errnum)
|
||||
gzFile file;
|
||||
int *errnum;
|
||||
{
|
||||
char *m;
|
||||
gz_stream *s = (gz_stream*)file;
|
||||
|
||||
if (s == NULL) {
|
||||
*errnum = Z_STREAM_ERROR;
|
||||
return (const char*)ERR_MSG(Z_STREAM_ERROR);
|
||||
}
|
||||
*errnum = s->z_err;
|
||||
if (*errnum == Z_OK) return (const char*)"";
|
||||
|
||||
m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg);
|
||||
|
||||
if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
|
||||
|
||||
TRYFREE(s->msg);
|
||||
s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3);
|
||||
strcpy(s->msg, s->path);
|
||||
strcat(s->msg, ": ");
|
||||
strcat(s->msg, m);
|
||||
return (const char*)s->msg;
|
||||
}
|
||||
BIN
Binary file not shown.
+403
@@ -0,0 +1,403 @@
|
||||
/* infblock.c -- interpret and process block types to last block
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
#include "zutil.h"
|
||||
#include "infblock.h"
|
||||
#include "inftrees.h"
|
||||
#include "infcodes.h"
|
||||
#include "infutil.h"
|
||||
|
||||
struct inflate_codes_state {int dummy;}; /* for buggy compilers */
|
||||
|
||||
/* simplify the use of the inflate_huft type with some defines */
|
||||
#define exop word.what.Exop
|
||||
#define bits word.what.Bits
|
||||
|
||||
/* Table for deflate from PKZIP's appnote.txt. */
|
||||
local const uInt border[] = { /* Order of the bit length code lengths */
|
||||
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
|
||||
|
||||
/*
|
||||
Notes beyond the 1.93a appnote.txt:
|
||||
|
||||
1. Distance pointers never point before the beginning of the output
|
||||
stream.
|
||||
2. Distance pointers can point back across blocks, up to 32k away.
|
||||
3. There is an implied maximum of 7 bits for the bit length table and
|
||||
15 bits for the actual data.
|
||||
4. If only one code exists, then it is encoded using one bit. (Zero
|
||||
would be more efficient, but perhaps a little confusing.) If two
|
||||
codes exist, they are coded using one bit each (0 and 1).
|
||||
5. There is no way of sending zero distance codes--a dummy must be
|
||||
sent if there are none. (History: a pre 2.0 version of PKZIP would
|
||||
store blocks with no distance codes, but this was discovered to be
|
||||
too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
|
||||
zero distance codes, which is sent as one code of zero bits in
|
||||
length.
|
||||
6. There are up to 286 literal/length codes. Code 256 represents the
|
||||
end-of-block. Note however that the static length tree defines
|
||||
288 codes just to fill out the Huffman codes. Codes 286 and 287
|
||||
cannot be used though, since there is no length base or extra bits
|
||||
defined for them. Similarily, there are up to 30 distance codes.
|
||||
However, static trees define 32 codes (all 5 bits) to fill out the
|
||||
Huffman codes, but the last two had better not show up in the data.
|
||||
7. Unzip can check dynamic Huffman blocks for complete code sets.
|
||||
The exception is that a single code would not be complete (see #4).
|
||||
8. The five bits following the block type is really the number of
|
||||
literal codes sent minus 257.
|
||||
9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
|
||||
(1+6+6). Therefore, to output three times the length, you output
|
||||
three codes (1+1+1), whereas to output four times the same length,
|
||||
you only need two codes (1+3). Hmm.
|
||||
10. In the tree reconstruction algorithm, Code = Code + Increment
|
||||
only if BitLength(i) is not zero. (Pretty obvious.)
|
||||
11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
|
||||
12. Note: length code 284 can represent 227-258, but length code 285
|
||||
really is 258. The last length deserves its own, short code
|
||||
since it gets used a lot in very redundant files. The length
|
||||
258 is special since 258 - 3 (the min match length) is 255.
|
||||
13. The literal/length and distance code bit lengths are read as a
|
||||
single stream of lengths. It is possible (and advantageous) for
|
||||
a repeat code (16, 17, or 18) to go across the boundary between
|
||||
the two sets of lengths.
|
||||
*/
|
||||
|
||||
|
||||
void inflate_blocks_reset(s, z, c)
|
||||
inflate_blocks_statef *s;
|
||||
z_streamp z;
|
||||
uLongf *c;
|
||||
{
|
||||
if (c != Z_NULL)
|
||||
*c = s->check;
|
||||
if (s->mode == BTREE || s->mode == DTREE)
|
||||
ZFREE(z, s->sub.trees.blens);
|
||||
if (s->mode == CODES)
|
||||
inflate_codes_free(s->sub.decode.codes, z);
|
||||
s->mode = TYPE;
|
||||
s->bitk = 0;
|
||||
s->bitb = 0;
|
||||
s->read = s->write = s->window;
|
||||
if (s->checkfn != Z_NULL)
|
||||
z->adler = s->check = (*s->checkfn)(0L, (const Bytef *)Z_NULL, 0);
|
||||
Tracev((stderr, "inflate: blocks reset\n"));
|
||||
}
|
||||
|
||||
|
||||
inflate_blocks_statef *inflate_blocks_new(z, c, w)
|
||||
z_streamp z;
|
||||
check_func c;
|
||||
uInt w;
|
||||
{
|
||||
inflate_blocks_statef *s;
|
||||
|
||||
if ((s = (inflate_blocks_statef *)ZALLOC
|
||||
(z,1,sizeof(struct inflate_blocks_state))) == Z_NULL)
|
||||
return s;
|
||||
if ((s->hufts =
|
||||
(inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL)
|
||||
{
|
||||
ZFREE(z, s);
|
||||
return Z_NULL;
|
||||
}
|
||||
if ((s->window = (Bytef *)ZALLOC(z, 1, w)) == Z_NULL)
|
||||
{
|
||||
ZFREE(z, s->hufts);
|
||||
ZFREE(z, s);
|
||||
return Z_NULL;
|
||||
}
|
||||
s->end = s->window + w;
|
||||
s->checkfn = c;
|
||||
s->mode = TYPE;
|
||||
Tracev((stderr, "inflate: blocks allocated\n"));
|
||||
inflate_blocks_reset(s, z, Z_NULL);
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
int inflate_blocks(s, z, r)
|
||||
inflate_blocks_statef *s;
|
||||
z_streamp z;
|
||||
int r;
|
||||
{
|
||||
uInt t; /* temporary storage */
|
||||
uLong b; /* bit buffer */
|
||||
uInt k; /* bits in bit buffer */
|
||||
Bytef *p; /* input data pointer */
|
||||
uInt n; /* bytes available there */
|
||||
Bytef *q; /* output window write pointer */
|
||||
uInt m; /* bytes to end of window or read pointer */
|
||||
|
||||
/* copy input/output information to locals (UPDATE macro restores) */
|
||||
LOAD
|
||||
|
||||
/* process input based on current state */
|
||||
while (1) switch (s->mode)
|
||||
{
|
||||
case TYPE:
|
||||
NEEDBITS(3)
|
||||
t = (uInt)b & 7;
|
||||
s->last = t & 1;
|
||||
switch (t >> 1)
|
||||
{
|
||||
case 0: /* stored */
|
||||
Tracev((stderr, "inflate: stored block%s\n",
|
||||
s->last ? " (last)" : ""));
|
||||
DUMPBITS(3)
|
||||
t = k & 7; /* go to byte boundary */
|
||||
DUMPBITS(t)
|
||||
s->mode = LENS; /* get length of stored block */
|
||||
break;
|
||||
case 1: /* fixed */
|
||||
Tracev((stderr, "inflate: fixed codes block%s\n",
|
||||
s->last ? " (last)" : ""));
|
||||
{
|
||||
uInt bl, bd;
|
||||
inflate_huft *tl, *td;
|
||||
|
||||
inflate_trees_fixed(&bl, &bd, &tl, &td, z);
|
||||
s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z);
|
||||
if (s->sub.decode.codes == Z_NULL)
|
||||
{
|
||||
r = Z_MEM_ERROR;
|
||||
LEAVE
|
||||
}
|
||||
}
|
||||
DUMPBITS(3)
|
||||
s->mode = CODES;
|
||||
break;
|
||||
case 2: /* dynamic */
|
||||
Tracev((stderr, "inflate: dynamic codes block%s\n",
|
||||
s->last ? " (last)" : ""));
|
||||
DUMPBITS(3)
|
||||
s->mode = TABLE;
|
||||
break;
|
||||
case 3: /* illegal */
|
||||
DUMPBITS(3)
|
||||
s->mode = BAD;
|
||||
z->msg = (char*)"invalid block type";
|
||||
r = Z_DATA_ERROR;
|
||||
LEAVE
|
||||
}
|
||||
break;
|
||||
case LENS:
|
||||
NEEDBITS(32)
|
||||
if ((((~b) >> 16) & 0xffff) != (b & 0xffff))
|
||||
{
|
||||
s->mode = BAD;
|
||||
z->msg = (char*)"invalid stored block lengths";
|
||||
r = Z_DATA_ERROR;
|
||||
LEAVE
|
||||
}
|
||||
s->sub.left = (uInt)b & 0xffff;
|
||||
b = k = 0; /* dump bits */
|
||||
Tracev((stderr, "inflate: stored length %u\n", s->sub.left));
|
||||
s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE);
|
||||
break;
|
||||
case STORED:
|
||||
if (n == 0)
|
||||
LEAVE
|
||||
NEEDOUT
|
||||
t = s->sub.left;
|
||||
if (t > n) t = n;
|
||||
if (t > m) t = m;
|
||||
zmemcpy(q, p, t);
|
||||
p += t; n -= t;
|
||||
q += t; m -= t;
|
||||
if ((s->sub.left -= t) != 0)
|
||||
break;
|
||||
Tracev((stderr, "inflate: stored end, %lu total out\n",
|
||||
z->total_out + (q >= s->read ? q - s->read :
|
||||
(s->end - s->read) + (q - s->window))));
|
||||
s->mode = s->last ? DRY : TYPE;
|
||||
break;
|
||||
case TABLE:
|
||||
NEEDBITS(14)
|
||||
s->sub.trees.table = t = (uInt)b & 0x3fff;
|
||||
#ifndef PKZIP_BUG_WORKAROUND
|
||||
if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
|
||||
{
|
||||
s->mode = BAD;
|
||||
z->msg = (char*)"too many length or distance symbols";
|
||||
r = Z_DATA_ERROR;
|
||||
LEAVE
|
||||
}
|
||||
#endif
|
||||
t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
|
||||
if ((s->sub.trees.blens = (uIntf*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL)
|
||||
{
|
||||
r = Z_MEM_ERROR;
|
||||
LEAVE
|
||||
}
|
||||
DUMPBITS(14)
|
||||
s->sub.trees.index = 0;
|
||||
Tracev((stderr, "inflate: table sizes ok\n"));
|
||||
s->mode = BTREE;
|
||||
case BTREE:
|
||||
while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
|
||||
{
|
||||
NEEDBITS(3)
|
||||
s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
|
||||
DUMPBITS(3)
|
||||
}
|
||||
while (s->sub.trees.index < 19)
|
||||
s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
|
||||
s->sub.trees.bb = 7;
|
||||
t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
|
||||
&s->sub.trees.tb, s->hufts, z);
|
||||
if (t != Z_OK)
|
||||
{
|
||||
r = t;
|
||||
if (r == Z_DATA_ERROR)
|
||||
{
|
||||
ZFREE(z, s->sub.trees.blens);
|
||||
s->mode = BAD;
|
||||
}
|
||||
LEAVE
|
||||
}
|
||||
s->sub.trees.index = 0;
|
||||
Tracev((stderr, "inflate: bits tree ok\n"));
|
||||
s->mode = DTREE;
|
||||
case DTREE:
|
||||
while (t = s->sub.trees.table,
|
||||
s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))
|
||||
{
|
||||
inflate_huft *h;
|
||||
uInt i, j, c;
|
||||
|
||||
t = s->sub.trees.bb;
|
||||
NEEDBITS(t)
|
||||
h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]);
|
||||
t = h->bits;
|
||||
c = h->base;
|
||||
if (c < 16)
|
||||
{
|
||||
DUMPBITS(t)
|
||||
s->sub.trees.blens[s->sub.trees.index++] = c;
|
||||
}
|
||||
else /* c == 16..18 */
|
||||
{
|
||||
i = c == 18 ? 7 : c - 14;
|
||||
j = c == 18 ? 11 : 3;
|
||||
NEEDBITS(t + i)
|
||||
DUMPBITS(t)
|
||||
j += (uInt)b & inflate_mask[i];
|
||||
DUMPBITS(i)
|
||||
i = s->sub.trees.index;
|
||||
t = s->sub.trees.table;
|
||||
if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
|
||||
(c == 16 && i < 1))
|
||||
{
|
||||
ZFREE(z, s->sub.trees.blens);
|
||||
s->mode = BAD;
|
||||
z->msg = (char*)"invalid bit length repeat";
|
||||
r = Z_DATA_ERROR;
|
||||
LEAVE
|
||||
}
|
||||
c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
|
||||
do {
|
||||
s->sub.trees.blens[i++] = c;
|
||||
} while (--j);
|
||||
s->sub.trees.index = i;
|
||||
}
|
||||
}
|
||||
s->sub.trees.tb = Z_NULL;
|
||||
{
|
||||
uInt bl, bd;
|
||||
inflate_huft *tl, *td;
|
||||
inflate_codes_statef *c;
|
||||
|
||||
bl = 9; /* must be <= 9 for lookahead assumptions */
|
||||
bd = 6; /* must be <= 9 for lookahead assumptions */
|
||||
t = s->sub.trees.table;
|
||||
t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
|
||||
s->sub.trees.blens, &bl, &bd, &tl, &td,
|
||||
s->hufts, z);
|
||||
if (t != Z_OK)
|
||||
{
|
||||
if (t == (uInt)Z_DATA_ERROR)
|
||||
{
|
||||
ZFREE(z, s->sub.trees.blens);
|
||||
s->mode = BAD;
|
||||
}
|
||||
r = t;
|
||||
LEAVE
|
||||
}
|
||||
Tracev((stderr, "inflate: trees ok\n"));
|
||||
if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL)
|
||||
{
|
||||
r = Z_MEM_ERROR;
|
||||
LEAVE
|
||||
}
|
||||
s->sub.decode.codes = c;
|
||||
}
|
||||
ZFREE(z, s->sub.trees.blens);
|
||||
s->mode = CODES;
|
||||
case CODES:
|
||||
UPDATE
|
||||
if ((r = inflate_codes(s, z, r)) != Z_STREAM_END)
|
||||
return inflate_flush(s, z, r);
|
||||
r = Z_OK;
|
||||
inflate_codes_free(s->sub.decode.codes, z);
|
||||
LOAD
|
||||
Tracev((stderr, "inflate: codes end, %lu total out\n",
|
||||
z->total_out + (q >= s->read ? q - s->read :
|
||||
(s->end - s->read) + (q - s->window))));
|
||||
if (!s->last)
|
||||
{
|
||||
s->mode = TYPE;
|
||||
break;
|
||||
}
|
||||
s->mode = DRY;
|
||||
case DRY:
|
||||
FLUSH
|
||||
if (s->read != s->write)
|
||||
LEAVE
|
||||
s->mode = DONE;
|
||||
case DONE:
|
||||
r = Z_STREAM_END;
|
||||
LEAVE
|
||||
case BAD:
|
||||
r = Z_DATA_ERROR;
|
||||
LEAVE
|
||||
default:
|
||||
r = Z_STREAM_ERROR;
|
||||
LEAVE
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int inflate_blocks_free(s, z)
|
||||
inflate_blocks_statef *s;
|
||||
z_streamp z;
|
||||
{
|
||||
inflate_blocks_reset(s, z, Z_NULL);
|
||||
ZFREE(z, s->window);
|
||||
ZFREE(z, s->hufts);
|
||||
ZFREE(z, s);
|
||||
Tracev((stderr, "inflate: blocks freed\n"));
|
||||
return Z_OK;
|
||||
}
|
||||
|
||||
|
||||
void inflate_set_dictionary(s, d, n)
|
||||
inflate_blocks_statef *s;
|
||||
const Bytef *d;
|
||||
uInt n;
|
||||
{
|
||||
zmemcpy(s->window, d, n);
|
||||
s->read = s->write = s->window + n;
|
||||
}
|
||||
|
||||
|
||||
/* Returns true if inflate is currently at the end of a block generated
|
||||
* by Z_SYNC_FLUSH or Z_FULL_FLUSH.
|
||||
* IN assertion: s != Z_NULL
|
||||
*/
|
||||
int inflate_blocks_sync_point(s)
|
||||
inflate_blocks_statef *s;
|
||||
{
|
||||
return s->mode == LENS;
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/* infblock.h -- header to use infblock.c
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* WARNING: this file should *not* be used by applications. It is
|
||||
part of the implementation of the compression library and is
|
||||
subject to change. Applications should only use zlib.h.
|
||||
*/
|
||||
|
||||
struct inflate_blocks_state;
|
||||
typedef struct inflate_blocks_state FAR inflate_blocks_statef;
|
||||
|
||||
extern inflate_blocks_statef * inflate_blocks_new OF((
|
||||
z_streamp z,
|
||||
check_func c, /* check function */
|
||||
uInt w)); /* window size */
|
||||
|
||||
extern int inflate_blocks OF((
|
||||
inflate_blocks_statef *,
|
||||
z_streamp ,
|
||||
int)); /* initial return code */
|
||||
|
||||
extern void inflate_blocks_reset OF((
|
||||
inflate_blocks_statef *,
|
||||
z_streamp ,
|
||||
uLongf *)); /* check value on output */
|
||||
|
||||
extern int inflate_blocks_free OF((
|
||||
inflate_blocks_statef *,
|
||||
z_streamp));
|
||||
|
||||
extern void inflate_set_dictionary OF((
|
||||
inflate_blocks_statef *s,
|
||||
const Bytef *d, /* dictionary */
|
||||
uInt n)); /* dictionary length */
|
||||
|
||||
extern int inflate_blocks_sync_point OF((
|
||||
inflate_blocks_statef *s));
|
||||
BIN
Binary file not shown.
+251
@@ -0,0 +1,251 @@
|
||||
/* infcodes.c -- process literals and length/distance pairs
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
#include "zutil.h"
|
||||
#include "inftrees.h"
|
||||
#include "infblock.h"
|
||||
#include "infcodes.h"
|
||||
#include "infutil.h"
|
||||
#include "inffast.h"
|
||||
|
||||
/* simplify the use of the inflate_huft type with some defines */
|
||||
#define exop word.what.Exop
|
||||
#define bits word.what.Bits
|
||||
|
||||
typedef enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
|
||||
START, /* x: set up for LEN */
|
||||
LEN, /* i: get length/literal/eob next */
|
||||
LENEXT, /* i: getting length extra (have base) */
|
||||
DIST, /* i: get distance next */
|
||||
DISTEXT, /* i: getting distance extra */
|
||||
COPY, /* o: copying bytes in window, waiting for space */
|
||||
LIT, /* o: got literal, waiting for output space */
|
||||
WASH, /* o: got eob, possibly still output waiting */
|
||||
END, /* x: got eob and all data flushed */
|
||||
BADCODE} /* x: got error */
|
||||
inflate_codes_mode;
|
||||
|
||||
/* inflate codes private state */
|
||||
struct inflate_codes_state {
|
||||
|
||||
/* mode */
|
||||
inflate_codes_mode mode; /* current inflate_codes mode */
|
||||
|
||||
/* mode dependent information */
|
||||
uInt len;
|
||||
union {
|
||||
struct {
|
||||
inflate_huft *tree; /* pointer into tree */
|
||||
uInt need; /* bits needed */
|
||||
} code; /* if LEN or DIST, where in tree */
|
||||
uInt lit; /* if LIT, literal */
|
||||
struct {
|
||||
uInt get; /* bits to get for extra */
|
||||
uInt dist; /* distance back to copy from */
|
||||
} copy; /* if EXT or COPY, where and how much */
|
||||
} sub; /* submode */
|
||||
|
||||
/* mode independent information */
|
||||
Byte lbits; /* ltree bits decoded per branch */
|
||||
Byte dbits; /* dtree bits decoder per branch */
|
||||
inflate_huft *ltree; /* literal/length/eob tree */
|
||||
inflate_huft *dtree; /* distance tree */
|
||||
|
||||
};
|
||||
|
||||
|
||||
inflate_codes_statef *inflate_codes_new(bl, bd, tl, td, z)
|
||||
uInt bl, bd;
|
||||
inflate_huft *tl;
|
||||
inflate_huft *td; /* need separate declaration for Borland C++ */
|
||||
z_streamp z;
|
||||
{
|
||||
inflate_codes_statef *c;
|
||||
|
||||
if ((c = (inflate_codes_statef *)
|
||||
ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL)
|
||||
{
|
||||
c->mode = START;
|
||||
c->lbits = (Byte)bl;
|
||||
c->dbits = (Byte)bd;
|
||||
c->ltree = tl;
|
||||
c->dtree = td;
|
||||
Tracev((stderr, "inflate: codes new\n"));
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
int inflate_codes(s, z, r)
|
||||
inflate_blocks_statef *s;
|
||||
z_streamp z;
|
||||
int r;
|
||||
{
|
||||
uInt j; /* temporary storage */
|
||||
inflate_huft *t; /* temporary pointer */
|
||||
uInt e; /* extra bits or operation */
|
||||
uLong b; /* bit buffer */
|
||||
uInt k; /* bits in bit buffer */
|
||||
Bytef *p; /* input data pointer */
|
||||
uInt n; /* bytes available there */
|
||||
Bytef *q; /* output window write pointer */
|
||||
uInt m; /* bytes to end of window or read pointer */
|
||||
Bytef *f; /* pointer to copy strings from */
|
||||
inflate_codes_statef *c = s->sub.decode.codes; /* codes state */
|
||||
|
||||
/* copy input/output information to locals (UPDATE macro restores) */
|
||||
LOAD
|
||||
|
||||
/* process input and output based on current state */
|
||||
while (1) switch (c->mode)
|
||||
{ /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
|
||||
case START: /* x: set up for LEN */
|
||||
#ifndef SLOW
|
||||
if (m >= 258 && n >= 10)
|
||||
{
|
||||
UPDATE
|
||||
r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
|
||||
LOAD
|
||||
if (r != Z_OK)
|
||||
{
|
||||
c->mode = r == Z_STREAM_END ? WASH : BADCODE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
#endif /* !SLOW */
|
||||
c->sub.code.need = c->lbits;
|
||||
c->sub.code.tree = c->ltree;
|
||||
c->mode = LEN;
|
||||
case LEN: /* i: get length/literal/eob next */
|
||||
j = c->sub.code.need;
|
||||
NEEDBITS(j)
|
||||
t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
|
||||
DUMPBITS(t->bits)
|
||||
e = (uInt)(t->exop);
|
||||
if (e == 0) /* literal */
|
||||
{
|
||||
c->sub.lit = t->base;
|
||||
Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
|
||||
"inflate: literal '%c'\n" :
|
||||
"inflate: literal 0x%02x\n", t->base));
|
||||
c->mode = LIT;
|
||||
break;
|
||||
}
|
||||
if (e & 16) /* length */
|
||||
{
|
||||
c->sub.copy.get = e & 15;
|
||||
c->len = t->base;
|
||||
c->mode = LENEXT;
|
||||
break;
|
||||
}
|
||||
if ((e & 64) == 0) /* next table */
|
||||
{
|
||||
c->sub.code.need = e;
|
||||
c->sub.code.tree = t + t->base;
|
||||
break;
|
||||
}
|
||||
if (e & 32) /* end of block */
|
||||
{
|
||||
Tracevv((stderr, "inflate: end of block\n"));
|
||||
c->mode = WASH;
|
||||
break;
|
||||
}
|
||||
c->mode = BADCODE; /* invalid code */
|
||||
z->msg = (char*)"invalid literal/length code";
|
||||
r = Z_DATA_ERROR;
|
||||
LEAVE
|
||||
case LENEXT: /* i: getting length extra (have base) */
|
||||
j = c->sub.copy.get;
|
||||
NEEDBITS(j)
|
||||
c->len += (uInt)b & inflate_mask[j];
|
||||
DUMPBITS(j)
|
||||
c->sub.code.need = c->dbits;
|
||||
c->sub.code.tree = c->dtree;
|
||||
Tracevv((stderr, "inflate: length %u\n", c->len));
|
||||
c->mode = DIST;
|
||||
case DIST: /* i: get distance next */
|
||||
j = c->sub.code.need;
|
||||
NEEDBITS(j)
|
||||
t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
|
||||
DUMPBITS(t->bits)
|
||||
e = (uInt)(t->exop);
|
||||
if (e & 16) /* distance */
|
||||
{
|
||||
c->sub.copy.get = e & 15;
|
||||
c->sub.copy.dist = t->base;
|
||||
c->mode = DISTEXT;
|
||||
break;
|
||||
}
|
||||
if ((e & 64) == 0) /* next table */
|
||||
{
|
||||
c->sub.code.need = e;
|
||||
c->sub.code.tree = t + t->base;
|
||||
break;
|
||||
}
|
||||
c->mode = BADCODE; /* invalid code */
|
||||
z->msg = (char*)"invalid distance code";
|
||||
r = Z_DATA_ERROR;
|
||||
LEAVE
|
||||
case DISTEXT: /* i: getting distance extra */
|
||||
j = c->sub.copy.get;
|
||||
NEEDBITS(j)
|
||||
c->sub.copy.dist += (uInt)b & inflate_mask[j];
|
||||
DUMPBITS(j)
|
||||
Tracevv((stderr, "inflate: distance %u\n", c->sub.copy.dist));
|
||||
c->mode = COPY;
|
||||
case COPY: /* o: copying bytes in window, waiting for space */
|
||||
f = q - c->sub.copy.dist;
|
||||
while (f < s->window) /* modulo window size-"while" instead */
|
||||
f += s->end - s->window; /* of "if" handles invalid distances */
|
||||
while (c->len)
|
||||
{
|
||||
NEEDOUT
|
||||
OUTBYTE(*f++)
|
||||
if (f == s->end)
|
||||
f = s->window;
|
||||
c->len--;
|
||||
}
|
||||
c->mode = START;
|
||||
break;
|
||||
case LIT: /* o: got literal, waiting for output space */
|
||||
NEEDOUT
|
||||
OUTBYTE(c->sub.lit)
|
||||
c->mode = START;
|
||||
break;
|
||||
case WASH: /* o: got eob, possibly more output */
|
||||
if (k > 7) /* return unused byte, if any */
|
||||
{
|
||||
Assert(k < 16, "inflate_codes grabbed too many bytes")
|
||||
k -= 8;
|
||||
n++;
|
||||
p--; /* can always return one */
|
||||
}
|
||||
FLUSH
|
||||
if (s->read != s->write)
|
||||
LEAVE
|
||||
c->mode = END;
|
||||
case END:
|
||||
r = Z_STREAM_END;
|
||||
LEAVE
|
||||
case BADCODE: /* x: got error */
|
||||
r = Z_DATA_ERROR;
|
||||
LEAVE
|
||||
default:
|
||||
r = Z_STREAM_ERROR;
|
||||
LEAVE
|
||||
}
|
||||
#ifdef NEED_DUMMY_RETURN
|
||||
return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
void inflate_codes_free(c, z)
|
||||
inflate_codes_statef *c;
|
||||
z_streamp z;
|
||||
{
|
||||
ZFREE(z, c);
|
||||
Tracev((stderr, "inflate: codes free\n"));
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/* infcodes.h -- header to use infcodes.c
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* WARNING: this file should *not* be used by applications. It is
|
||||
part of the implementation of the compression library and is
|
||||
subject to change. Applications should only use zlib.h.
|
||||
*/
|
||||
|
||||
struct inflate_codes_state;
|
||||
typedef struct inflate_codes_state FAR inflate_codes_statef;
|
||||
|
||||
extern inflate_codes_statef *inflate_codes_new OF((
|
||||
uInt, uInt,
|
||||
inflate_huft *, inflate_huft *,
|
||||
z_streamp ));
|
||||
|
||||
extern int inflate_codes OF((
|
||||
inflate_blocks_statef *,
|
||||
z_streamp ,
|
||||
int));
|
||||
|
||||
extern void inflate_codes_free OF((
|
||||
inflate_codes_statef *,
|
||||
z_streamp ));
|
||||
|
||||
BIN
Binary file not shown.
+183
@@ -0,0 +1,183 @@
|
||||
/* inffast.c -- process literals and length/distance pairs fast
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
#include "zutil.h"
|
||||
#include "inftrees.h"
|
||||
#include "infblock.h"
|
||||
#include "infcodes.h"
|
||||
#include "infutil.h"
|
||||
#include "inffast.h"
|
||||
|
||||
struct inflate_codes_state {int dummy;}; /* for buggy compilers */
|
||||
|
||||
/* simplify the use of the inflate_huft type with some defines */
|
||||
#define exop word.what.Exop
|
||||
#define bits word.what.Bits
|
||||
|
||||
/* macros for bit input with no checking and for returning unused bytes */
|
||||
#define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}}
|
||||
#define UNGRAB {c=z->avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;}
|
||||
|
||||
/* Called with number of bytes left to write in window at least 258
|
||||
(the maximum string length) and number of input bytes available
|
||||
at least ten. The ten bytes are six bytes for the longest length/
|
||||
distance pair plus four bytes for overloading the bit buffer. */
|
||||
|
||||
int inflate_fast(bl, bd, tl, td, s, z)
|
||||
uInt bl, bd;
|
||||
inflate_huft *tl;
|
||||
inflate_huft *td; /* need separate declaration for Borland C++ */
|
||||
inflate_blocks_statef *s;
|
||||
z_streamp z;
|
||||
{
|
||||
inflate_huft *t; /* temporary pointer */
|
||||
uInt e; /* extra bits or operation */
|
||||
uLong b; /* bit buffer */
|
||||
uInt k; /* bits in bit buffer */
|
||||
Bytef *p; /* input data pointer */
|
||||
uInt n; /* bytes available there */
|
||||
Bytef *q; /* output window write pointer */
|
||||
uInt m; /* bytes to end of window or read pointer */
|
||||
uInt ml; /* mask for literal/length tree */
|
||||
uInt md; /* mask for distance tree */
|
||||
uInt c; /* bytes to copy */
|
||||
uInt d; /* distance back to copy from */
|
||||
Bytef *r; /* copy source pointer */
|
||||
|
||||
/* load input, output, bit values */
|
||||
LOAD
|
||||
|
||||
/* initialize masks */
|
||||
ml = inflate_mask[bl];
|
||||
md = inflate_mask[bd];
|
||||
|
||||
/* do until not enough input or output space for fast loop */
|
||||
do { /* assume called with m >= 258 && n >= 10 */
|
||||
/* get literal/length code */
|
||||
GRABBITS(20) /* max bits for literal/length code */
|
||||
if ((e = (t = tl + ((uInt)b & ml))->exop) == 0)
|
||||
{
|
||||
DUMPBITS(t->bits)
|
||||
Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
|
||||
"inflate: * literal '%c'\n" :
|
||||
"inflate: * literal 0x%02x\n", t->base));
|
||||
*q++ = (Byte)t->base;
|
||||
m--;
|
||||
continue;
|
||||
}
|
||||
do {
|
||||
DUMPBITS(t->bits)
|
||||
if (e & 16)
|
||||
{
|
||||
/* get extra bits for length */
|
||||
e &= 15;
|
||||
c = t->base + ((uInt)b & inflate_mask[e]);
|
||||
DUMPBITS(e)
|
||||
Tracevv((stderr, "inflate: * length %u\n", c));
|
||||
|
||||
/* decode distance base of block to copy */
|
||||
GRABBITS(15); /* max bits for distance code */
|
||||
e = (t = td + ((uInt)b & md))->exop;
|
||||
do {
|
||||
DUMPBITS(t->bits)
|
||||
if (e & 16)
|
||||
{
|
||||
/* get extra bits to add to distance base */
|
||||
e &= 15;
|
||||
GRABBITS(e) /* get extra bits (up to 13) */
|
||||
d = t->base + ((uInt)b & inflate_mask[e]);
|
||||
DUMPBITS(e)
|
||||
Tracevv((stderr, "inflate: * distance %u\n", d));
|
||||
|
||||
/* do the copy */
|
||||
m -= c;
|
||||
r = q - d;
|
||||
if (r < s->window) /* wrap if needed */
|
||||
{
|
||||
do {
|
||||
r += s->end - s->window; /* force pointer in window */
|
||||
} while (r < s->window); /* covers invalid distances */
|
||||
e = s->end - r;
|
||||
if (c > e)
|
||||
{
|
||||
c -= e; /* wrapped copy */
|
||||
do {
|
||||
*q++ = *r++;
|
||||
} while (--e);
|
||||
r = s->window;
|
||||
do {
|
||||
*q++ = *r++;
|
||||
} while (--c);
|
||||
}
|
||||
else /* normal copy */
|
||||
{
|
||||
*q++ = *r++; c--;
|
||||
*q++ = *r++; c--;
|
||||
do {
|
||||
*q++ = *r++;
|
||||
} while (--c);
|
||||
}
|
||||
}
|
||||
else /* normal copy */
|
||||
{
|
||||
*q++ = *r++; c--;
|
||||
*q++ = *r++; c--;
|
||||
do {
|
||||
*q++ = *r++;
|
||||
} while (--c);
|
||||
}
|
||||
break;
|
||||
}
|
||||
else if ((e & 64) == 0)
|
||||
{
|
||||
t += t->base;
|
||||
e = (t += ((uInt)b & inflate_mask[e]))->exop;
|
||||
}
|
||||
else
|
||||
{
|
||||
z->msg = (char*)"invalid distance code";
|
||||
UNGRAB
|
||||
UPDATE
|
||||
return Z_DATA_ERROR;
|
||||
}
|
||||
} while (1);
|
||||
break;
|
||||
}
|
||||
if ((e & 64) == 0)
|
||||
{
|
||||
t += t->base;
|
||||
if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0)
|
||||
{
|
||||
DUMPBITS(t->bits)
|
||||
Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
|
||||
"inflate: * literal '%c'\n" :
|
||||
"inflate: * literal 0x%02x\n", t->base));
|
||||
*q++ = (Byte)t->base;
|
||||
m--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if (e & 32)
|
||||
{
|
||||
Tracevv((stderr, "inflate: * end of block\n"));
|
||||
UNGRAB
|
||||
UPDATE
|
||||
return Z_STREAM_END;
|
||||
}
|
||||
else
|
||||
{
|
||||
z->msg = (char*)"invalid literal/length code";
|
||||
UNGRAB
|
||||
UPDATE
|
||||
return Z_DATA_ERROR;
|
||||
}
|
||||
} while (1);
|
||||
} while (m >= 258 && n >= 10);
|
||||
|
||||
/* not enough input or output--restore pointers and return */
|
||||
UNGRAB
|
||||
UPDATE
|
||||
return Z_OK;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/* inffast.h -- header to use inffast.c
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* WARNING: this file should *not* be used by applications. It is
|
||||
part of the implementation of the compression library and is
|
||||
subject to change. Applications should only use zlib.h.
|
||||
*/
|
||||
|
||||
extern int inflate_fast OF((
|
||||
uInt,
|
||||
uInt,
|
||||
inflate_huft *,
|
||||
inflate_huft *,
|
||||
inflate_blocks_statef *,
|
||||
z_streamp ));
|
||||
BIN
Binary file not shown.
+151
@@ -0,0 +1,151 @@
|
||||
/* inffixed.h -- table for decoding fixed codes
|
||||
* Generated automatically by the maketree.c program
|
||||
*/
|
||||
|
||||
/* WARNING: this file should *not* be used by applications. It is
|
||||
part of the implementation of the compression library and is
|
||||
subject to change. Applications should only use zlib.h.
|
||||
*/
|
||||
|
||||
local uInt fixed_bl = 9;
|
||||
local uInt fixed_bd = 5;
|
||||
local inflate_huft fixed_tl[] = {
|
||||
{{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
|
||||
{{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192},
|
||||
{{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160},
|
||||
{{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224},
|
||||
{{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144},
|
||||
{{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208},
|
||||
{{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176},
|
||||
{{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240},
|
||||
{{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
|
||||
{{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200},
|
||||
{{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168},
|
||||
{{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232},
|
||||
{{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152},
|
||||
{{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216},
|
||||
{{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184},
|
||||
{{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248},
|
||||
{{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
|
||||
{{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196},
|
||||
{{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164},
|
||||
{{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228},
|
||||
{{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148},
|
||||
{{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212},
|
||||
{{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180},
|
||||
{{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244},
|
||||
{{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
|
||||
{{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204},
|
||||
{{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172},
|
||||
{{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236},
|
||||
{{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156},
|
||||
{{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220},
|
||||
{{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188},
|
||||
{{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252},
|
||||
{{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
|
||||
{{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194},
|
||||
{{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162},
|
||||
{{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226},
|
||||
{{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146},
|
||||
{{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210},
|
||||
{{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178},
|
||||
{{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242},
|
||||
{{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
|
||||
{{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202},
|
||||
{{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170},
|
||||
{{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234},
|
||||
{{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154},
|
||||
{{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218},
|
||||
{{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186},
|
||||
{{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250},
|
||||
{{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
|
||||
{{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198},
|
||||
{{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166},
|
||||
{{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230},
|
||||
{{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150},
|
||||
{{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214},
|
||||
{{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182},
|
||||
{{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246},
|
||||
{{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
|
||||
{{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206},
|
||||
{{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174},
|
||||
{{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238},
|
||||
{{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158},
|
||||
{{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222},
|
||||
{{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190},
|
||||
{{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254},
|
||||
{{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
|
||||
{{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193},
|
||||
{{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161},
|
||||
{{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225},
|
||||
{{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145},
|
||||
{{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209},
|
||||
{{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177},
|
||||
{{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241},
|
||||
{{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
|
||||
{{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201},
|
||||
{{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169},
|
||||
{{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233},
|
||||
{{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153},
|
||||
{{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217},
|
||||
{{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185},
|
||||
{{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249},
|
||||
{{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
|
||||
{{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197},
|
||||
{{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165},
|
||||
{{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229},
|
||||
{{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149},
|
||||
{{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213},
|
||||
{{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181},
|
||||
{{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245},
|
||||
{{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
|
||||
{{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205},
|
||||
{{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173},
|
||||
{{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237},
|
||||
{{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157},
|
||||
{{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221},
|
||||
{{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189},
|
||||
{{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253},
|
||||
{{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
|
||||
{{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195},
|
||||
{{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163},
|
||||
{{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227},
|
||||
{{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147},
|
||||
{{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211},
|
||||
{{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179},
|
||||
{{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243},
|
||||
{{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
|
||||
{{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203},
|
||||
{{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171},
|
||||
{{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235},
|
||||
{{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155},
|
||||
{{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219},
|
||||
{{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187},
|
||||
{{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251},
|
||||
{{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
|
||||
{{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199},
|
||||
{{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167},
|
||||
{{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231},
|
||||
{{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151},
|
||||
{{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215},
|
||||
{{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183},
|
||||
{{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247},
|
||||
{{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
|
||||
{{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207},
|
||||
{{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175},
|
||||
{{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239},
|
||||
{{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159},
|
||||
{{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223},
|
||||
{{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191},
|
||||
{{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255}
|
||||
};
|
||||
local inflate_huft fixed_td[] = {
|
||||
{{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097},
|
||||
{{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385},
|
||||
{{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193},
|
||||
{{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577},
|
||||
{{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145},
|
||||
{{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577},
|
||||
{{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289},
|
||||
{{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577}
|
||||
};
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
/* inflate.c -- zlib interface to inflate modules
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
#include "zutil.h"
|
||||
#include "infblock.h"
|
||||
|
||||
struct inflate_blocks_state {int dummy;}; /* for buggy compilers */
|
||||
|
||||
typedef enum {
|
||||
METHOD, /* waiting for method byte */
|
||||
FLAG, /* waiting for flag byte */
|
||||
DICT4, /* four dictionary check bytes to go */
|
||||
DICT3, /* three dictionary check bytes to go */
|
||||
DICT2, /* two dictionary check bytes to go */
|
||||
DICT1, /* one dictionary check byte to go */
|
||||
DICT0, /* waiting for inflateSetDictionary */
|
||||
BLOCKS, /* decompressing blocks */
|
||||
CHECK4, /* four check bytes to go */
|
||||
CHECK3, /* three check bytes to go */
|
||||
CHECK2, /* two check bytes to go */
|
||||
CHECK1, /* one check byte to go */
|
||||
DONE, /* finished check, done */
|
||||
BAD} /* got an error--stay here */
|
||||
inflate_mode;
|
||||
|
||||
/* inflate private state */
|
||||
struct internal_state {
|
||||
|
||||
/* mode */
|
||||
inflate_mode mode; /* current inflate mode */
|
||||
|
||||
/* mode dependent information */
|
||||
union {
|
||||
uInt method; /* if FLAGS, method byte */
|
||||
struct {
|
||||
uLong was; /* computed check value */
|
||||
uLong need; /* stream check value */
|
||||
} check; /* if CHECK, check values to compare */
|
||||
uInt marker; /* if BAD, inflateSync's marker bytes count */
|
||||
} sub; /* submode */
|
||||
|
||||
/* mode independent information */
|
||||
int nowrap; /* flag for no wrapper */
|
||||
uInt wbits; /* log2(window size) (8..15, defaults to 15) */
|
||||
inflate_blocks_statef
|
||||
*blocks; /* current inflate_blocks state */
|
||||
|
||||
};
|
||||
|
||||
|
||||
int ZEXPORT inflateReset(z)
|
||||
z_streamp z;
|
||||
{
|
||||
if (z == Z_NULL || z->state == Z_NULL)
|
||||
return Z_STREAM_ERROR;
|
||||
z->total_in = z->total_out = 0;
|
||||
z->msg = Z_NULL;
|
||||
z->state->mode = z->state->nowrap ? BLOCKS : METHOD;
|
||||
inflate_blocks_reset(z->state->blocks, z, Z_NULL);
|
||||
Tracev((stderr, "inflate: reset\n"));
|
||||
return Z_OK;
|
||||
}
|
||||
|
||||
|
||||
int ZEXPORT inflateEnd(z)
|
||||
z_streamp z;
|
||||
{
|
||||
if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
|
||||
return Z_STREAM_ERROR;
|
||||
if (z->state->blocks != Z_NULL)
|
||||
inflate_blocks_free(z->state->blocks, z);
|
||||
ZFREE(z, z->state);
|
||||
z->state = Z_NULL;
|
||||
Tracev((stderr, "inflate: end\n"));
|
||||
return Z_OK;
|
||||
}
|
||||
|
||||
|
||||
int ZEXPORT inflateInit2_(z, w, version, stream_size)
|
||||
z_streamp z;
|
||||
int w;
|
||||
const char *version;
|
||||
int stream_size;
|
||||
{
|
||||
if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
|
||||
stream_size != sizeof(z_stream))
|
||||
return Z_VERSION_ERROR;
|
||||
|
||||
/* initialize state */
|
||||
if (z == Z_NULL)
|
||||
return Z_STREAM_ERROR;
|
||||
z->msg = Z_NULL;
|
||||
if (z->zalloc == Z_NULL)
|
||||
{
|
||||
z->zalloc = zcalloc;
|
||||
z->opaque = (voidpf)0;
|
||||
}
|
||||
if (z->zfree == Z_NULL) z->zfree = zcfree;
|
||||
if ((z->state = (struct internal_state FAR *)
|
||||
ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
|
||||
return Z_MEM_ERROR;
|
||||
z->state->blocks = Z_NULL;
|
||||
|
||||
/* handle undocumented nowrap option (no zlib header or check) */
|
||||
z->state->nowrap = 0;
|
||||
if (w < 0)
|
||||
{
|
||||
w = - w;
|
||||
z->state->nowrap = 1;
|
||||
}
|
||||
|
||||
/* set window size */
|
||||
if (w < 8 || w > 15)
|
||||
{
|
||||
inflateEnd(z);
|
||||
return Z_STREAM_ERROR;
|
||||
}
|
||||
z->state->wbits = (uInt)w;
|
||||
|
||||
/* create inflate_blocks state */
|
||||
if ((z->state->blocks =
|
||||
inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w))
|
||||
== Z_NULL)
|
||||
{
|
||||
inflateEnd(z);
|
||||
return Z_MEM_ERROR;
|
||||
}
|
||||
Tracev((stderr, "inflate: allocated\n"));
|
||||
|
||||
/* reset state */
|
||||
inflateReset(z);
|
||||
return Z_OK;
|
||||
}
|
||||
|
||||
|
||||
int ZEXPORT inflateInit_(z, version, stream_size)
|
||||
z_streamp z;
|
||||
const char *version;
|
||||
int stream_size;
|
||||
{
|
||||
return inflateInit2_(z, DEF_WBITS, version, stream_size);
|
||||
}
|
||||
|
||||
|
||||
#define NEEDBYTE {if(z->avail_in==0)return r;r=f;}
|
||||
#define NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++)
|
||||
|
||||
int ZEXPORT inflate(z, f)
|
||||
z_streamp z;
|
||||
int f;
|
||||
{
|
||||
int r;
|
||||
uInt b;
|
||||
|
||||
if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL)
|
||||
return Z_STREAM_ERROR;
|
||||
f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
|
||||
r = Z_BUF_ERROR;
|
||||
while (1) switch (z->state->mode)
|
||||
{
|
||||
case METHOD:
|
||||
NEEDBYTE
|
||||
if (((z->state->sub.method = NEXTBYTE) & 0xf) != Z_DEFLATED)
|
||||
{
|
||||
z->state->mode = BAD;
|
||||
z->msg = (char*)"unknown compression method";
|
||||
z->state->sub.marker = 5; /* can't try inflateSync */
|
||||
break;
|
||||
}
|
||||
if ((z->state->sub.method >> 4) + 8 > z->state->wbits)
|
||||
{
|
||||
z->state->mode = BAD;
|
||||
z->msg = (char*)"invalid window size";
|
||||
z->state->sub.marker = 5; /* can't try inflateSync */
|
||||
break;
|
||||
}
|
||||
z->state->mode = FLAG;
|
||||
case FLAG:
|
||||
NEEDBYTE
|
||||
b = NEXTBYTE;
|
||||
if (((z->state->sub.method << 8) + b) % 31)
|
||||
{
|
||||
z->state->mode = BAD;
|
||||
z->msg = (char*)"incorrect header check";
|
||||
z->state->sub.marker = 5; /* can't try inflateSync */
|
||||
break;
|
||||
}
|
||||
Tracev((stderr, "inflate: zlib header ok\n"));
|
||||
if (!(b & PRESET_DICT))
|
||||
{
|
||||
z->state->mode = BLOCKS;
|
||||
break;
|
||||
}
|
||||
z->state->mode = DICT4;
|
||||
case DICT4:
|
||||
NEEDBYTE
|
||||
z->state->sub.check.need = (uLong)NEXTBYTE << 24;
|
||||
z->state->mode = DICT3;
|
||||
case DICT3:
|
||||
NEEDBYTE
|
||||
z->state->sub.check.need += (uLong)NEXTBYTE << 16;
|
||||
z->state->mode = DICT2;
|
||||
case DICT2:
|
||||
NEEDBYTE
|
||||
z->state->sub.check.need += (uLong)NEXTBYTE << 8;
|
||||
z->state->mode = DICT1;
|
||||
case DICT1:
|
||||
NEEDBYTE
|
||||
z->state->sub.check.need += (uLong)NEXTBYTE;
|
||||
z->adler = z->state->sub.check.need;
|
||||
z->state->mode = DICT0;
|
||||
return Z_NEED_DICT;
|
||||
case DICT0:
|
||||
z->state->mode = BAD;
|
||||
z->msg = (char*)"need dictionary";
|
||||
z->state->sub.marker = 0; /* can try inflateSync */
|
||||
return Z_STREAM_ERROR;
|
||||
case BLOCKS:
|
||||
r = inflate_blocks(z->state->blocks, z, r);
|
||||
if (r == Z_DATA_ERROR)
|
||||
{
|
||||
z->state->mode = BAD;
|
||||
z->state->sub.marker = 0; /* can try inflateSync */
|
||||
break;
|
||||
}
|
||||
if (r == Z_OK)
|
||||
r = f;
|
||||
if (r != Z_STREAM_END)
|
||||
return r;
|
||||
r = f;
|
||||
inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was);
|
||||
if (z->state->nowrap)
|
||||
{
|
||||
z->state->mode = DONE;
|
||||
break;
|
||||
}
|
||||
z->state->mode = CHECK4;
|
||||
case CHECK4:
|
||||
NEEDBYTE
|
||||
z->state->sub.check.need = (uLong)NEXTBYTE << 24;
|
||||
z->state->mode = CHECK3;
|
||||
case CHECK3:
|
||||
NEEDBYTE
|
||||
z->state->sub.check.need += (uLong)NEXTBYTE << 16;
|
||||
z->state->mode = CHECK2;
|
||||
case CHECK2:
|
||||
NEEDBYTE
|
||||
z->state->sub.check.need += (uLong)NEXTBYTE << 8;
|
||||
z->state->mode = CHECK1;
|
||||
case CHECK1:
|
||||
NEEDBYTE
|
||||
z->state->sub.check.need += (uLong)NEXTBYTE;
|
||||
|
||||
if (z->state->sub.check.was != z->state->sub.check.need)
|
||||
{
|
||||
z->state->mode = BAD;
|
||||
z->msg = (char*)"incorrect data check";
|
||||
z->state->sub.marker = 5; /* can't try inflateSync */
|
||||
break;
|
||||
}
|
||||
Tracev((stderr, "inflate: zlib check ok\n"));
|
||||
z->state->mode = DONE;
|
||||
case DONE:
|
||||
return Z_STREAM_END;
|
||||
case BAD:
|
||||
return Z_DATA_ERROR;
|
||||
default:
|
||||
return Z_STREAM_ERROR;
|
||||
}
|
||||
#ifdef NEED_DUMMY_RETURN
|
||||
return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
int ZEXPORT inflateSetDictionary(z, dictionary, dictLength)
|
||||
z_streamp z;
|
||||
const Bytef *dictionary;
|
||||
uInt dictLength;
|
||||
{
|
||||
uInt length = dictLength;
|
||||
|
||||
if (z == Z_NULL || z->state == Z_NULL || z->state->mode != DICT0)
|
||||
return Z_STREAM_ERROR;
|
||||
|
||||
if (adler32(1L, dictionary, dictLength) != z->adler) return Z_DATA_ERROR;
|
||||
z->adler = 1L;
|
||||
|
||||
if (length >= ((uInt)1<<z->state->wbits))
|
||||
{
|
||||
length = (1<<z->state->wbits)-1;
|
||||
dictionary += dictLength - length;
|
||||
}
|
||||
inflate_set_dictionary(z->state->blocks, dictionary, length);
|
||||
z->state->mode = BLOCKS;
|
||||
return Z_OK;
|
||||
}
|
||||
|
||||
|
||||
int ZEXPORT inflateSync(z)
|
||||
z_streamp z;
|
||||
{
|
||||
uInt n; /* number of bytes to look at */
|
||||
Bytef *p; /* pointer to bytes */
|
||||
uInt m; /* number of marker bytes found in a row */
|
||||
uLong r, w; /* temporaries to save total_in and total_out */
|
||||
|
||||
/* set up */
|
||||
if (z == Z_NULL || z->state == Z_NULL)
|
||||
return Z_STREAM_ERROR;
|
||||
if (z->state->mode != BAD)
|
||||
{
|
||||
z->state->mode = BAD;
|
||||
z->state->sub.marker = 0;
|
||||
}
|
||||
if ((n = z->avail_in) == 0)
|
||||
return Z_BUF_ERROR;
|
||||
p = z->next_in;
|
||||
m = z->state->sub.marker;
|
||||
|
||||
/* search */
|
||||
while (n && m < 4)
|
||||
{
|
||||
static const Byte mark[4] = {0, 0, 0xff, 0xff};
|
||||
if (*p == mark[m])
|
||||
m++;
|
||||
else if (*p)
|
||||
m = 0;
|
||||
else
|
||||
m = 4 - m;
|
||||
p++, n--;
|
||||
}
|
||||
|
||||
/* restore */
|
||||
z->total_in += p - z->next_in;
|
||||
z->next_in = p;
|
||||
z->avail_in = n;
|
||||
z->state->sub.marker = m;
|
||||
|
||||
/* return no joy or set up to restart on a new block */
|
||||
if (m != 4)
|
||||
return Z_DATA_ERROR;
|
||||
r = z->total_in; w = z->total_out;
|
||||
inflateReset(z);
|
||||
z->total_in = r; z->total_out = w;
|
||||
z->state->mode = BLOCKS;
|
||||
return Z_OK;
|
||||
}
|
||||
|
||||
|
||||
/* Returns true if inflate is currently at the end of a block generated
|
||||
* by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
|
||||
* implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
|
||||
* but removes the length bytes of the resulting empty stored block. When
|
||||
* decompressing, PPP checks that at the end of input packet, inflate is
|
||||
* waiting for these length bytes.
|
||||
*/
|
||||
int ZEXPORT inflateSyncPoint(z)
|
||||
z_streamp z;
|
||||
{
|
||||
if (z == Z_NULL || z->state == Z_NULL || z->state->blocks == Z_NULL)
|
||||
return Z_STREAM_ERROR;
|
||||
return inflate_blocks_sync_point(z->state->blocks);
|
||||
}
|
||||
BIN
Binary file not shown.
+454
@@ -0,0 +1,454 @@
|
||||
/* inftrees.c -- generate Huffman trees for efficient decoding
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
#include "zutil.h"
|
||||
#include "inftrees.h"
|
||||
|
||||
#if !defined(BUILDFIXED) && !defined(STDC)
|
||||
# define BUILDFIXED /* non ANSI compilers may not accept inffixed.h */
|
||||
#endif
|
||||
|
||||
const char inflate_copyright[] =
|
||||
" inflate 1.1.4 Copyright 1995-2002 Mark Adler ";
|
||||
/*
|
||||
If you use the zlib library in a product, an acknowledgment is welcome
|
||||
in the documentation of your product. If for some reason you cannot
|
||||
include such an acknowledgment, I would appreciate that you keep this
|
||||
copyright string in the executable of your product.
|
||||
*/
|
||||
struct internal_state {int dummy;}; /* for buggy compilers */
|
||||
|
||||
/* simplify the use of the inflate_huft type with some defines */
|
||||
#define exop word.what.Exop
|
||||
#define bits word.what.Bits
|
||||
|
||||
|
||||
local int huft_build OF((
|
||||
uIntf *, /* code lengths in bits */
|
||||
uInt, /* number of codes */
|
||||
uInt, /* number of "simple" codes */
|
||||
const uIntf *, /* list of base values for non-simple codes */
|
||||
const uIntf *, /* list of extra bits for non-simple codes */
|
||||
inflate_huft * FAR*,/* result: starting table */
|
||||
uIntf *, /* maximum lookup bits (returns actual) */
|
||||
inflate_huft *, /* space for trees */
|
||||
uInt *, /* hufts used in space */
|
||||
uIntf * )); /* space for values */
|
||||
|
||||
/* Tables for deflate from PKZIP's appnote.txt. */
|
||||
local const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
|
||||
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
|
||||
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
|
||||
/* see note #13 above about 258 */
|
||||
local const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
|
||||
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */
|
||||
local const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
|
||||
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
|
||||
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
|
||||
8193, 12289, 16385, 24577};
|
||||
local const uInt cpdext[30] = { /* Extra bits for distance codes */
|
||||
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
|
||||
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
|
||||
12, 12, 13, 13};
|
||||
|
||||
/*
|
||||
Huffman code decoding is performed using a multi-level table lookup.
|
||||
The fastest way to decode is to simply build a lookup table whose
|
||||
size is determined by the longest code. However, the time it takes
|
||||
to build this table can also be a factor if the data being decoded
|
||||
is not very long. The most common codes are necessarily the
|
||||
shortest codes, so those codes dominate the decoding time, and hence
|
||||
the speed. The idea is you can have a shorter table that decodes the
|
||||
shorter, more probable codes, and then point to subsidiary tables for
|
||||
the longer codes. The time it costs to decode the longer codes is
|
||||
then traded against the time it takes to make longer tables.
|
||||
|
||||
This results of this trade are in the variables lbits and dbits
|
||||
below. lbits is the number of bits the first level table for literal/
|
||||
length codes can decode in one step, and dbits is the same thing for
|
||||
the distance codes. Subsequent tables are also less than or equal to
|
||||
those sizes. These values may be adjusted either when all of the
|
||||
codes are shorter than that, in which case the longest code length in
|
||||
bits is used, or when the shortest code is *longer* than the requested
|
||||
table size, in which case the length of the shortest code in bits is
|
||||
used.
|
||||
|
||||
There are two different values for the two tables, since they code a
|
||||
different number of possibilities each. The literal/length table
|
||||
codes 286 possible values, or in a flat code, a little over eight
|
||||
bits. The distance table codes 30 possible values, or a little less
|
||||
than five bits, flat. The optimum values for speed end up being
|
||||
about one bit more than those, so lbits is 8+1 and dbits is 5+1.
|
||||
The optimum values may differ though from machine to machine, and
|
||||
possibly even between compilers. Your mileage may vary.
|
||||
*/
|
||||
|
||||
|
||||
/* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
|
||||
#define BMAX 15 /* maximum bit length of any code */
|
||||
|
||||
local int huft_build(b, n, s, d, e, t, m, hp, hn, v)
|
||||
uIntf *b; /* code lengths in bits (all assumed <= BMAX) */
|
||||
uInt n; /* number of codes (assumed <= 288) */
|
||||
uInt s; /* number of simple-valued codes (0..s-1) */
|
||||
const uIntf *d; /* list of base values for non-simple codes */
|
||||
const uIntf *e; /* list of extra bits for non-simple codes */
|
||||
inflate_huft * FAR *t; /* result: starting table */
|
||||
uIntf *m; /* maximum lookup bits, returns actual */
|
||||
inflate_huft *hp; /* space for trees */
|
||||
uInt *hn; /* hufts used in space */
|
||||
uIntf *v; /* working area: values in order of bit length */
|
||||
/* Given a list of code lengths and a maximum table size, make a set of
|
||||
tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
|
||||
if the given code set is incomplete (the tables are still built in this
|
||||
case), or Z_DATA_ERROR if the input is invalid. */
|
||||
{
|
||||
|
||||
uInt a; /* counter for codes of length k */
|
||||
uInt c[BMAX+1]; /* bit length count table */
|
||||
uInt f; /* i repeats in table every f entries */
|
||||
int g; /* maximum code length */
|
||||
int h; /* table level */
|
||||
register uInt i; /* counter, current code */
|
||||
register uInt j; /* counter */
|
||||
register int k; /* number of bits in current code */
|
||||
int l; /* bits per table (returned in m) */
|
||||
uInt mask; /* (1 << w) - 1, to avoid cc -O bug on HP */
|
||||
register uIntf *p; /* pointer into c[], b[], or v[] */
|
||||
inflate_huft *q; /* points to current table */
|
||||
struct inflate_huft_s r; /* table entry for structure assignment */
|
||||
inflate_huft *u[BMAX]; /* table stack */
|
||||
register int w; /* bits before this table == (l * h) */
|
||||
uInt x[BMAX+1]; /* bit offsets, then code stack */
|
||||
uIntf *xp; /* pointer into x */
|
||||
int y; /* number of dummy codes added */
|
||||
uInt z; /* number of entries in current table */
|
||||
|
||||
|
||||
/* Generate counts for each bit length */
|
||||
p = c;
|
||||
#define C0 *p++ = 0;
|
||||
#define C2 C0 C0 C0 C0
|
||||
#define C4 C2 C2 C2 C2
|
||||
C4 /* clear c[]--assume BMAX+1 is 16 */
|
||||
p = b; i = n;
|
||||
do {
|
||||
c[*p++]++; /* assume all entries <= BMAX */
|
||||
} while (--i);
|
||||
if (c[0] == n) /* null input--all zero length codes */
|
||||
{
|
||||
*t = (inflate_huft *)Z_NULL;
|
||||
*m = 0;
|
||||
return Z_OK;
|
||||
}
|
||||
|
||||
|
||||
/* Find minimum and maximum length, bound *m by those */
|
||||
l = *m;
|
||||
for (j = 1; j <= BMAX; j++)
|
||||
if (c[j])
|
||||
break;
|
||||
k = j; /* minimum code length */
|
||||
if ((uInt)l < j)
|
||||
l = j;
|
||||
for (i = BMAX; i; i--)
|
||||
if (c[i])
|
||||
break;
|
||||
g = i; /* maximum code length */
|
||||
if ((uInt)l > i)
|
||||
l = i;
|
||||
*m = l;
|
||||
|
||||
|
||||
/* Adjust last length count to fill out codes, if needed */
|
||||
for (y = 1 << j; j < i; j++, y <<= 1)
|
||||
if ((y -= c[j]) < 0)
|
||||
return Z_DATA_ERROR;
|
||||
if ((y -= c[i]) < 0)
|
||||
return Z_DATA_ERROR;
|
||||
c[i] += y;
|
||||
|
||||
|
||||
/* Generate starting offsets into the value table for each length */
|
||||
x[1] = j = 0;
|
||||
p = c + 1; xp = x + 2;
|
||||
while (--i) { /* note that i == g from above */
|
||||
*xp++ = (j += *p++);
|
||||
}
|
||||
|
||||
|
||||
/* Make a table of values in order of bit lengths */
|
||||
p = b; i = 0;
|
||||
do {
|
||||
if ((j = *p++) != 0)
|
||||
v[x[j]++] = i;
|
||||
} while (++i < n);
|
||||
n = x[g]; /* set n to length of v */
|
||||
|
||||
|
||||
/* Generate the Huffman codes and for each, make the table entries */
|
||||
x[0] = i = 0; /* first Huffman code is zero */
|
||||
p = v; /* grab values in bit order */
|
||||
h = -1; /* no tables yet--level -1 */
|
||||
w = -l; /* bits decoded == (l * h) */
|
||||
u[0] = (inflate_huft *)Z_NULL; /* just to keep compilers happy */
|
||||
q = (inflate_huft *)Z_NULL; /* ditto */
|
||||
z = 0; /* ditto */
|
||||
|
||||
/* go through the bit lengths (k already is bits in shortest code) */
|
||||
for (; k <= g; k++)
|
||||
{
|
||||
a = c[k];
|
||||
while (a--)
|
||||
{
|
||||
/* here i is the Huffman code of length k bits for value *p */
|
||||
/* make tables up to required level */
|
||||
while (k > w + l)
|
||||
{
|
||||
h++;
|
||||
w += l; /* previous table always l bits */
|
||||
|
||||
/* compute minimum size table less than or equal to l bits */
|
||||
z = g - w;
|
||||
z = z > (uInt)l ? (uInt)l : z; /* table size upper limit */
|
||||
if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */
|
||||
{ /* too few codes for k-w bit table */
|
||||
f -= a + 1; /* deduct codes from patterns left */
|
||||
xp = c + k;
|
||||
if (j < z)
|
||||
while (++j < z) /* try smaller tables up to z bits */
|
||||
{
|
||||
if ((f <<= 1) <= *++xp)
|
||||
break; /* enough codes to use up j bits */
|
||||
f -= *xp; /* else deduct codes from patterns */
|
||||
}
|
||||
}
|
||||
z = 1 << j; /* table entries for j-bit table */
|
||||
|
||||
/* allocate new table */
|
||||
if (*hn + z > MANY) /* (note: doesn't matter for fixed) */
|
||||
return Z_DATA_ERROR; /* overflow of MANY */
|
||||
u[h] = q = hp + *hn;
|
||||
*hn += z;
|
||||
|
||||
/* connect to last table, if there is one */
|
||||
if (h)
|
||||
{
|
||||
x[h] = i; /* save pattern for backing up */
|
||||
r.bits = (Byte)l; /* bits to dump before this table */
|
||||
r.exop = (Byte)j; /* bits in this table */
|
||||
j = i >> (w - l);
|
||||
r.base = (uInt)(q - u[h-1] - j); /* offset to this table */
|
||||
u[h-1][j] = r; /* connect to last table */
|
||||
}
|
||||
else
|
||||
*t = q; /* first table is returned result */
|
||||
}
|
||||
|
||||
/* set up table entry in r */
|
||||
r.bits = (Byte)(k - w);
|
||||
if (p >= v + n)
|
||||
r.exop = 128 + 64; /* out of values--invalid code */
|
||||
else if (*p < s)
|
||||
{
|
||||
r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); /* 256 is end-of-block */
|
||||
r.base = *p++; /* simple code is just the value */
|
||||
}
|
||||
else
|
||||
{
|
||||
r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
|
||||
r.base = d[*p++ - s];
|
||||
}
|
||||
|
||||
/* fill code-like entries with r */
|
||||
f = 1 << (k - w);
|
||||
for (j = i >> w; j < z; j += f)
|
||||
q[j] = r;
|
||||
|
||||
/* backwards increment the k-bit code i */
|
||||
for (j = 1 << (k - 1); i & j; j >>= 1)
|
||||
i ^= j;
|
||||
i ^= j;
|
||||
|
||||
/* backup over finished tables */
|
||||
mask = (1 << w) - 1; /* needed on HP, cc -O bug */
|
||||
while ((i & mask) != x[h])
|
||||
{
|
||||
h--; /* don't need to update q */
|
||||
w -= l;
|
||||
mask = (1 << w) - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Return Z_BUF_ERROR if we were given an incomplete table */
|
||||
return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
|
||||
}
|
||||
|
||||
|
||||
int inflate_trees_bits(c, bb, tb, hp, z)
|
||||
uIntf *c; /* 19 code lengths */
|
||||
uIntf *bb; /* bits tree desired/actual depth */
|
||||
inflate_huft * FAR *tb; /* bits tree result */
|
||||
inflate_huft *hp; /* space for trees */
|
||||
z_streamp z; /* for messages */
|
||||
{
|
||||
int r;
|
||||
uInt hn = 0; /* hufts used in space */
|
||||
uIntf *v; /* work area for huft_build */
|
||||
|
||||
if ((v = (uIntf*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL)
|
||||
return Z_MEM_ERROR;
|
||||
r = huft_build(c, 19, 19, (uIntf*)Z_NULL, (uIntf*)Z_NULL,
|
||||
tb, bb, hp, &hn, v);
|
||||
if (r == Z_DATA_ERROR)
|
||||
z->msg = (char*)"oversubscribed dynamic bit lengths tree";
|
||||
else if (r == Z_BUF_ERROR || *bb == 0)
|
||||
{
|
||||
z->msg = (char*)"incomplete dynamic bit lengths tree";
|
||||
r = Z_DATA_ERROR;
|
||||
}
|
||||
ZFREE(z, v);
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
int inflate_trees_dynamic(nl, nd, c, bl, bd, tl, td, hp, z)
|
||||
uInt nl; /* number of literal/length codes */
|
||||
uInt nd; /* number of distance codes */
|
||||
uIntf *c; /* that many (total) code lengths */
|
||||
uIntf *bl; /* literal desired/actual bit depth */
|
||||
uIntf *bd; /* distance desired/actual bit depth */
|
||||
inflate_huft * FAR *tl; /* literal/length tree result */
|
||||
inflate_huft * FAR *td; /* distance tree result */
|
||||
inflate_huft *hp; /* space for trees */
|
||||
z_streamp z; /* for messages */
|
||||
{
|
||||
int r;
|
||||
uInt hn = 0; /* hufts used in space */
|
||||
uIntf *v; /* work area for huft_build */
|
||||
|
||||
/* allocate work area */
|
||||
if ((v = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
|
||||
return Z_MEM_ERROR;
|
||||
|
||||
/* build literal/length tree */
|
||||
r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v);
|
||||
if (r != Z_OK || *bl == 0)
|
||||
{
|
||||
if (r == Z_DATA_ERROR)
|
||||
z->msg = (char*)"oversubscribed literal/length tree";
|
||||
else if (r != Z_MEM_ERROR)
|
||||
{
|
||||
z->msg = (char*)"incomplete literal/length tree";
|
||||
r = Z_DATA_ERROR;
|
||||
}
|
||||
ZFREE(z, v);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* build distance tree */
|
||||
r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v);
|
||||
if (r != Z_OK || (*bd == 0 && nl > 257))
|
||||
{
|
||||
if (r == Z_DATA_ERROR)
|
||||
z->msg = (char*)"oversubscribed distance tree";
|
||||
else if (r == Z_BUF_ERROR) {
|
||||
#ifdef PKZIP_BUG_WORKAROUND
|
||||
r = Z_OK;
|
||||
}
|
||||
#else
|
||||
z->msg = (char*)"incomplete distance tree";
|
||||
r = Z_DATA_ERROR;
|
||||
}
|
||||
else if (r != Z_MEM_ERROR)
|
||||
{
|
||||
z->msg = (char*)"empty distance tree with lengths";
|
||||
r = Z_DATA_ERROR;
|
||||
}
|
||||
ZFREE(z, v);
|
||||
return r;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* done */
|
||||
ZFREE(z, v);
|
||||
return Z_OK;
|
||||
}
|
||||
|
||||
|
||||
/* build fixed tables only once--keep them here */
|
||||
#ifdef BUILDFIXED
|
||||
local int fixed_built = 0;
|
||||
#define FIXEDH 544 /* number of hufts used by fixed tables */
|
||||
local inflate_huft fixed_mem[FIXEDH];
|
||||
local uInt fixed_bl;
|
||||
local uInt fixed_bd;
|
||||
local inflate_huft *fixed_tl;
|
||||
local inflate_huft *fixed_td;
|
||||
#else
|
||||
#include "inffixed.h"
|
||||
#endif
|
||||
|
||||
|
||||
int inflate_trees_fixed(bl, bd, tl, td, z)
|
||||
uIntf *bl; /* literal desired/actual bit depth */
|
||||
uIntf *bd; /* distance desired/actual bit depth */
|
||||
inflate_huft * FAR *tl; /* literal/length tree result */
|
||||
inflate_huft * FAR *td; /* distance tree result */
|
||||
z_streamp z; /* for memory allocation */
|
||||
{
|
||||
#ifdef BUILDFIXED
|
||||
/* build fixed tables if not already */
|
||||
if (!fixed_built)
|
||||
{
|
||||
int k; /* temporary variable */
|
||||
uInt f = 0; /* number of hufts used in fixed_mem */
|
||||
uIntf *c; /* length list for huft_build */
|
||||
uIntf *v; /* work area for huft_build */
|
||||
|
||||
/* allocate memory */
|
||||
if ((c = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
|
||||
return Z_MEM_ERROR;
|
||||
if ((v = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
|
||||
{
|
||||
ZFREE(z, c);
|
||||
return Z_MEM_ERROR;
|
||||
}
|
||||
|
||||
/* literal table */
|
||||
for (k = 0; k < 144; k++)
|
||||
c[k] = 8;
|
||||
for (; k < 256; k++)
|
||||
c[k] = 9;
|
||||
for (; k < 280; k++)
|
||||
c[k] = 7;
|
||||
for (; k < 288; k++)
|
||||
c[k] = 8;
|
||||
fixed_bl = 9;
|
||||
huft_build(c, 288, 257, cplens, cplext, &fixed_tl, &fixed_bl,
|
||||
fixed_mem, &f, v);
|
||||
|
||||
/* distance table */
|
||||
for (k = 0; k < 30; k++)
|
||||
c[k] = 5;
|
||||
fixed_bd = 5;
|
||||
huft_build(c, 30, 0, cpdist, cpdext, &fixed_td, &fixed_bd,
|
||||
fixed_mem, &f, v);
|
||||
|
||||
/* done */
|
||||
ZFREE(z, v);
|
||||
ZFREE(z, c);
|
||||
fixed_built = 1;
|
||||
}
|
||||
#endif
|
||||
*bl = fixed_bl;
|
||||
*bd = fixed_bd;
|
||||
*tl = fixed_tl;
|
||||
*td = fixed_td;
|
||||
return Z_OK;
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
/* inftrees.h -- header to use inftrees.c
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* WARNING: this file should *not* be used by applications. It is
|
||||
part of the implementation of the compression library and is
|
||||
subject to change. Applications should only use zlib.h.
|
||||
*/
|
||||
|
||||
/* Huffman code lookup table entry--this entry is four bytes for machines
|
||||
that have 16-bit pointers (e.g. PC's in the small or medium model). */
|
||||
|
||||
typedef struct inflate_huft_s FAR inflate_huft;
|
||||
|
||||
struct inflate_huft_s {
|
||||
union {
|
||||
struct {
|
||||
Byte Exop; /* number of extra bits or operation */
|
||||
Byte Bits; /* number of bits in this code or subcode */
|
||||
} what;
|
||||
uInt pad; /* pad structure to a power of 2 (4 bytes for */
|
||||
} word; /* 16-bit, 8 bytes for 32-bit int's) */
|
||||
uInt base; /* literal, length base, distance base,
|
||||
or table offset */
|
||||
};
|
||||
|
||||
/* Maximum size of dynamic tree. The maximum found in a long but non-
|
||||
exhaustive search was 1004 huft structures (850 for length/literals
|
||||
and 154 for distances, the latter actually the result of an
|
||||
exhaustive search). The actual maximum is not known, but the
|
||||
value below is more than safe. */
|
||||
#define MANY 1440
|
||||
|
||||
extern int inflate_trees_bits OF((
|
||||
uIntf *, /* 19 code lengths */
|
||||
uIntf *, /* bits tree desired/actual depth */
|
||||
inflate_huft * FAR *, /* bits tree result */
|
||||
inflate_huft *, /* space for trees */
|
||||
z_streamp)); /* for messages */
|
||||
|
||||
extern int inflate_trees_dynamic OF((
|
||||
uInt, /* number of literal/length codes */
|
||||
uInt, /* number of distance codes */
|
||||
uIntf *, /* that many (total) code lengths */
|
||||
uIntf *, /* literal desired/actual bit depth */
|
||||
uIntf *, /* distance desired/actual bit depth */
|
||||
inflate_huft * FAR *, /* literal/length tree result */
|
||||
inflate_huft * FAR *, /* distance tree result */
|
||||
inflate_huft *, /* space for trees */
|
||||
z_streamp)); /* for messages */
|
||||
|
||||
extern int inflate_trees_fixed OF((
|
||||
uIntf *, /* literal desired/actual bit depth */
|
||||
uIntf *, /* distance desired/actual bit depth */
|
||||
inflate_huft * FAR *, /* literal/length tree result */
|
||||
inflate_huft * FAR *, /* distance tree result */
|
||||
z_streamp)); /* for memory allocation */
|
||||
BIN
Binary file not shown.
+87
@@ -0,0 +1,87 @@
|
||||
/* inflate_util.c -- data and routines common to blocks and codes
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
#include "zutil.h"
|
||||
#include "infblock.h"
|
||||
#include "inftrees.h"
|
||||
#include "infcodes.h"
|
||||
#include "infutil.h"
|
||||
|
||||
struct inflate_codes_state {int dummy;}; /* for buggy compilers */
|
||||
|
||||
/* And'ing with mask[n] masks the lower n bits */
|
||||
uInt inflate_mask[17] = {
|
||||
0x0000,
|
||||
0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
|
||||
0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
|
||||
};
|
||||
|
||||
|
||||
/* copy as much as possible from the sliding window to the output area */
|
||||
int inflate_flush(s, z, r)
|
||||
inflate_blocks_statef *s;
|
||||
z_streamp z;
|
||||
int r;
|
||||
{
|
||||
uInt n;
|
||||
Bytef *p;
|
||||
Bytef *q;
|
||||
|
||||
/* local copies of source and destination pointers */
|
||||
p = z->next_out;
|
||||
q = s->read;
|
||||
|
||||
/* compute number of bytes to copy as far as end of window */
|
||||
n = (uInt)((q <= s->write ? s->write : s->end) - q);
|
||||
if (n > z->avail_out) n = z->avail_out;
|
||||
if (n && r == Z_BUF_ERROR) r = Z_OK;
|
||||
|
||||
/* update counters */
|
||||
z->avail_out -= n;
|
||||
z->total_out += n;
|
||||
|
||||
/* update check information */
|
||||
if (s->checkfn != Z_NULL)
|
||||
z->adler = s->check = (*s->checkfn)(s->check, q, n);
|
||||
|
||||
/* copy as far as end of window */
|
||||
zmemcpy(p, q, n);
|
||||
p += n;
|
||||
q += n;
|
||||
|
||||
/* see if more to copy at beginning of window */
|
||||
if (q == s->end)
|
||||
{
|
||||
/* wrap pointers */
|
||||
q = s->window;
|
||||
if (s->write == s->end)
|
||||
s->write = s->window;
|
||||
|
||||
/* compute bytes to copy */
|
||||
n = (uInt)(s->write - q);
|
||||
if (n > z->avail_out) n = z->avail_out;
|
||||
if (n && r == Z_BUF_ERROR) r = Z_OK;
|
||||
|
||||
/* update counters */
|
||||
z->avail_out -= n;
|
||||
z->total_out += n;
|
||||
|
||||
/* update check information */
|
||||
if (s->checkfn != Z_NULL)
|
||||
z->adler = s->check = (*s->checkfn)(s->check, q, n);
|
||||
|
||||
/* copy */
|
||||
zmemcpy(p, q, n);
|
||||
p += n;
|
||||
q += n;
|
||||
}
|
||||
|
||||
/* update pointers */
|
||||
z->next_out = p;
|
||||
s->read = q;
|
||||
|
||||
/* done */
|
||||
return r;
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
/* infutil.h -- types and macros common to blocks and codes
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* WARNING: this file should *not* be used by applications. It is
|
||||
part of the implementation of the compression library and is
|
||||
subject to change. Applications should only use zlib.h.
|
||||
*/
|
||||
|
||||
#ifndef _INFUTIL_H
|
||||
#define _INFUTIL_H
|
||||
|
||||
typedef enum {
|
||||
TYPE, /* get type bits (3, including end bit) */
|
||||
LENS, /* get lengths for stored */
|
||||
STORED, /* processing stored block */
|
||||
TABLE, /* get table lengths */
|
||||
BTREE, /* get bit lengths tree for a dynamic block */
|
||||
DTREE, /* get length, distance trees for a dynamic block */
|
||||
CODES, /* processing fixed or dynamic block */
|
||||
DRY, /* output remaining window bytes */
|
||||
DONE, /* finished last block, done */
|
||||
BAD} /* got a data error--stuck here */
|
||||
inflate_block_mode;
|
||||
|
||||
/* inflate blocks semi-private state */
|
||||
struct inflate_blocks_state {
|
||||
|
||||
/* mode */
|
||||
inflate_block_mode mode; /* current inflate_block mode */
|
||||
|
||||
/* mode dependent information */
|
||||
union {
|
||||
uInt left; /* if STORED, bytes left to copy */
|
||||
struct {
|
||||
uInt table; /* table lengths (14 bits) */
|
||||
uInt index; /* index into blens (or border) */
|
||||
uIntf *blens; /* bit lengths of codes */
|
||||
uInt bb; /* bit length tree depth */
|
||||
inflate_huft *tb; /* bit length decoding tree */
|
||||
} trees; /* if DTREE, decoding info for trees */
|
||||
struct {
|
||||
inflate_codes_statef
|
||||
*codes;
|
||||
} decode; /* if CODES, current state */
|
||||
} sub; /* submode */
|
||||
uInt last; /* true if this block is the last block */
|
||||
|
||||
/* mode independent information */
|
||||
uInt bitk; /* bits in bit buffer */
|
||||
uLong bitb; /* bit buffer */
|
||||
inflate_huft *hufts; /* single malloc for tree space */
|
||||
Bytef *window; /* sliding window */
|
||||
Bytef *end; /* one byte after sliding window */
|
||||
Bytef *read; /* window read pointer */
|
||||
Bytef *write; /* window write pointer */
|
||||
check_func checkfn; /* check function */
|
||||
uLong check; /* check on output */
|
||||
|
||||
};
|
||||
|
||||
|
||||
/* defines for inflate input/output */
|
||||
/* update pointers and return */
|
||||
#define UPDBITS {s->bitb=b;s->bitk=k;}
|
||||
#define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;}
|
||||
#define UPDOUT {s->write=q;}
|
||||
#define UPDATE {UPDBITS UPDIN UPDOUT}
|
||||
#define LEAVE {UPDATE return inflate_flush(s,z,r);}
|
||||
/* get bytes and bits */
|
||||
#define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
|
||||
#define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
|
||||
#define NEXTBYTE (n--,*p++)
|
||||
#define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
|
||||
#define DUMPBITS(j) {b>>=(j);k-=(j);}
|
||||
/* output bytes */
|
||||
#define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)
|
||||
#define LOADOUT {q=s->write;m=(uInt)WAVAIL;}
|
||||
#define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}
|
||||
#define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}
|
||||
#define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}
|
||||
#define OUTBYTE(a) {*q++=(Byte)(a);m--;}
|
||||
/* load local pointers */
|
||||
#define LOAD {LOADIN LOADOUT}
|
||||
|
||||
/* masks for lower bits (size given to avoid silly warnings with Visual C++) */
|
||||
extern uInt inflate_mask[17];
|
||||
|
||||
/* copy as much as possible from the sliding window to the output area */
|
||||
extern int inflate_flush OF((
|
||||
inflate_blocks_statef *,
|
||||
z_streamp ,
|
||||
int));
|
||||
|
||||
struct internal_state {int dummy;}; /* for buggy compilers */
|
||||
|
||||
#endif
|
||||
BIN
Binary file not shown.
+51
@@ -0,0 +1,51 @@
|
||||
/* maketree.c -- make inffixed.h table for decoding fixed codes
|
||||
* Copyright (C) 1995-2002 Mark Adler
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* WARNING: this file should *not* be used by applications. It is
|
||||
part of the implementation of the compression library and is
|
||||
subject to change. Applications should only use zlib.h.
|
||||
*/
|
||||
|
||||
/* This program is included in the distribution for completeness.
|
||||
You do not need to compile or run this program since inffixed.h
|
||||
is already included in the distribution. To use this program
|
||||
you need to compile zlib with BUILDFIXED defined and then compile
|
||||
and link this program with the zlib library. Then the output of
|
||||
this program can be piped to inffixed.h. */
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "zutil.h"
|
||||
#include "inftrees.h"
|
||||
|
||||
/* simplify the use of the inflate_huft type with some defines */
|
||||
#define exop word.what.Exop
|
||||
#define bits word.what.Bits
|
||||
|
||||
/* generate initialization table for an inflate_huft structure array */
|
||||
void maketree(uInt b, inflate_huft *t)
|
||||
{
|
||||
int i, e;
|
||||
|
||||
i = 0;
|
||||
while (1)
|
||||
{
|
||||
e = t[i].exop;
|
||||
if (e && (e & (16+64)) == 0) /* table pointer */
|
||||
{
|
||||
fprintf(stderr, "maketree: cannot initialize sub-tables!\n");
|
||||
exit(1);
|
||||
}
|
||||
if (i % 4 == 0)
|
||||
printf("\n ");
|
||||
printf(" {{{%u,%u}},%u}", t[i].exop, t[i].bits, t[i].base);
|
||||
if (++i == (1<<b))
|
||||
break;
|
||||
putchar(',');
|
||||
}
|
||||
puts("");
|
||||
}
|
||||
|
||||
|
||||
BIN
Binary file not shown.
+1214
File diff suppressed because it is too large
Load Diff
+128
@@ -0,0 +1,128 @@
|
||||
/* header created automatically with -DGEN_TREES_H */
|
||||
|
||||
local const ct_data static_ltree[L_CODES+2] = {
|
||||
{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
|
||||
{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
|
||||
{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
|
||||
{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
|
||||
{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
|
||||
{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
|
||||
{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
|
||||
{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
|
||||
{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
|
||||
{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
|
||||
{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
|
||||
{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
|
||||
{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
|
||||
{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
|
||||
{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
|
||||
{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
|
||||
{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
|
||||
{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
|
||||
{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
|
||||
{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
|
||||
{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
|
||||
{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
|
||||
{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
|
||||
{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
|
||||
{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
|
||||
{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
|
||||
{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
|
||||
{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
|
||||
{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
|
||||
{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
|
||||
{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
|
||||
{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
|
||||
{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
|
||||
{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
|
||||
{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
|
||||
{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
|
||||
{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
|
||||
{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
|
||||
{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
|
||||
{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
|
||||
{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
|
||||
{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
|
||||
{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
|
||||
{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
|
||||
{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
|
||||
{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
|
||||
{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
|
||||
{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
|
||||
{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
|
||||
{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
|
||||
{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
|
||||
{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
|
||||
{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
|
||||
{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
|
||||
{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
|
||||
{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
|
||||
{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
|
||||
{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
|
||||
};
|
||||
|
||||
local const ct_data static_dtree[D_CODES] = {
|
||||
{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
|
||||
{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
|
||||
{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
|
||||
{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
|
||||
{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
|
||||
{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
|
||||
};
|
||||
|
||||
const uch _dist_code[DIST_CODE_LEN] = {
|
||||
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
|
||||
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
|
||||
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
|
||||
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
|
||||
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
|
||||
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
|
||||
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
|
||||
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
|
||||
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
|
||||
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
|
||||
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
|
||||
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
|
||||
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
|
||||
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
|
||||
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
|
||||
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
|
||||
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
|
||||
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
|
||||
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
|
||||
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
|
||||
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
|
||||
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
|
||||
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
|
||||
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
|
||||
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
|
||||
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
|
||||
};
|
||||
|
||||
const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
|
||||
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
|
||||
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
|
||||
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
|
||||
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
|
||||
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
|
||||
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
|
||||
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
|
||||
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
|
||||
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
|
||||
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
|
||||
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
|
||||
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
|
||||
};
|
||||
|
||||
local const int base_length[LENGTH_CODES] = {
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
|
||||
64, 80, 96, 112, 128, 160, 192, 224, 0
|
||||
};
|
||||
|
||||
local const int base_dist[D_CODES] = {
|
||||
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
|
||||
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
|
||||
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
|
||||
};
|
||||
|
||||
BIN
Binary file not shown.
+58
@@ -0,0 +1,58 @@
|
||||
/* uncompr.c -- decompress a memory buffer
|
||||
* Copyright (C) 1995-2002 Jean-loup Gailly.
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* @(#) $Id$ */
|
||||
|
||||
#include "zlib.h"
|
||||
|
||||
/* ===========================================================================
|
||||
Decompresses the source buffer into the destination buffer. sourceLen is
|
||||
the byte length of the source buffer. Upon entry, destLen is the total
|
||||
size of the destination buffer, which must be large enough to hold the
|
||||
entire uncompressed data. (The size of the uncompressed data must have
|
||||
been saved previously by the compressor and transmitted to the decompressor
|
||||
by some mechanism outside the scope of this compression library.)
|
||||
Upon exit, destLen is the actual size of the compressed buffer.
|
||||
This function can be used to decompress a whole file at once if the
|
||||
input file is mmap'ed.
|
||||
|
||||
uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
|
||||
enough memory, Z_BUF_ERROR if there was not enough room in the output
|
||||
buffer, or Z_DATA_ERROR if the input data was corrupted.
|
||||
*/
|
||||
int ZEXPORT uncompress (dest, destLen, source, sourceLen)
|
||||
Bytef *dest;
|
||||
uLongf *destLen;
|
||||
const Bytef *source;
|
||||
uLong sourceLen;
|
||||
{
|
||||
z_stream stream;
|
||||
int err;
|
||||
|
||||
stream.next_in = (Bytef*)source;
|
||||
stream.avail_in = (uInt)sourceLen;
|
||||
/* Check for source > 64K on 16-bit machine: */
|
||||
if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
|
||||
|
||||
stream.next_out = dest;
|
||||
stream.avail_out = (uInt)*destLen;
|
||||
if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
|
||||
|
||||
stream.zalloc = (alloc_func)0;
|
||||
stream.zfree = (free_func)0;
|
||||
|
||||
err = inflateInit(&stream);
|
||||
if (err != Z_OK) return err;
|
||||
|
||||
err = inflate(&stream, Z_FINISH);
|
||||
if (err != Z_STREAM_END) {
|
||||
inflateEnd(&stream);
|
||||
return err == Z_OK ? Z_BUF_ERROR : err;
|
||||
}
|
||||
*destLen = stream.total_out;
|
||||
|
||||
err = inflateEnd(&stream);
|
||||
return err;
|
||||
}
|
||||
BIN
Binary file not shown.
+279
@@ -0,0 +1,279 @@
|
||||
/* zconf.h -- configuration of the zlib compression library
|
||||
* Copyright (C) 1995-2002 Jean-loup Gailly.
|
||||
* For conditions of distribution and use, see copyright notice in zlib.h
|
||||
*/
|
||||
|
||||
/* @(#) $Id$ */
|
||||
|
||||
#ifndef _ZCONF_H
|
||||
#define _ZCONF_H
|
||||
|
||||
/*
|
||||
* If you *really* need a unique prefix for all types and library functions,
|
||||
* compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
|
||||
*/
|
||||
#ifdef Z_PREFIX
|
||||
# define deflateInit_ z_deflateInit_
|
||||
# define deflate z_deflate
|
||||
# define deflateEnd z_deflateEnd
|
||||
# define inflateInit_ z_inflateInit_
|
||||
# define inflate z_inflate
|
||||
# define inflateEnd z_inflateEnd
|
||||
# define deflateInit2_ z_deflateInit2_
|
||||
# define deflateSetDictionary z_deflateSetDictionary
|
||||
# define deflateCopy z_deflateCopy
|
||||
# define deflateReset z_deflateReset
|
||||
# define deflateParams z_deflateParams
|
||||
# define inflateInit2_ z_inflateInit2_
|
||||
# define inflateSetDictionary z_inflateSetDictionary
|
||||
# define inflateSync z_inflateSync
|
||||
# define inflateSyncPoint z_inflateSyncPoint
|
||||
# define inflateReset z_inflateReset
|
||||
# define compress z_compress
|
||||
# define compress2 z_compress2
|
||||
# define uncompress z_uncompress
|
||||
# define adler32 z_adler32
|
||||
# define crc32 z_crc32
|
||||
# define get_crc_table z_get_crc_table
|
||||
|
||||
# define Byte z_Byte
|
||||
# define uInt z_uInt
|
||||
# define uLong z_uLong
|
||||
# define Bytef z_Bytef
|
||||
# define charf z_charf
|
||||
# define intf z_intf
|
||||
# define uIntf z_uIntf
|
||||
# define uLongf z_uLongf
|
||||
# define voidpf z_voidpf
|
||||
# define voidp z_voidp
|
||||
#endif
|
||||
|
||||
#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32)
|
||||
# define WIN32
|
||||
#endif
|
||||
#if defined(__GNUC__) || defined(WIN32) || defined(__386__) || defined(i386)
|
||||
# ifndef __32BIT__
|
||||
# define __32BIT__
|
||||
# endif
|
||||
#endif
|
||||
#if defined(__MSDOS__) && !defined(MSDOS)
|
||||
# define MSDOS
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Compile with -DMAXSEG_64K if the alloc function cannot allocate more
|
||||
* than 64k bytes at a time (needed on systems with 16-bit int).
|
||||
*/
|
||||
#if defined(MSDOS) && !defined(__32BIT__)
|
||||
# define MAXSEG_64K
|
||||
#endif
|
||||
#ifdef MSDOS
|
||||
# define UNALIGNED_OK
|
||||
#endif
|
||||
|
||||
#if (defined(MSDOS) || defined(_WINDOWS) || defined(WIN32)) && !defined(STDC)
|
||||
# define STDC
|
||||
#endif
|
||||
#if defined(__STDC__) || defined(__cplusplus) || defined(__OS2__)
|
||||
# ifndef STDC
|
||||
# define STDC
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifndef STDC
|
||||
# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
|
||||
# define const
|
||||
# endif
|
||||
#endif
|
||||
|
||||
/* Some Mac compilers merge all .h files incorrectly: */
|
||||
#if defined(__MWERKS__) || defined(applec) ||defined(THINK_C) ||defined(__SC__)
|
||||
# define NO_DUMMY_DECL
|
||||
#endif
|
||||
|
||||
/* Old Borland C incorrectly complains about missing returns: */
|
||||
#if defined(__BORLANDC__) && (__BORLANDC__ < 0x500)
|
||||
# define NEED_DUMMY_RETURN
|
||||
#endif
|
||||
|
||||
|
||||
/* Maximum value for memLevel in deflateInit2 */
|
||||
#ifndef MAX_MEM_LEVEL
|
||||
# ifdef MAXSEG_64K
|
||||
# define MAX_MEM_LEVEL 8
|
||||
# else
|
||||
# define MAX_MEM_LEVEL 9
|
||||
# endif
|
||||
#endif
|
||||
|
||||
/* Maximum value for windowBits in deflateInit2 and inflateInit2.
|
||||
* WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
|
||||
* created by gzip. (Files created by minigzip can still be extracted by
|
||||
* gzip.)
|
||||
*/
|
||||
#ifndef MAX_WBITS
|
||||
# define MAX_WBITS 15 /* 32K LZ77 window */
|
||||
#endif
|
||||
|
||||
/* The memory requirements for deflate are (in bytes):
|
||||
(1 << (windowBits+2)) + (1 << (memLevel+9))
|
||||
that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
|
||||
plus a few kilobytes for small objects. For example, if you want to reduce
|
||||
the default memory requirements from 256K to 128K, compile with
|
||||
make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
|
||||
Of course this will generally degrade compression (there's no free lunch).
|
||||
|
||||
The memory requirements for inflate are (in bytes) 1 << windowBits
|
||||
that is, 32K for windowBits=15 (default value) plus a few kilobytes
|
||||
for small objects.
|
||||
*/
|
||||
|
||||
/* Type declarations */
|
||||
|
||||
#ifndef OF /* function prototypes */
|
||||
# ifdef STDC
|
||||
# define OF(args) args
|
||||
# else
|
||||
# define OF(args) ()
|
||||
# endif
|
||||
#endif
|
||||
|
||||
/* The following definitions for FAR are needed only for MSDOS mixed
|
||||
* model programming (small or medium model with some far allocations).
|
||||
* This was tested only with MSC; for other MSDOS compilers you may have
|
||||
* to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
|
||||
* just define FAR to be empty.
|
||||
*/
|
||||
#if (defined(M_I86SM) || defined(M_I86MM)) && !defined(__32BIT__)
|
||||
/* MSC small or medium model */
|
||||
# define SMALL_MEDIUM
|
||||
# ifdef _MSC_VER
|
||||
# define FAR _far
|
||||
# else
|
||||
# define FAR far
|
||||
# endif
|
||||
#endif
|
||||
#if defined(__BORLANDC__) && (defined(__SMALL__) || defined(__MEDIUM__))
|
||||
# ifndef __32BIT__
|
||||
# define SMALL_MEDIUM
|
||||
# define FAR _far
|
||||
# endif
|
||||
#endif
|
||||
|
||||
/* Compile with -DZLIB_DLL for Windows DLL support */
|
||||
#if defined(ZLIB_DLL)
|
||||
# if defined(_WINDOWS) || defined(WINDOWS)
|
||||
# ifdef FAR
|
||||
# undef FAR
|
||||
# endif
|
||||
# include <windows.h>
|
||||
# define ZEXPORT WINAPI
|
||||
# ifdef WIN32
|
||||
# define ZEXPORTVA WINAPIV
|
||||
# else
|
||||
# define ZEXPORTVA FAR _cdecl _export
|
||||
# endif
|
||||
# endif
|
||||
# if defined (__BORLANDC__)
|
||||
# if (__BORLANDC__ >= 0x0500) && defined (WIN32)
|
||||
# include <windows.h>
|
||||
# define ZEXPORT __declspec(dllexport) WINAPI
|
||||
# define ZEXPORTRVA __declspec(dllexport) WINAPIV
|
||||
# else
|
||||
# if defined (_Windows) && defined (__DLL__)
|
||||
# define ZEXPORT _export
|
||||
# define ZEXPORTVA _export
|
||||
# endif
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if defined (__BEOS__)
|
||||
# if defined (ZLIB_DLL)
|
||||
# define ZEXTERN extern __declspec(dllexport)
|
||||
# else
|
||||
# define ZEXTERN extern __declspec(dllimport)
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifndef ZEXPORT
|
||||
# define ZEXPORT
|
||||
#endif
|
||||
#ifndef ZEXPORTVA
|
||||
# define ZEXPORTVA
|
||||
#endif
|
||||
#ifndef ZEXTERN
|
||||
# define ZEXTERN extern
|
||||
#endif
|
||||
|
||||
#ifndef FAR
|
||||
# define FAR
|
||||
#endif
|
||||
|
||||
#if !defined(MACOS) && !defined(TARGET_OS_MAC)
|
||||
typedef unsigned char Byte; /* 8 bits */
|
||||
#endif
|
||||
typedef unsigned int uInt; /* 16 bits or more */
|
||||
typedef unsigned long uLong; /* 32 bits or more */
|
||||
|
||||
#ifdef SMALL_MEDIUM
|
||||
/* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
|
||||
# define Bytef Byte FAR
|
||||
#else
|
||||
typedef Byte FAR Bytef;
|
||||
#endif
|
||||
typedef char FAR charf;
|
||||
typedef int FAR intf;
|
||||
typedef uInt FAR uIntf;
|
||||
typedef uLong FAR uLongf;
|
||||
|
||||
#ifdef STDC
|
||||
typedef void FAR *voidpf;
|
||||
typedef void *voidp;
|
||||
#else
|
||||
typedef Byte FAR *voidpf;
|
||||
typedef Byte *voidp;
|
||||
#endif
|
||||
|
||||
#ifdef HAVE_UNISTD_H
|
||||
# include <sys/types.h> /* for off_t */
|
||||
# include <unistd.h> /* for SEEK_* and off_t */
|
||||
# define z_off_t off_t
|
||||
#endif
|
||||
#ifndef SEEK_SET
|
||||
# define SEEK_SET 0 /* Seek from beginning of file. */
|
||||
# define SEEK_CUR 1 /* Seek from current position. */
|
||||
# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
|
||||
#endif
|
||||
#ifndef z_off_t
|
||||
# define z_off_t long
|
||||
#endif
|
||||
|
||||
/* MVS linker does not support external names larger than 8 bytes */
|
||||
#if defined(__MVS__)
|
||||
# pragma map(deflateInit_,"DEIN")
|
||||
# pragma map(deflateInit2_,"DEIN2")
|
||||
# pragma map(deflateEnd,"DEEND")
|
||||
# pragma map(inflateInit_,"ININ")
|
||||
# pragma map(inflateInit2_,"ININ2")
|
||||
# pragma map(inflateEnd,"INEND")
|
||||
# pragma map(inflateSync,"INSY")
|
||||
# pragma map(inflateSetDictionary,"INSEDI")
|
||||
# pragma map(inflate_blocks,"INBL")
|
||||
# pragma map(inflate_blocks_new,"INBLNE")
|
||||
# pragma map(inflate_blocks_free,"INBLFR")
|
||||
# pragma map(inflate_blocks_reset,"INBLRE")
|
||||
# pragma map(inflate_codes_free,"INCOFR")
|
||||
# pragma map(inflate_codes,"INCO")
|
||||
# pragma map(inflate_fast,"INFA")
|
||||
# pragma map(inflate_flush,"INFLU")
|
||||
# pragma map(inflate_mask,"INMA")
|
||||
# pragma map(inflate_set_dictionary,"INSEDI2")
|
||||
# pragma map(inflate_copyright,"INCOPY")
|
||||
# pragma map(inflate_trees_bits,"INTRBI")
|
||||
# pragma map(inflate_trees_dynamic,"INTRDY")
|
||||
# pragma map(inflate_trees_fixed,"INTRFI")
|
||||
# pragma map(inflate_trees_free,"INTRFR")
|
||||
#endif
|
||||
|
||||
#endif /* _ZCONF_H */
|
||||
+893
@@ -0,0 +1,893 @@
|
||||
/* zlib.h -- interface of the 'zlib' general purpose compression library
|
||||
version 1.1.4, March 11th, 2002
|
||||
|
||||
Copyright (C) 1995-2002 Jean-loup Gailly and Mark Adler
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
|
||||
Jean-loup Gailly Mark Adler
|
||||
[email protected] [email protected]
|
||||
|
||||
|
||||
The data format used by the zlib library is described by RFCs (Request for
|
||||
Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
|
||||
(zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
|
||||
*/
|
||||
|
||||
#ifndef _ZLIB_H
|
||||
#define _ZLIB_H
|
||||
|
||||
#include "zconf.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define ZLIB_VERSION "1.1.4"
|
||||
|
||||
/*
|
||||
The 'zlib' compression library provides in-memory compression and
|
||||
decompression functions, including integrity checks of the uncompressed
|
||||
data. This version of the library supports only one compression method
|
||||
(deflation) but other algorithms will be added later and will have the same
|
||||
stream interface.
|
||||
|
||||
Compression can be done in a single step if the buffers are large
|
||||
enough (for example if an input file is mmap'ed), or can be done by
|
||||
repeated calls of the compression function. In the latter case, the
|
||||
application must provide more input and/or consume the output
|
||||
(providing more output space) before each call.
|
||||
|
||||
The library also supports reading and writing files in gzip (.gz) format
|
||||
with an interface similar to that of stdio.
|
||||
|
||||
The library does not install any signal handler. The decoder checks
|
||||
the consistency of the compressed data, so the library should never
|
||||
crash even in case of corrupted input.
|
||||
*/
|
||||
|
||||
typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
|
||||
typedef void (*free_func) OF((voidpf opaque, voidpf address));
|
||||
|
||||
struct internal_state;
|
||||
|
||||
typedef struct z_stream_s {
|
||||
Bytef *next_in; /* next input byte */
|
||||
uInt avail_in; /* number of bytes available at next_in */
|
||||
uLong total_in; /* total nb of input bytes read so far */
|
||||
|
||||
Bytef *next_out; /* next output byte should be put there */
|
||||
uInt avail_out; /* remaining free space at next_out */
|
||||
uLong total_out; /* total nb of bytes output so far */
|
||||
|
||||
char *msg; /* last error message, NULL if no error */
|
||||
struct internal_state FAR *state; /* not visible by applications */
|
||||
|
||||
alloc_func zalloc; /* used to allocate the internal state */
|
||||
free_func zfree; /* used to free the internal state */
|
||||
voidpf opaque; /* private data object passed to zalloc and zfree */
|
||||
|
||||
int data_type; /* best guess about the data type: ascii or binary */
|
||||
uLong adler; /* adler32 value of the uncompressed data */
|
||||
uLong reserved; /* reserved for future use */
|
||||
} z_stream;
|
||||
|
||||
typedef z_stream FAR *z_streamp;
|
||||
|
||||
/*
|
||||
The application must update next_in and avail_in when avail_in has
|
||||
dropped to zero. It must update next_out and avail_out when avail_out
|
||||
has dropped to zero. The application must initialize zalloc, zfree and
|
||||
opaque before calling the init function. All other fields are set by the
|
||||
compression library and must not be updated by the application.
|
||||
|
||||
The opaque value provided by the application will be passed as the first
|
||||
parameter for calls of zalloc and zfree. This can be useful for custom
|
||||
memory management. The compression library attaches no meaning to the
|
||||
opaque value.
|
||||
|
||||
zalloc must return Z_NULL if there is not enough memory for the object.
|
||||
If zlib is used in a multi-threaded application, zalloc and zfree must be
|
||||
thread safe.
|
||||
|
||||
On 16-bit systems, the functions zalloc and zfree must be able to allocate
|
||||
exactly 65536 bytes, but will not be required to allocate more than this
|
||||
if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
|
||||
pointers returned by zalloc for objects of exactly 65536 bytes *must*
|
||||
have their offset normalized to zero. The default allocation function
|
||||
provided by this library ensures this (see zutil.c). To reduce memory
|
||||
requirements and avoid any allocation of 64K objects, at the expense of
|
||||
compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
|
||||
|
||||
The fields total_in and total_out can be used for statistics or
|
||||
progress reports. After compression, total_in holds the total size of
|
||||
the uncompressed data and may be saved for use in the decompressor
|
||||
(particularly if the decompressor wants to decompress everything in
|
||||
a single step).
|
||||
*/
|
||||
|
||||
/* constants */
|
||||
|
||||
#define Z_NO_FLUSH 0
|
||||
#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
|
||||
#define Z_SYNC_FLUSH 2
|
||||
#define Z_FULL_FLUSH 3
|
||||
#define Z_FINISH 4
|
||||
/* Allowed flush values; see deflate() below for details */
|
||||
|
||||
#define Z_OK 0
|
||||
#define Z_STREAM_END 1
|
||||
#define Z_NEED_DICT 2
|
||||
#define Z_ERRNO (-1)
|
||||
#define Z_STREAM_ERROR (-2)
|
||||
#define Z_DATA_ERROR (-3)
|
||||
#define Z_MEM_ERROR (-4)
|
||||
#define Z_BUF_ERROR (-5)
|
||||
#define Z_VERSION_ERROR (-6)
|
||||
/* Return codes for the compression/decompression functions. Negative
|
||||
* values are errors, positive values are used for special but normal events.
|
||||
*/
|
||||
|
||||
#define Z_NO_COMPRESSION 0
|
||||
#define Z_BEST_SPEED 1
|
||||
#define Z_BEST_COMPRESSION 9
|
||||
#define Z_DEFAULT_COMPRESSION (-1)
|
||||
/* compression levels */
|
||||
|
||||
#define Z_FILTERED 1
|
||||
#define Z_HUFFMAN_ONLY 2
|
||||
#define Z_DEFAULT_STRATEGY 0
|
||||
/* compression strategy; see deflateInit2() below for details */
|
||||
|
||||
#define Z_BINARY 0
|
||||
#define Z_ASCII 1
|
||||
#define Z_UNKNOWN 2
|
||||
/* Possible values of the data_type field */
|
||||
|
||||
#define Z_DEFLATED 8
|
||||
/* The deflate compression method (the only one supported in this version) */
|
||||
|
||||
#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
|
||||
|
||||
#define zlib_version zlibVersion()
|
||||
/* for compatibility with versions < 1.0.2 */
|
||||
|
||||
/* basic functions */
|
||||
|
||||
ZEXTERN const char * ZEXPORT zlibVersion OF((void));
|
||||
/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
|
||||
If the first character differs, the library code actually used is
|
||||
not compatible with the zlib.h header file used by the application.
|
||||
This check is automatically made by deflateInit and inflateInit.
|
||||
*/
|
||||
|
||||
/*
|
||||
ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
|
||||
|
||||
Initializes the internal stream state for compression. The fields
|
||||
zalloc, zfree and opaque must be initialized before by the caller.
|
||||
If zalloc and zfree are set to Z_NULL, deflateInit updates them to
|
||||
use default allocation functions.
|
||||
|
||||
The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
|
||||
1 gives best speed, 9 gives best compression, 0 gives no compression at
|
||||
all (the input data is simply copied a block at a time).
|
||||
Z_DEFAULT_COMPRESSION requests a default compromise between speed and
|
||||
compression (currently equivalent to level 6).
|
||||
|
||||
deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
|
||||
enough memory, Z_STREAM_ERROR if level is not a valid compression level,
|
||||
Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
|
||||
with the version assumed by the caller (ZLIB_VERSION).
|
||||
msg is set to null if there is no error message. deflateInit does not
|
||||
perform any compression: this will be done by deflate().
|
||||
*/
|
||||
|
||||
|
||||
ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
|
||||
/*
|
||||
deflate compresses as much data as possible, and stops when the input
|
||||
buffer becomes empty or the output buffer becomes full. It may introduce some
|
||||
output latency (reading input without producing any output) except when
|
||||
forced to flush.
|
||||
|
||||
The detailed semantics are as follows. deflate performs one or both of the
|
||||
following actions:
|
||||
|
||||
- Compress more input starting at next_in and update next_in and avail_in
|
||||
accordingly. If not all input can be processed (because there is not
|
||||
enough room in the output buffer), next_in and avail_in are updated and
|
||||
processing will resume at this point for the next call of deflate().
|
||||
|
||||
- Provide more output starting at next_out and update next_out and avail_out
|
||||
accordingly. This action is forced if the parameter flush is non zero.
|
||||
Forcing flush frequently degrades the compression ratio, so this parameter
|
||||
should be set only when necessary (in interactive applications).
|
||||
Some output may be provided even if flush is not set.
|
||||
|
||||
Before the call of deflate(), the application should ensure that at least
|
||||
one of the actions is possible, by providing more input and/or consuming
|
||||
more output, and updating avail_in or avail_out accordingly; avail_out
|
||||
should never be zero before the call. The application can consume the
|
||||
compressed output when it wants, for example when the output buffer is full
|
||||
(avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
|
||||
and with zero avail_out, it must be called again after making room in the
|
||||
output buffer because there might be more output pending.
|
||||
|
||||
If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
|
||||
flushed to the output buffer and the output is aligned on a byte boundary, so
|
||||
that the decompressor can get all input data available so far. (In particular
|
||||
avail_in is zero after the call if enough output space has been provided
|
||||
before the call.) Flushing may degrade compression for some compression
|
||||
algorithms and so it should be used only when necessary.
|
||||
|
||||
If flush is set to Z_FULL_FLUSH, all output is flushed as with
|
||||
Z_SYNC_FLUSH, and the compression state is reset so that decompression can
|
||||
restart from this point if previous compressed data has been damaged or if
|
||||
random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
|
||||
the compression.
|
||||
|
||||
If deflate returns with avail_out == 0, this function must be called again
|
||||
with the same value of the flush parameter and more output space (updated
|
||||
avail_out), until the flush is complete (deflate returns with non-zero
|
||||
avail_out).
|
||||
|
||||
If the parameter flush is set to Z_FINISH, pending input is processed,
|
||||
pending output is flushed and deflate returns with Z_STREAM_END if there
|
||||
was enough output space; if deflate returns with Z_OK, this function must be
|
||||
called again with Z_FINISH and more output space (updated avail_out) but no
|
||||
more input data, until it returns with Z_STREAM_END or an error. After
|
||||
deflate has returned Z_STREAM_END, the only possible operations on the
|
||||
stream are deflateReset or deflateEnd.
|
||||
|
||||
Z_FINISH can be used immediately after deflateInit if all the compression
|
||||
is to be done in a single step. In this case, avail_out must be at least
|
||||
0.1% larger than avail_in plus 12 bytes. If deflate does not return
|
||||
Z_STREAM_END, then it must be called again as described above.
|
||||
|
||||
deflate() sets strm->adler to the adler32 checksum of all input read
|
||||
so far (that is, total_in bytes).
|
||||
|
||||
deflate() may update data_type if it can make a good guess about
|
||||
the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
|
||||
binary. This field is only for information purposes and does not affect
|
||||
the compression algorithm in any manner.
|
||||
|
||||
deflate() returns Z_OK if some progress has been made (more input
|
||||
processed or more output produced), Z_STREAM_END if all input has been
|
||||
consumed and all output has been produced (only when flush is set to
|
||||
Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
|
||||
if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
|
||||
(for example avail_in or avail_out was zero).
|
||||
*/
|
||||
|
||||
|
||||
ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
|
||||
/*
|
||||
All dynamically allocated data structures for this stream are freed.
|
||||
This function discards any unprocessed input and does not flush any
|
||||
pending output.
|
||||
|
||||
deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
|
||||
stream state was inconsistent, Z_DATA_ERROR if the stream was freed
|
||||
prematurely (some input or output was discarded). In the error case,
|
||||
msg may be set but then points to a static string (which must not be
|
||||
deallocated).
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
|
||||
|
||||
Initializes the internal stream state for decompression. The fields
|
||||
next_in, avail_in, zalloc, zfree and opaque must be initialized before by
|
||||
the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
|
||||
value depends on the compression method), inflateInit determines the
|
||||
compression method from the zlib header and allocates all data structures
|
||||
accordingly; otherwise the allocation will be deferred to the first call of
|
||||
inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
|
||||
use default allocation functions.
|
||||
|
||||
inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
|
||||
memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
|
||||
version assumed by the caller. msg is set to null if there is no error
|
||||
message. inflateInit does not perform any decompression apart from reading
|
||||
the zlib header if present: this will be done by inflate(). (So next_in and
|
||||
avail_in may be modified, but next_out and avail_out are unchanged.)
|
||||
*/
|
||||
|
||||
|
||||
ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
|
||||
/*
|
||||
inflate decompresses as much data as possible, and stops when the input
|
||||
buffer becomes empty or the output buffer becomes full. It may some
|
||||
introduce some output latency (reading input without producing any output)
|
||||
except when forced to flush.
|
||||
|
||||
The detailed semantics are as follows. inflate performs one or both of the
|
||||
following actions:
|
||||
|
||||
- Decompress more input starting at next_in and update next_in and avail_in
|
||||
accordingly. If not all input can be processed (because there is not
|
||||
enough room in the output buffer), next_in is updated and processing
|
||||
will resume at this point for the next call of inflate().
|
||||
|
||||
- Provide more output starting at next_out and update next_out and avail_out
|
||||
accordingly. inflate() provides as much output as possible, until there
|
||||
is no more input data or no more space in the output buffer (see below
|
||||
about the flush parameter).
|
||||
|
||||
Before the call of inflate(), the application should ensure that at least
|
||||
one of the actions is possible, by providing more input and/or consuming
|
||||
more output, and updating the next_* and avail_* values accordingly.
|
||||
The application can consume the uncompressed output when it wants, for
|
||||
example when the output buffer is full (avail_out == 0), or after each
|
||||
call of inflate(). If inflate returns Z_OK and with zero avail_out, it
|
||||
must be called again after making room in the output buffer because there
|
||||
might be more output pending.
|
||||
|
||||
If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
|
||||
output as possible to the output buffer. The flushing behavior of inflate is
|
||||
not specified for values of the flush parameter other than Z_SYNC_FLUSH
|
||||
and Z_FINISH, but the current implementation actually flushes as much output
|
||||
as possible anyway.
|
||||
|
||||
inflate() should normally be called until it returns Z_STREAM_END or an
|
||||
error. However if all decompression is to be performed in a single step
|
||||
(a single call of inflate), the parameter flush should be set to
|
||||
Z_FINISH. In this case all pending input is processed and all pending
|
||||
output is flushed; avail_out must be large enough to hold all the
|
||||
uncompressed data. (The size of the uncompressed data may have been saved
|
||||
by the compressor for this purpose.) The next operation on this stream must
|
||||
be inflateEnd to deallocate the decompression state. The use of Z_FINISH
|
||||
is never required, but can be used to inform inflate that a faster routine
|
||||
may be used for the single inflate() call.
|
||||
|
||||
If a preset dictionary is needed at this point (see inflateSetDictionary
|
||||
below), inflate sets strm-adler to the adler32 checksum of the
|
||||
dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise
|
||||
it sets strm->adler to the adler32 checksum of all output produced
|
||||
so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
|
||||
an error code as described below. At the end of the stream, inflate()
|
||||
checks that its computed adler32 checksum is equal to that saved by the
|
||||
compressor and returns Z_STREAM_END only if the checksum is correct.
|
||||
|
||||
inflate() returns Z_OK if some progress has been made (more input processed
|
||||
or more output produced), Z_STREAM_END if the end of the compressed data has
|
||||
been reached and all uncompressed output has been produced, Z_NEED_DICT if a
|
||||
preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
|
||||
corrupted (input stream not conforming to the zlib format or incorrect
|
||||
adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
|
||||
(for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
|
||||
enough memory, Z_BUF_ERROR if no progress is possible or if there was not
|
||||
enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
|
||||
case, the application may then call inflateSync to look for a good
|
||||
compression block.
|
||||
*/
|
||||
|
||||
|
||||
ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
|
||||
/*
|
||||
All dynamically allocated data structures for this stream are freed.
|
||||
This function discards any unprocessed input and does not flush any
|
||||
pending output.
|
||||
|
||||
inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
|
||||
was inconsistent. In the error case, msg may be set but then points to a
|
||||
static string (which must not be deallocated).
|
||||
*/
|
||||
|
||||
/* Advanced functions */
|
||||
|
||||
/*
|
||||
The following functions are needed only in some special applications.
|
||||
*/
|
||||
|
||||
/*
|
||||
ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
|
||||
int level,
|
||||
int method,
|
||||
int windowBits,
|
||||
int memLevel,
|
||||
int strategy));
|
||||
|
||||
This is another version of deflateInit with more compression options. The
|
||||
fields next_in, zalloc, zfree and opaque must be initialized before by
|
||||
the caller.
|
||||
|
||||
The method parameter is the compression method. It must be Z_DEFLATED in
|
||||
this version of the library.
|
||||
|
||||
The windowBits parameter is the base two logarithm of the window size
|
||||
(the size of the history buffer). It should be in the range 8..15 for this
|
||||
version of the library. Larger values of this parameter result in better
|
||||
compression at the expense of memory usage. The default value is 15 if
|
||||
deflateInit is used instead.
|
||||
|
||||
The memLevel parameter specifies how much memory should be allocated
|
||||
for the internal compression state. memLevel=1 uses minimum memory but
|
||||
is slow and reduces compression ratio; memLevel=9 uses maximum memory
|
||||
for optimal speed. The default value is 8. See zconf.h for total memory
|
||||
usage as a function of windowBits and memLevel.
|
||||
|
||||
The strategy parameter is used to tune the compression algorithm. Use the
|
||||
value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
|
||||
filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
|
||||
string match). Filtered data consists mostly of small values with a
|
||||
somewhat random distribution. In this case, the compression algorithm is
|
||||
tuned to compress them better. The effect of Z_FILTERED is to force more
|
||||
Huffman coding and less string matching; it is somewhat intermediate
|
||||
between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
|
||||
the compression ratio but not the correctness of the compressed output even
|
||||
if it is not set appropriately.
|
||||
|
||||
deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
|
||||
memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
|
||||
method). msg is set to null if there is no error message. deflateInit2 does
|
||||
not perform any compression: this will be done by deflate().
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
|
||||
const Bytef *dictionary,
|
||||
uInt dictLength));
|
||||
/*
|
||||
Initializes the compression dictionary from the given byte sequence
|
||||
without producing any compressed output. This function must be called
|
||||
immediately after deflateInit, deflateInit2 or deflateReset, before any
|
||||
call of deflate. The compressor and decompressor must use exactly the same
|
||||
dictionary (see inflateSetDictionary).
|
||||
|
||||
The dictionary should consist of strings (byte sequences) that are likely
|
||||
to be encountered later in the data to be compressed, with the most commonly
|
||||
used strings preferably put towards the end of the dictionary. Using a
|
||||
dictionary is most useful when the data to be compressed is short and can be
|
||||
predicted with good accuracy; the data can then be compressed better than
|
||||
with the default empty dictionary.
|
||||
|
||||
Depending on the size of the compression data structures selected by
|
||||
deflateInit or deflateInit2, a part of the dictionary may in effect be
|
||||
discarded, for example if the dictionary is larger than the window size in
|
||||
deflate or deflate2. Thus the strings most likely to be useful should be
|
||||
put at the end of the dictionary, not at the front.
|
||||
|
||||
Upon return of this function, strm->adler is set to the Adler32 value
|
||||
of the dictionary; the decompressor may later use this value to determine
|
||||
which dictionary has been used by the compressor. (The Adler32 value
|
||||
applies to the whole dictionary even if only a subset of the dictionary is
|
||||
actually used by the compressor.)
|
||||
|
||||
deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
|
||||
parameter is invalid (such as NULL dictionary) or the stream state is
|
||||
inconsistent (for example if deflate has already been called for this stream
|
||||
or if the compression method is bsort). deflateSetDictionary does not
|
||||
perform any compression: this will be done by deflate().
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
|
||||
z_streamp source));
|
||||
/*
|
||||
Sets the destination stream as a complete copy of the source stream.
|
||||
|
||||
This function can be useful when several compression strategies will be
|
||||
tried, for example when there are several ways of pre-processing the input
|
||||
data with a filter. The streams that will be discarded should then be freed
|
||||
by calling deflateEnd. Note that deflateCopy duplicates the internal
|
||||
compression state which can be quite large, so this strategy is slow and
|
||||
can consume lots of memory.
|
||||
|
||||
deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
|
||||
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
|
||||
(such as zalloc being NULL). msg is left unchanged in both source and
|
||||
destination.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
|
||||
/*
|
||||
This function is equivalent to deflateEnd followed by deflateInit,
|
||||
but does not free and reallocate all the internal compression state.
|
||||
The stream will keep the same compression level and any other attributes
|
||||
that may have been set by deflateInit2.
|
||||
|
||||
deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
|
||||
stream state was inconsistent (such as zalloc or state being NULL).
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
|
||||
int level,
|
||||
int strategy));
|
||||
/*
|
||||
Dynamically update the compression level and compression strategy. The
|
||||
interpretation of level and strategy is as in deflateInit2. This can be
|
||||
used to switch between compression and straight copy of the input data, or
|
||||
to switch to a different kind of input data requiring a different
|
||||
strategy. If the compression level is changed, the input available so far
|
||||
is compressed with the old level (and may be flushed); the new level will
|
||||
take effect only at the next call of deflate().
|
||||
|
||||
Before the call of deflateParams, the stream state must be set as for
|
||||
a call of deflate(), since the currently available input may have to
|
||||
be compressed and flushed. In particular, strm->avail_out must be non-zero.
|
||||
|
||||
deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
|
||||
stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
|
||||
if strm->avail_out was zero.
|
||||
*/
|
||||
|
||||
/*
|
||||
ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
|
||||
int windowBits));
|
||||
|
||||
This is another version of inflateInit with an extra parameter. The
|
||||
fields next_in, avail_in, zalloc, zfree and opaque must be initialized
|
||||
before by the caller.
|
||||
|
||||
The windowBits parameter is the base two logarithm of the maximum window
|
||||
size (the size of the history buffer). It should be in the range 8..15 for
|
||||
this version of the library. The default value is 15 if inflateInit is used
|
||||
instead. If a compressed stream with a larger window size is given as
|
||||
input, inflate() will return with the error code Z_DATA_ERROR instead of
|
||||
trying to allocate a larger window.
|
||||
|
||||
inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
|
||||
memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
|
||||
memLevel). msg is set to null if there is no error message. inflateInit2
|
||||
does not perform any decompression apart from reading the zlib header if
|
||||
present: this will be done by inflate(). (So next_in and avail_in may be
|
||||
modified, but next_out and avail_out are unchanged.)
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
|
||||
const Bytef *dictionary,
|
||||
uInt dictLength));
|
||||
/*
|
||||
Initializes the decompression dictionary from the given uncompressed byte
|
||||
sequence. This function must be called immediately after a call of inflate
|
||||
if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
|
||||
can be determined from the Adler32 value returned by this call of
|
||||
inflate. The compressor and decompressor must use exactly the same
|
||||
dictionary (see deflateSetDictionary).
|
||||
|
||||
inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
|
||||
parameter is invalid (such as NULL dictionary) or the stream state is
|
||||
inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
|
||||
expected one (incorrect Adler32 value). inflateSetDictionary does not
|
||||
perform any decompression: this will be done by subsequent calls of
|
||||
inflate().
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
|
||||
/*
|
||||
Skips invalid compressed data until a full flush point (see above the
|
||||
description of deflate with Z_FULL_FLUSH) can be found, or until all
|
||||
available input is skipped. No output is provided.
|
||||
|
||||
inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
|
||||
if no more input was provided, Z_DATA_ERROR if no flush point has been found,
|
||||
or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
|
||||
case, the application may save the current current value of total_in which
|
||||
indicates where valid compressed data was found. In the error case, the
|
||||
application may repeatedly call inflateSync, providing more input each time,
|
||||
until success or end of the input data.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
|
||||
/*
|
||||
This function is equivalent to inflateEnd followed by inflateInit,
|
||||
but does not free and reallocate all the internal decompression state.
|
||||
The stream will keep attributes that may have been set by inflateInit2.
|
||||
|
||||
inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
|
||||
stream state was inconsistent (such as zalloc or state being NULL).
|
||||
*/
|
||||
|
||||
|
||||
/* utility functions */
|
||||
|
||||
/*
|
||||
The following utility functions are implemented on top of the
|
||||
basic stream-oriented functions. To simplify the interface, some
|
||||
default options are assumed (compression level and memory usage,
|
||||
standard memory allocation functions). The source code of these
|
||||
utility functions can easily be modified if you need special options.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
|
||||
const Bytef *source, uLong sourceLen));
|
||||
/*
|
||||
Compresses the source buffer into the destination buffer. sourceLen is
|
||||
the byte length of the source buffer. Upon entry, destLen is the total
|
||||
size of the destination buffer, which must be at least 0.1% larger than
|
||||
sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
|
||||
compressed buffer.
|
||||
This function can be used to compress a whole file at once if the
|
||||
input file is mmap'ed.
|
||||
compress returns Z_OK if success, Z_MEM_ERROR if there was not
|
||||
enough memory, Z_BUF_ERROR if there was not enough room in the output
|
||||
buffer.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
|
||||
const Bytef *source, uLong sourceLen,
|
||||
int level));
|
||||
/*
|
||||
Compresses the source buffer into the destination buffer. The level
|
||||
parameter has the same meaning as in deflateInit. sourceLen is the byte
|
||||
length of the source buffer. Upon entry, destLen is the total size of the
|
||||
destination buffer, which must be at least 0.1% larger than sourceLen plus
|
||||
12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
|
||||
|
||||
compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
|
||||
memory, Z_BUF_ERROR if there was not enough room in the output buffer,
|
||||
Z_STREAM_ERROR if the level parameter is invalid.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
|
||||
const Bytef *source, uLong sourceLen));
|
||||
/*
|
||||
Decompresses the source buffer into the destination buffer. sourceLen is
|
||||
the byte length of the source buffer. Upon entry, destLen is the total
|
||||
size of the destination buffer, which must be large enough to hold the
|
||||
entire uncompressed data. (The size of the uncompressed data must have
|
||||
been saved previously by the compressor and transmitted to the decompressor
|
||||
by some mechanism outside the scope of this compression library.)
|
||||
Upon exit, destLen is the actual size of the compressed buffer.
|
||||
This function can be used to decompress a whole file at once if the
|
||||
input file is mmap'ed.
|
||||
|
||||
uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
|
||||
enough memory, Z_BUF_ERROR if there was not enough room in the output
|
||||
buffer, or Z_DATA_ERROR if the input data was corrupted.
|
||||
*/
|
||||
|
||||
|
||||
typedef voidp gzFile;
|
||||
|
||||
ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
|
||||
/*
|
||||
Opens a gzip (.gz) file for reading or writing. The mode parameter
|
||||
is as in fopen ("rb" or "wb") but can also include a compression level
|
||||
("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
|
||||
Huffman only compression as in "wb1h". (See the description
|
||||
of deflateInit2 for more information about the strategy parameter.)
|
||||
|
||||
gzopen can be used to read a file which is not in gzip format; in this
|
||||
case gzread will directly read from the file without decompression.
|
||||
|
||||
gzopen returns NULL if the file could not be opened or if there was
|
||||
insufficient memory to allocate the (de)compression state; errno
|
||||
can be checked to distinguish the two cases (if errno is zero, the
|
||||
zlib error is Z_MEM_ERROR). */
|
||||
|
||||
ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
|
||||
/*
|
||||
gzdopen() associates a gzFile with the file descriptor fd. File
|
||||
descriptors are obtained from calls like open, dup, creat, pipe or
|
||||
fileno (in the file has been previously opened with fopen).
|
||||
The mode parameter is as in gzopen.
|
||||
The next call of gzclose on the returned gzFile will also close the
|
||||
file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
|
||||
descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
|
||||
gzdopen returns NULL if there was insufficient memory to allocate
|
||||
the (de)compression state.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
|
||||
/*
|
||||
Dynamically update the compression level or strategy. See the description
|
||||
of deflateInit2 for the meaning of these parameters.
|
||||
gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
|
||||
opened for writing.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
|
||||
/*
|
||||
Reads the given number of uncompressed bytes from the compressed file.
|
||||
If the input file was not in gzip format, gzread copies the given number
|
||||
of bytes into the buffer.
|
||||
gzread returns the number of uncompressed bytes actually read (0 for
|
||||
end of file, -1 for error). */
|
||||
|
||||
ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
|
||||
const voidp buf, unsigned len));
|
||||
/*
|
||||
Writes the given number of uncompressed bytes into the compressed file.
|
||||
gzwrite returns the number of uncompressed bytes actually written
|
||||
(0 in case of error).
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
|
||||
/*
|
||||
Converts, formats, and writes the args to the compressed file under
|
||||
control of the format string, as in fprintf. gzprintf returns the number of
|
||||
uncompressed bytes actually written (0 in case of error).
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
|
||||
/*
|
||||
Writes the given null-terminated string to the compressed file, excluding
|
||||
the terminating null character.
|
||||
gzputs returns the number of characters written, or -1 in case of error.
|
||||
*/
|
||||
|
||||
ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
|
||||
/*
|
||||
Reads bytes from the compressed file until len-1 characters are read, or
|
||||
a newline character is read and transferred to buf, or an end-of-file
|
||||
condition is encountered. The string is then terminated with a null
|
||||
character.
|
||||
gzgets returns buf, or Z_NULL in case of error.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
|
||||
/*
|
||||
Writes c, converted to an unsigned char, into the compressed file.
|
||||
gzputc returns the value that was written, or -1 in case of error.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
|
||||
/*
|
||||
Reads one byte from the compressed file. gzgetc returns this byte
|
||||
or -1 in case of end of file or error.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
|
||||
/*
|
||||
Flushes all pending output into the compressed file. The parameter
|
||||
flush is as in the deflate() function. The return value is the zlib
|
||||
error number (see function gzerror below). gzflush returns Z_OK if
|
||||
the flush parameter is Z_FINISH and all output could be flushed.
|
||||
gzflush should be called only when strictly necessary because it can
|
||||
degrade compression.
|
||||
*/
|
||||
|
||||
ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
|
||||
z_off_t offset, int whence));
|
||||
/*
|
||||
Sets the starting position for the next gzread or gzwrite on the
|
||||
given compressed file. The offset represents a number of bytes in the
|
||||
uncompressed data stream. The whence parameter is defined as in lseek(2);
|
||||
the value SEEK_END is not supported.
|
||||
If the file is opened for reading, this function is emulated but can be
|
||||
extremely slow. If the file is opened for writing, only forward seeks are
|
||||
supported; gzseek then compresses a sequence of zeroes up to the new
|
||||
starting position.
|
||||
|
||||
gzseek returns the resulting offset location as measured in bytes from
|
||||
the beginning of the uncompressed stream, or -1 in case of error, in
|
||||
particular if the file is opened for writing and the new starting position
|
||||
would be before the current position.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
|
||||
/*
|
||||
Rewinds the given file. This function is supported only for reading.
|
||||
|
||||
gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
|
||||
*/
|
||||
|
||||
ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
|
||||
/*
|
||||
Returns the starting position for the next gzread or gzwrite on the
|
||||
given compressed file. This position represents a number of bytes in the
|
||||
uncompressed data stream.
|
||||
|
||||
gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzeof OF((gzFile file));
|
||||
/*
|
||||
Returns 1 when EOF has previously been detected reading the given
|
||||
input stream, otherwise zero.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzclose OF((gzFile file));
|
||||
/*
|
||||
Flushes all pending output if necessary, closes the compressed file
|
||||
and deallocates all the (de)compression state. The return value is the zlib
|
||||
error number (see function gzerror below).
|
||||
*/
|
||||
|
||||
ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
|
||||
/*
|
||||
Returns the error message for the last error which occurred on the
|
||||
given compressed file. errnum is set to zlib error number. If an
|
||||
error occurred in the file system and not in the compression library,
|
||||
errnum is set to Z_ERRNO and the application may consult errno
|
||||
to get the exact error code.
|
||||
*/
|
||||
|
||||
/* checksum functions */
|
||||
|
||||
/*
|
||||
These functions are not related to compression but are exported
|
||||
anyway because they might be useful in applications using the
|
||||
compression library.
|
||||
*/
|
||||
|
||||
ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
|
||||
|
||||
/*
|
||||
Update a running Adler-32 checksum with the bytes buf[0..len-1] and
|
||||
return the updated checksum. If buf is NULL, this function returns
|
||||
the required initial value for the checksum.
|
||||
An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
|
||||
much faster. Usage example:
|
||||
|
||||
uLong adler = adler32(0L, Z_NULL, 0);
|
||||
|
||||
while (read_buffer(buffer, length) != EOF) {
|
||||
adler = adler32(adler, buffer, length);
|
||||
}
|
||||
if (adler != original_adler) error();
|
||||
*/
|
||||
|
||||
ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
|
||||
/*
|
||||
Update a running crc with the bytes buf[0..len-1] and return the updated
|
||||
crc. If buf is NULL, this function returns the required initial value
|
||||
for the crc. Pre- and post-conditioning (one's complement) is performed
|
||||
within this function so it shouldn't be done by the application.
|
||||
Usage example:
|
||||
|
||||
uLong crc = crc32(0L, Z_NULL, 0);
|
||||
|
||||
while (read_buffer(buffer, length) != EOF) {
|
||||
crc = crc32(crc, buffer, length);
|
||||
}
|
||||
if (crc != original_crc) error();
|
||||
*/
|
||||
|
||||
|
||||
/* various hacks, don't look :) */
|
||||
|
||||
/* deflateInit and inflateInit are macros to allow checking the zlib version
|
||||
* and the compiler's view of z_stream:
|
||||
*/
|
||||
ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
|
||||
const char *version, int stream_size));
|
||||
ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
|
||||
const char *version, int stream_size));
|
||||
ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
|
||||
int windowBits, int memLevel,
|
||||
int strategy, const char *version,
|
||||
int stream_size));
|
||||
ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
|
||||
const char *version, int stream_size));
|
||||
#define deflateInit(strm, level) \
|
||||
deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
|
||||
#define inflateInit(strm) \
|
||||
inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
|
||||
#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
|
||||
deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
|
||||
(strategy), ZLIB_VERSION, sizeof(z_stream))
|
||||
#define inflateInit2(strm, windowBits) \
|
||||
inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
|
||||
|
||||
|
||||
#if !defined(_Z_UTIL_H) && !defined(NO_DUMMY_DECL)
|
||||
struct internal_state {int dummy;}; /* hack for buggy compilers */
|
||||
#endif
|
||||
|
||||
ZEXTERN const char * ZEXPORT zError OF((int err));
|
||||
ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
|
||||
ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _ZLIB_H */
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user