* Fix botched commit (forgot -a)

This commit is contained in:
Antidote 2013-07-20 20:57:20 -07:00
parent 8f550d3a5e
commit e86d64e7bb
56 changed files with 3213 additions and 1741 deletions

View File

@ -16,6 +16,8 @@
#ifndef __ALTTP_ENUMS_HPP__ #ifndef __ALTTP_ENUMS_HPP__
#define __ALTTP_ENUMS_HPP__ #define __ALTTP_ENUMS_HPP__
#ifndef __DOXYGEN_IGNORE__
#include "Types.hpp" #include "Types.hpp"
enum BowType : char enum BowType : char
@ -103,4 +105,5 @@ enum ALTTPTagAlong
AfterBoss AfterBoss
}; };
#endif // __DOXYGEN_IGNORE__
#endif // __ALTTP_ENUMS_HPP__ #endif // __ALTTP_ENUMS_HPP__

View File

@ -19,10 +19,13 @@
#include <Types.hpp> #include <Types.hpp>
#include <vector> #include <vector>
namespace zelda
{
class ALTTPQuest; class ALTTPQuest;
/*! \class ALTTPFile /*! \class ALTTPFile
* \brief A Link to the Past data container class * \brief A Link to the Past data container class class
* *
* Contains all relevant data for an A Link to the Past * Contains all relevant data for an A Link to the Past
* SRM file. * SRM file.
@ -84,4 +87,5 @@ private:
std::vector<ALTTPQuest*> m_backup; std::vector<ALTTPQuest*> m_backup;
}; };
} // zelda
#endif // __ALTTP_FILE_HPP__ #endif // __ALTTP_FILE_HPP__

View File

@ -21,14 +21,38 @@
#include "BinaryReader.hpp" #include "BinaryReader.hpp"
#include "ALTTPQuest.hpp" #include "ALTTPQuest.hpp"
namespace zelda
{
/*! \class ALTTPFileReader
* \brief A Link to the Past save data reader class
*
* A Class for reading binary data from an ALTTP Save File,
* all work is done using a memory buffer, and not read directly from the disk.
* \sa BinaryReader
*/
class ALTTPFile; class ALTTPFile;
class ALTTPFileReader : public BinaryReader class ALTTPFileReader : public io::BinaryReader
{ {
public: public:
/*! \brief This constructor takes an existing buffer to read from.
*
* \param data The existing buffer
* \param length The length of the existing buffer
*/
ALTTPFileReader(Uint8*, Uint64); ALTTPFileReader(Uint8*, Uint64);
/*! \brief This constructor creates an instance from a file on disk.
*
* \param filename The file to create the stream from
*/
ALTTPFileReader(const std::string&); ALTTPFileReader(const std::string&);
/*! \brief Reads the SRAM data from the buffer
*
* \return ALTTPFile* SRAM data
*/
ALTTPFile* readFile(); ALTTPFile* readFile();
private: private:
ALTTPRoomFlags* readRoomFlags(); ALTTPRoomFlags* readRoomFlags();
@ -36,4 +60,5 @@ private:
ALTTPDungeonItemFlags readDungeonFlags(); ALTTPDungeonItemFlags readDungeonFlags();
}; };
} // zelda
#endif // __ALTTP_FILE_READER_HPP__ #endif // __ALTTP_FILE_READER_HPP__

View File

@ -21,15 +21,40 @@
#include <BinaryWriter.hpp> #include <BinaryWriter.hpp>
#include "ALTTPQuest.hpp" #include "ALTTPQuest.hpp"
namespace zelda
{
class ALTTPFile; class ALTTPFile;
class ALTTPFileWriter : public BinaryWriter /*! \class ALTTPFileWriter
* \brief A Link to the Past save data writer class
*
* A Class for writing binary data to an ALTTP Save File,
* all work is done using a memory buffer, and not written directly to the disk.
* \sa BinaryReader
*/
class ALTTPFileWriter : public io::BinaryWriter
{ {
public: public:
/*! \brief This constructor takes an existing buffer to write to.
*
* \param data The existing buffer
* \param length The length of the existing buffer
*/
ALTTPFileWriter(Uint8*, Uint64); ALTTPFileWriter(Uint8*, Uint64);
/*! \brief This constructor creates an instance from a file on disk.
*
* \param filename The file to create the stream from
*/
ALTTPFileWriter(const std::string&); ALTTPFileWriter(const std::string&);
/*! \brief Writes the given SRAM data to a file on disk
*
* \param file SRAM data to right
*/
void writeFile(ALTTPFile* file); void writeFile(ALTTPFile* file);
private: private:
void writeRoomFlags(ALTTPRoomFlags*); void writeRoomFlags(ALTTPRoomFlags*);
void writeOverworldEvent(ALTTPOverworldEvent*); void writeOverworldEvent(ALTTPOverworldEvent*);
@ -37,4 +62,6 @@ private:
Uint16 calculateChecksum(Uint32 game); Uint16 calculateChecksum(Uint32 game);
}; };
} // zelda
#endif // __ALTTP_FILE_WRITER_HPP__ #endif // __ALTTP_FILE_WRITER_HPP__

View File

@ -22,6 +22,9 @@
#include "ALTTPStructs.hpp" #include "ALTTPStructs.hpp"
#include "ALTTPEnums.hpp" #include "ALTTPEnums.hpp"
namespace zelda
{
/*! \class ALTTPQuest /*! \class ALTTPQuest
* \brief A Link to the Past Quest container class * \brief A Link to the Past Quest container class
* *
@ -31,146 +34,607 @@
class ALTTPQuest class ALTTPQuest
{ {
public: public:
/*!
* \brief ALTTPQuest
*/
ALTTPQuest(); ALTTPQuest();
~ALTTPQuest(); ~ALTTPQuest();
/*!
* \brief setRoomFlags
* \param flags
*/
void setRoomFlags(std::vector<ALTTPRoomFlags*> flags); void setRoomFlags(std::vector<ALTTPRoomFlags*> flags);
/*!
* \brief setRoomFlags
* \param rf
* \param id
*/
void setRoomFlags(ALTTPRoomFlags* rf, Uint32 id); void setRoomFlags(ALTTPRoomFlags* rf, Uint32 id);
/*!
* \brief roomFlags
* \return
*/
std::vector<ALTTPRoomFlags*> roomFlags(); std::vector<ALTTPRoomFlags*> roomFlags();
/*!
* \brief roomFlags
* \param id
* \return
*/
ALTTPRoomFlags* roomFlags(Uint32 id); ALTTPRoomFlags* roomFlags(Uint32 id);
/*!
* \brief setOverworldEvents
* \param events
*/
void setOverworldEvents(std::vector<ALTTPOverworldEvent*> events); void setOverworldEvents(std::vector<ALTTPOverworldEvent*> events);
/*!
* \brief setOverworldEvents
* \param ow
* \param id
*/
void setOverworldEvents(ALTTPOverworldEvent* ow, Uint32 id); void setOverworldEvents(ALTTPOverworldEvent* ow, Uint32 id);
/*!
* \brief overworldEvents
* \return
*/
std::vector<ALTTPOverworldEvent*> overworldEvents() const; std::vector<ALTTPOverworldEvent*> overworldEvents() const;
/*!
* \brief overworldEvent
* \param id
* \return
*/
ALTTPOverworldEvent* overworldEvent(Uint32 id) const; ALTTPOverworldEvent* overworldEvent(Uint32 id) const;
/*!
* \brief setInventory
* \param inv
*/
void setInventory(ALTTPInventory* inv); void setInventory(ALTTPInventory* inv);
/*!
* \brief inventory
* \return
*/
ALTTPInventory* inventory() const; ALTTPInventory* inventory() const;
/*!
* \brief setRupeeMax
* \param val
*/
void setRupeeMax(Uint16 val); void setRupeeMax(Uint16 val);
/*!
* \brief rupeeMax
* \return
*/
Uint16 rupeeMax() const; Uint16 rupeeMax() const;
/*!
* \brief setRupeeCurrent
* \param val
*/
void setRupeeCurrent(Uint16 val); void setRupeeCurrent(Uint16 val);
/*!
* \brief rupeeCurrent
* \return
*/
Uint16 rupeeCurrent() const; Uint16 rupeeCurrent() const;
/*!
* \brief setCompasses
* \param flags
*/
void setCompasses(ALTTPDungeonItemFlags flags); void setCompasses(ALTTPDungeonItemFlags flags);
/*!
* \brief compasses
* \return
*/
ALTTPDungeonItemFlags compasses() const; ALTTPDungeonItemFlags compasses() const;
/*!
* \brief setBigKeys
* \param flags
*/
void setBigKeys(ALTTPDungeonItemFlags flags); void setBigKeys(ALTTPDungeonItemFlags flags);
/*!
* \brief bigKeys
* \return
*/
ALTTPDungeonItemFlags bigKeys() const; ALTTPDungeonItemFlags bigKeys() const;
/*!
* \brief setDungeonMaps
* \param flags
*/
void setDungeonMaps(ALTTPDungeonItemFlags flags); void setDungeonMaps(ALTTPDungeonItemFlags flags);
/*!
* \brief dungeonMaps
* \return
*/
ALTTPDungeonItemFlags dungeonMaps() const; ALTTPDungeonItemFlags dungeonMaps() const;
/*!
* \brief setWishingPond
* \param val
*/
void setWishingPond(Uint16 val); void setWishingPond(Uint16 val);
/*!
* \brief wishingPond
* \return
*/
Uint16 wishingPond() const; Uint16 wishingPond() const;
/*!
* \brief setHealthMax
* \param val
*/
void setHealthMax(Uint8 val); void setHealthMax(Uint8 val);
/*!
* \brief healthMax
* \return
*/
Uint8 healthMax() const; Uint8 healthMax() const;
/*!
* \brief setHealth
* \param val
*/
void setHealth(Uint8 val); void setHealth(Uint8 val);
/*!
* \brief health
* \return
*/
Uint8 health() const; Uint8 health() const;
/*!
* \brief setMagicPower
* \param val
*/
void setMagicPower(Uint8 val); void setMagicPower(Uint8 val);
/*!
* \brief magicPower
* \return
*/
Uint8 magicPower() const; Uint8 magicPower() const;
/*!
* \brief setKeys
* \param val
*/
void setKeys(Uint8 val); void setKeys(Uint8 val);
/*!
* \brief keys
* \return
*/
Uint8 keys() const; Uint8 keys() const;
/*!
* \brief setBombUpgrades
* \param val
*/
void setBombUpgrades(Uint8 val); void setBombUpgrades(Uint8 val);
/*!
* \brief bombUpgrades
* \return
*/
Uint8 bombUpgrades() const; Uint8 bombUpgrades() const;
/*!
* \brief setArrowUpgrades
* \param val
*/
void setArrowUpgrades(Uint8 val); void setArrowUpgrades(Uint8 val);
/*!
* \brief arrowUpgrades
* \return
*/
Uint8 arrowUpgrades() const; Uint8 arrowUpgrades() const;
/*!
* \brief setHealthFiller
* \param val
*/
void setHealthFiller(Uint8 val); void setHealthFiller(Uint8 val);
/*!
* \brief healthFiller
* \return
*/
Uint8 healthFiller() const; Uint8 healthFiller() const;
/*!
* \brief setMagicFiller
* \param val
*/
void setMagicFiller(Uint8 val); void setMagicFiller(Uint8 val);
/*!
* \brief magicFiller
* \return
*/
Uint8 magicFiller() const; Uint8 magicFiller() const;
/*!
* \brief setPendants
* \param val
*/
void setPendants(ALTTPPendants val); void setPendants(ALTTPPendants val);
/*!
* \brief pendants
* \return
*/
ALTTPPendants pendants() const; ALTTPPendants pendants() const;
/*!
* \brief setBombFiller
* \param val
*/
void setBombFiller(Uint8 val); void setBombFiller(Uint8 val);
/*!
* \brief bombFiller
* \return
*/
Uint8 bombFiller() const; Uint8 bombFiller() const;
/*!
* \brief setArrowFiller
* \param val
*/
void setArrowFiller(Uint8 val); void setArrowFiller(Uint8 val);
/*!
* \brief arrowFiller
* \return
*/
Uint8 arrowFiller() const; Uint8 arrowFiller() const;
/*!
* \brief setArrows
* \param val
*/
void setArrows(Uint8 val); void setArrows(Uint8 val);
/*!
* \brief arrows
* \return
*/
Uint8 arrows() const; Uint8 arrows() const;
/*!
* \brief setAbilityFlags
* \param val
*/
void setAbilityFlags(ALTTPAbilities val); void setAbilityFlags(ALTTPAbilities val);
/*!
* \brief abilityFlags
* \return
*/
ALTTPAbilities abilityFlags() const; ALTTPAbilities abilityFlags() const;
void setCrystals(ALTTPCrystals val); /*!
* \brief setCrystals
* \param val
*/
void setCrystals(ALTTPCrystals val);\
/*!
* \brief crystals
* \return
*/
ALTTPCrystals crystals() const; ALTTPCrystals crystals() const;
/*!
* \brief setMagicUsage
* \param val
*/
void setMagicUsage(ALTTPMagicUsage val); void setMagicUsage(ALTTPMagicUsage val);
/*!
* \brief magicUsage
* \return
*/
ALTTPMagicUsage magicUsage() const; ALTTPMagicUsage magicUsage() const;
/*!
* \brief setDungeonKeys
* \param val
*/
void setDungeonKeys(std::vector<Uint8> val); void setDungeonKeys(std::vector<Uint8> val);
/*!
* \brief setDungeonKeys
* \param id
* \param val
*/
void setDungeonKeys(Uint32 id, Uint8 val); void setDungeonKeys(Uint32 id, Uint8 val);
/*!
* \brief dungeonKeys
* \param id
* \return
*/
Uint8 dungeonKeys(Uint32 id) const; Uint8 dungeonKeys(Uint32 id) const;
/*!
* \brief dungeonCount
* \return
*/
Uint32 dungeonCount() const; Uint32 dungeonCount() const;
/*!
* \brief setProgressIndicator
* \param val
*/
void setProgressIndicator(ALTTPProgressIndicator val); void setProgressIndicator(ALTTPProgressIndicator val);
/*!
* \brief progressIndicator
* \return
*/
ALTTPProgressIndicator progressIndicator() const; ALTTPProgressIndicator progressIndicator() const;
/*!
* \brief setProgressFlags1
* \param val
*/
void setProgressFlags1(ALTTPProgressFlags1 val); void setProgressFlags1(ALTTPProgressFlags1 val);
/*!
* \brief progressFlags1
* \return
*/
ALTTPProgressFlags1 progressFlags1() const; ALTTPProgressFlags1 progressFlags1() const;
/*!
* \brief setMapIcon
* \param val
*/
void setMapIcon(ALTTPMapIcon val); void setMapIcon(ALTTPMapIcon val);
/*!
* \brief mapIcon
* \return
*/
ALTTPMapIcon mapIcon() const; ALTTPMapIcon mapIcon() const;
/*!
* \brief setStartLocation
* \param val
*/
void setStartLocation(ALTTPStartLocation val); void setStartLocation(ALTTPStartLocation val);
/*!
* \brief startLocation
* \return
*/
ALTTPStartLocation startLocation() const; ALTTPStartLocation startLocation() const;
/*!
* \brief setProgressFlags2
* \param val
*/
void setProgressFlags2(ALTTPProgressFlags2 val); void setProgressFlags2(ALTTPProgressFlags2 val);
/*!
* \brief progressFlags2
* \return
*/
ALTTPProgressFlags2 progressFlags2() const; ALTTPProgressFlags2 progressFlags2() const;
/*!
* \brief setLightDarkWorldIndicator
* \param val
*/
void setLightDarkWorldIndicator(ALTTPLightDarkWorldIndicator val); void setLightDarkWorldIndicator(ALTTPLightDarkWorldIndicator val);
/*!
* \brief lightDarkWorldIndicator
* \return
*/
ALTTPLightDarkWorldIndicator lightDarkWorldIndicator() const; ALTTPLightDarkWorldIndicator lightDarkWorldIndicator() const;
/*!
* \brief setTagAlong
* \param val
*/
void setTagAlong(ALTTPTagAlong val); void setTagAlong(ALTTPTagAlong val);
/*!
* \brief tagAlong
* \return
*/
ALTTPTagAlong tagAlong() const; ALTTPTagAlong tagAlong() const;
/*!
* \brief setOldManFlags
* \param flags
*/
void setOldManFlags(std::vector<Uint8> flags); void setOldManFlags(std::vector<Uint8> flags);
/*!
* \brief setOldManFlag
* \param id
* \param val
*/
void setOldManFlag(Uint32 id, Uint8 val); void setOldManFlag(Uint32 id, Uint8 val);
/*!
* \brief oldManFlag
* \param id
* \return
*/
Uint8 oldManFlag(Uint32 id); Uint8 oldManFlag(Uint32 id);
/*!
* \brief oldManFlagCount
* \return
*/
Uint32 oldManFlagCount() const; Uint32 oldManFlagCount() const;
/*!
* \brief setBombFlag
* \param flag
*/
void setBombFlag(Uint8 flag); void setBombFlag(Uint8 flag);
/*!
* \brief bombFlag
* \return
*/
Uint8 bombFlag() const; Uint8 bombFlag() const;
/*!
* \brief setUnknown1
* \param flags
*/
void setUnknown1(std::vector<Uint8> flags); void setUnknown1(std::vector<Uint8> flags);
/*!
* \brief setUnknown1
* \param id
* \param val
*/
void setUnknown1(Uint32 id, Uint8 val); void setUnknown1(Uint32 id, Uint8 val);
/*!
* \brief unknown1
* \param id
* \return
*/
Uint8 unknown1(Uint32 id); Uint8 unknown1(Uint32 id);
/*!
* \brief unknown1Count
* \return
*/
Uint32 unknown1Count() const; Uint32 unknown1Count() const;
/*!
* \brief setPlayerName
* \param playerName
*/
void setPlayerName(std::vector<Uint16> playerName); void setPlayerName(std::vector<Uint16> playerName);
/*!
* \brief setPlayerName
* \param playerName
*/
void setPlayerName(const std::string& playerName); void setPlayerName(const std::string& playerName);
/*!
* \brief playerName
* \return
*/
std::vector<Uint16> playerName() const; std::vector<Uint16> playerName() const;
/*!
* \brief playerNameToString
* \return
*/
std::string playerNameToString() const; std::string playerNameToString() const;
/*!
* \brief setValid
* \param val
*/
void setValid(bool val); void setValid(bool val);
/*!
* \brief valid
* \return
*/
bool valid(); bool valid();
/*!
* \brief setDungeonDeathTotals
* \param val
*/
void setDungeonDeathTotals(std::vector<Uint16> val); void setDungeonDeathTotals(std::vector<Uint16> val);
/*!
* \brief setDungeonDeathTotal
* \param id
* \param val
*/
void setDungeonDeathTotal(Uint32 id, Uint16 val); void setDungeonDeathTotal(Uint32 id, Uint16 val);
/*!
* \brief dungeonDeathTotal
* \param id
* \return
*/
Uint16 dungeonDeathTotal(Uint32 id) const; Uint16 dungeonDeathTotal(Uint32 id) const;
/*!
* \brief dungeonDeathTotalCount
* \return
*/
Uint16 dungeonDeathTotalCount() const; Uint16 dungeonDeathTotalCount() const;
/*!
* \brief setUnknown2
* \param val
*/
void setUnknown2(Uint16 val); void setUnknown2(Uint16 val);
/*!
* \brief unknown2
* \return
*/
Uint16 unknown2() const; Uint16 unknown2() const;
/*!
* \brief setDeathSaveCount
* \param val
*/
void setDeathSaveCount(Uint16 val); void setDeathSaveCount(Uint16 val);
/*!
* \brief deathSaveCount
* \return
*/
Uint16 deathSaveCount() const; Uint16 deathSaveCount() const;
/*!
* \brief setPostGameDeathCounter
* \param val
*/
void setPostGameDeathCounter(Int16 val); void setPostGameDeathCounter(Int16 val);
/*!
* \brief postGameDeathCounter
* \return
*/
Int16 postGameDeathCounter() const; Int16 postGameDeathCounter() const;
/*!
* \brief setChecksum
* \param checksum
*/
void setChecksum(Uint16 checksum); void setChecksum(Uint16 checksum);
/*!
* \brief checksum
* \return
*/
Uint16 checksum() const; Uint16 checksum() const;
private: private:
std::vector<ALTTPRoomFlags*> m_roomFlags; std::vector<ALTTPRoomFlags*> m_roomFlags;
@ -217,5 +681,6 @@ private:
Uint16 m_checksum; Uint16 m_checksum;
}; };
} // zelda
#endif // __ALTTP_QUEST_HPP__ #endif // __ALTTP_QUEST_HPP__

View File

@ -16,11 +16,14 @@
#ifndef __ALTTP_STRUCTS_HPP__ #ifndef __ALTTP_STRUCTS_HPP__
#define __ALTTP_STRUCTS_HPP__ #define __ALTTP_STRUCTS_HPP__
#ifndef __DOXYGEN_IGNORE__
#include <string> #include <string>
#include "Types.hpp" #include "Types.hpp"
/*! \struct ALTTPRoomFlags namespace zelda
*/ {
struct ALTTPRoomFlags struct ALTTPRoomFlags
{ {
bool Chest1:1; bool Chest1:1;
@ -41,8 +44,6 @@ struct ALTTPRoomFlags
bool ChestOrTile:1; bool ChestOrTile:1;
}; };
/*! \struct ALTTPOverworldEvent
*/
struct ALTTPOverworldEvent struct ALTTPOverworldEvent
{ {
bool Unused1:1; bool Unused1:1;
@ -55,8 +56,6 @@ struct ALTTPOverworldEvent
bool Unused5:1; bool Unused5:1;
}; };
/*! \struct ALTTPInventory
*/
struct ALTTPInventory struct ALTTPInventory
{ {
char Bow; char Bow;
@ -88,12 +87,6 @@ struct ALTTPInventory
char Shield; char Shield;
char Armor; char Armor;
char BottleTypes[4]; char BottleTypes[4];
std::string bowType();
std::string boomerangType();
std::string magicType();
std::string armorType();
std::string bottleType(Uint32);
}; };
/*! \struct ALTTPLightDarkWorldIndicator /*! \struct ALTTPLightDarkWorldIndicator
@ -204,4 +197,7 @@ struct ALTTPProgressFlags2
bool SmithsHaveSword:1; bool SmithsHaveSword:1;
}; };
}
#endif // __DOXYGEN_IGNORE__
#endif // __ALTTP_STRUCTS_HPP__ #endif // __ALTTP_STRUCTS_HPP__

View File

@ -12,12 +12,17 @@
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with libZelda. If not, see <http://www.gnu.org/licenses/> // along with libZelda. If not, see <http://www.gnu.org/licenses/>
#ifndef __BINARYREADER_HPP__ #ifndef __BINARYREADER_HPP__
#define __BINARYREADER_HPP__ #define __BINARYREADER_HPP__
#include "Stream.hpp" #include "Stream.hpp"
#include <string> #include <string>
namespace zelda
{
namespace io
{
/*! \class BinaryReader /*! \class BinaryReader
* \brief A Stream class for reading binary data * \brief A Stream class for reading binary data
* *
@ -139,6 +144,13 @@ public:
*/ */
std::string readUnicode(); std::string readUnicode();
/*! \brief Reads a string and advances the position in the file
*
* \return std::string The value at the current address
* \throw IOException when address is out of range
*/
std::string readString();
protected: protected:
/*! \brief Overload of isOpenForWriting in Stream /*! \brief Overload of isOpenForWriting in Stream
* *
@ -155,7 +167,14 @@ protected:
* \throw IOException * \throw IOException
*/ */
void writeBytes(Int8*, Int64); void writeBytes(Int8*, Int64);
std::string m_filepath; std::string m_filepath; //!< Path to the target file
}; };
}
}
#endif #ifndef BINARYREADER_BASE
#define BINARYREADER_BASE \
private: \
typedef zelda::io::BinaryReader base;
#endif // BINARYREADER_BASE
#endif // __BINARYREADER_HPP__

View File

@ -19,6 +19,11 @@
#include "Stream.hpp" #include "Stream.hpp"
#include <string> #include <string>
namespace zelda
{
namespace io
{
/*! \class BinaryWriter /*! \class BinaryWriter
* \brief A Stream class for writing binary data * \brief A Stream class for writing binary data
* *
@ -136,8 +141,15 @@ public:
protected: protected:
Int8 readByte(); Int8 readByte();
Int8* readBytes(Int64); Int8* readBytes(Int64);
bool isOpenForReading(); bool isOpenForReading(); //!< Overridden from \sa Stream
std::string m_filepath; std::string m_filepath; //!< Path to the target file
}; };
}
}
#endif #ifndef BINARYWRITER_BASE
#define BINARYWRITER_BASE \
private: \
typedef zelda::io::BinaryWriter base;
#endif // BINARYWRITER_BASE
#endif // __BINARY_WRITER_HPP__

View File

@ -18,6 +18,9 @@
#include <string> #include <string>
namespace zelda
{
/*! \class Exception /*! \class Exception
* \brief The baseclass for all Exceptions. * \brief The baseclass for all Exceptions.
* *
@ -33,7 +36,7 @@ public:
inline Exception(const std::string& message) : inline Exception(const std::string& message) :
m_message(message) m_message(message)
{ {
}; }
/*! \brief Returns the Error message of the exception /*! \brief Returns the Error message of the exception
* \return std::string The error message * \return std::string The error message
@ -41,9 +44,10 @@ public:
inline std::string message() const inline std::string message() const
{ {
return m_message; return m_message;
}; }
protected: protected:
std::string m_message; std::string m_message; //!< The error message string
}; };
} // zelda
#endif #endif

View File

@ -18,6 +18,9 @@
#include "Exception.hpp" #include "Exception.hpp"
namespace zelda
{
/*! \class FileNotFoundException /*! \class FileNotFoundException
* \brief An excpeption thrown when a file could not be found at the given path. * \brief An excpeption thrown when a file could not be found at the given path.
* *
@ -45,4 +48,6 @@ private:
std::string m_filename; std::string m_filename;
}; };
} // zelda
#endif #endif

View File

@ -19,6 +19,9 @@
#include "Exception.hpp" #include "Exception.hpp"
namespace zelda
{
/*! \class IOException /*! \class IOException
* \brief An excpeption thrown on inappropriate IO calls. * \brief An excpeption thrown on inappropriate IO calls.
* *
@ -36,8 +39,9 @@ public:
* \param message The error message to throw * \param message The error message to throw
*/ */
IOException(const std::string& message) : IOException(const std::string& message) :
Exception("IOException: " + message) Exception("IOException: " + message)
{}; {};
}; };
} // zelda
#endif #endif

View File

@ -17,7 +17,10 @@
#define __INVALID_OPERATION_EXCEPTION_HPP__ #define __INVALID_OPERATION_EXCEPTION_HPP__
#include <string> #include <string>
#include <Exception.hpp> #include "Exception.hpp"
namespace zelda
{
/*! \class InvalidOperationException /*! \class InvalidOperationException
* \brief An excpeption thrown on Invalid Operations calls. * \brief An excpeption thrown on Invalid Operations calls.
@ -39,4 +42,7 @@ public:
{ {
} }
}; };
} // zelda
#endif // __INVALID_OPERATION_EXCEPTION_HPP__ #endif // __INVALID_OPERATION_EXCEPTION_HPP__

36
include/MCFile.hpp Normal file
View File

@ -0,0 +1,36 @@
// This file is part of libZelda.
//
// libZelda is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libZelda is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libZelda. If not, see <http://www.gnu.org/licenses/>
#ifndef __MCFILE_HPP__
#define __MCFILE_HPP__
namespace zelda
{
/*! \class MCFile
* \brief The Minish Cap data container class class
*
* Contains all relevant data for a The Minish Cap save,
* file.
*/
class MCFile
{
public:
MCFile();
private:
};
} // zelda
#endif // __MCFILE_HPP__

62
include/MCFileReader.hpp Normal file
View File

@ -0,0 +1,62 @@
// This file is part of libZelda.
//
// libZelda is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libZelda is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libZelda. If not, see <http://www.gnu.org/licenses/>
#ifndef __MCFILEREADER_HPP__
#define __MCFILEREADER_HPP__
#include "Types.hpp"
#include "BinaryReader.hpp"
namespace zelda
{
class MCFile;
/*! \class MCFileReader
* \brief The Minish Cap Save save data reader class
*
* A Class for reading binary data from a The Minish Cap Save File,
* all work is done using a memory buffer, and not read directly from the disk.
* \sa BinaryReader
*/
class MCFileReader : public io::BinaryReader
{
public:
/*!
* \brief This constructor takes an existing buffer to read from.
*
* \param data The existing buffer
* \param length The length of the existing buffer
*/
MCFileReader(Uint8*, Uint64);
/*!
* \brief This constructor creates an instance from a file on disk.
*
* \param filename The file to create the stream from
*/
MCFileReader(const std::string&);
/*!
* \brief Reads the save data from the buffer
*
* \return MCFile* SRAM data
*/
MCFile* readFile();
};
} // zelda
#endif // __MCFILEREADER_HPP__

68
include/MCFileWriter.hpp Normal file
View File

@ -0,0 +1,68 @@
// This file is part of libZelda.
//
// libZelda is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libZelda is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libZelda. If not, see <http://www.gnu.org/licenses/>
#ifndef __MCFILEWRITER_HPP__
#define __MCFILEWRITER_HPP__
#include "Types.hpp"
#include "BinaryWriter.hpp"
namespace zelda
{
class MCFile;
/*! \class MCFileWriter
* \brief The Minish Cap Save save data writer class
*
* A Class for writing binary data to a The Minish Cap Save File,
* all work is done using a memory buffer, and not written directly from the disk.
* \sa BinaryWriter
*/
class MCFileWriter : public io::BinaryWriter
{
public:
/*!
* \brief This constructor takes an existing buffer to write to.
*
* \param data The existing buffer
* \param length The length of the existing buffer
*/
MCFileWriter(Uint8*, Uint64);
/*!
* \brief This constructor creates an instance from a file on disk.
*
* \param filename The file to create the stream from
*/
MCFileWriter(const std::string&);
/*!
* \brief Writes the given save data to a file on disk
*
* \param file Save data to write
*/
void writeFile(MCFile* file);
private:
Uint16 calculateSlotChecksum(Uint32 game);
Uint16 calculateChecksum(Uint8* data, Uint32 length);
Uint8* reverse(Uint8* data, Uint32 length);
void unscramble();
};
} // zelda
#endif // __MCFILEWRITER_HPP__

View File

@ -12,6 +12,7 @@
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with libZelda. If not, see <http://www.gnu.org/licenses/> // along with libZelda. If not, see <http://www.gnu.org/licenses/>
#ifndef __MAINPAGE_HPP__ #ifndef __MAINPAGE_HPP__
#define __MAINPAGE_HPP__ #define __MAINPAGE_HPP__
@ -22,7 +23,7 @@
* <br /> * <br />
* libZelda provides several basic classes that can be used to read from * libZelda provides several basic classes that can be used to read from
* and write to files, and memory, classes such as Stream, BinaryReader, BinaryWriter, * and write to files, and memory, classes such as Stream, BinaryReader, BinaryWriter,
* and the currently work in progress TextStream. * and TextStream.
* \section example_sec BinaryWriter example * \section example_sec BinaryWriter example
* \code * \code
* #include "BinaryWriter.hpp" * #include "BinaryWriter.hpp"

View File

@ -17,6 +17,11 @@
#include "Types.hpp" #include "Types.hpp"
namespace zelda
{
namespace io
{
/*! \class Stream /*! \class Stream
* \brief Stream is the main class all streams inherit from * \brief Stream is the main class all streams inherit from
* *
@ -35,17 +40,6 @@ public:
//! \brief Default buffer block size. //! \brief Default buffer block size.
static const Uint32 BLOCKSZ; static const Uint32 BLOCKSZ;
/*! \enum Endian
* \brief Allows the user to specify the Endianness of the stream buffer.<br />
* The proper actions are automatically taken depending on platform and
* buffer settings
*/
enum Endian
{
LittleEndian, //!< Specifies that the Stream is Little Endian (LSB)
BigEndian //!< Specifies that the Stream is Big Endian (MSB)
};
/*! \enum SeekOrigin /*! \enum SeekOrigin
* \brief Specifies how to seek in a stream. * \brief Specifies how to seek in a stream.
*/ */
@ -56,9 +50,8 @@ public:
End //!< Tells the Stream to seek from the End of the buffer. End //!< Tells the Stream to seek from the End of the buffer.
}; };
/*! \brief The default constructor /*! \brief The default constructor
*/ */
Stream(); Stream();
/*! \brief This constructor takes an existing buffer to read from. /*! \brief This constructor takes an existing buffer to read from.
* *
@ -87,13 +80,27 @@ public:
* \throw IOException * \throw IOException
*/ */
virtual void writeBit(bool val); virtual void writeBit(bool val);
/*! \brief Writes a byte at the current position and advances the position by one byte. /*! \brief Writes a byte at the current position and advances the position by one byte.
* \param byte The value to write * \param byte The value to write
* \throw IOException * \throw IOException
*/ */
virtual void writeUByte(Uint8 byte);
/*! \brief Writes a byte at the current position and advances the position by one byte.
* \param byte The value to write
* \throw IOException
*/
virtual void writeByte(Int8 byte); virtual void writeByte(Int8 byte);
/*! \brief Writes the given buffer with the specified length, buffers can be bigger than the length
* however it's undefined behavior to try and write a buffer which is smaller than the given length.
*
* \param data The buffer to write
* \param length The amount to write
* \throw IOException
*/
virtual void writeUBytes(Uint8* data, Int64 length);
/*! \brief Writes the given buffer with the specified length, buffers can be bigger than the length /*! \brief Writes the given buffer with the specified length, buffers can be bigger than the length
* however it's undefined behavior to try and write a buffer which is smaller than the given length. * however it's undefined behavior to try and write a buffer which is smaller than the given length.
* *
@ -212,7 +219,7 @@ public:
* *
* \return Endian The current Stream Endianess * \return Endian The current Stream Endianess
*/ */
Endian endianness() const; Endian endian() const;
/*! \brief Returns whether the stream is BigEndian /*! \brief Returns whether the stream is BigEndian
@ -235,5 +242,6 @@ protected:
Uint8* m_data; //!< The Stream buffer Uint8* m_data; //!< The Stream buffer
bool m_autoResize; //!< Whether the stream is autoresizing bool m_autoResize; //!< Whether the stream is autoresizing
}; };
} // io
} // zelda
#endif // __STREAM_HPP__ #endif // __STREAM_HPP__

View File

@ -20,6 +20,10 @@
#include <vector> #include <vector>
namespace zelda
{
namespace io
{
// TODO (Phil#1#): Need to actually use AccessMode // TODO (Phil#1#): Need to actually use AccessMode
/*! \class TextStream /*! \class TextStream
* \brief A Class for reading or writing Text data. * \brief A Class for reading or writing Text data.
@ -122,28 +126,28 @@ public:
* *
* \param mode The mode to set. * \param mode The mode to set.
*/ */
void setAccessMode(AccessMode mode); void setAccessMode(AccessMode mode);
/*! \brief Returns the AccessMode of the Stream. /*! \brief Returns the AccessMode of the Stream.
* *
* \return AccessModeThe mode to set. * \return AccessModeThe mode to set.
*/ */
AccessMode accessMode() const; AccessMode accessMode() const;
/*! \brief Sets the Textmode of the Stream. /*! \brief Sets the Textmode of the Stream.
* *
* \param mode The mode to set. * \param mode The mode to set.
*/ */
void setTextMode(TextMode mode); void setTextMode(TextMode mode);
/*! \brief Returns the TextMode of the Stream. /*! \brief Returns the TextMode of the Stream.
* *
* \return TextMode The mode to set. * \return TextMode The mode to set.
*/ */
TextMode textMode() const; TextMode textMode() const;
bool isOpenForReading() const; bool isOpenForReading() const;
bool isOpenForWriting() const; bool isOpenForWriting() const;
private: private:
void loadLines(); void loadLines();
std::string m_filename; std::string m_filename;
@ -154,5 +158,6 @@ private:
Uint32 m_currentLine; Uint32 m_currentLine;
Uint32 m_startLength; Uint32 m_startLength;
}; };
} // io
} // zelda
#endif #endif

View File

@ -17,6 +17,17 @@
#include <limits.h> #include <limits.h>
/*! \enum Endian
* \brief Allows the user to specify the Endianness of data.<br />
* The proper actions are automatically taken depending on platform and
* buffer settings
*/
enum Endian
{
LittleEndian, //!< Specifies that the Stream is Little Endian (LSB)
BigEndian //!< Specifies that the Stream is Big Endian (MSB)
};
// 8 bits integer types // 8 bits integer types
#if UCHAR_MAX == 0xFF #if UCHAR_MAX == 0xFF
typedef signed char Int8; typedef signed char Int8;
@ -56,4 +67,12 @@
typedef signed long long Int64; typedef signed long long Int64;
typedef unsigned long long Uint64; typedef unsigned long long Uint64;
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else // __cplusplus
#define NULL (void*)0
#endif
#endif // NULL
#endif #endif

View File

@ -20,22 +20,67 @@
#include <string> #include <string>
#include <Types.hpp> #include <Types.hpp>
namespace zelda
{
/*!
* \brief The WiiImage class
*/
class WiiImage class WiiImage
{ {
public: public:
/*!
* \brief WiiImage
*/
WiiImage(); WiiImage();
/*!
* \brief WiiImage
* \param width
* \param height
* \param data
*/
WiiImage(Uint32 width, Uint32 height, Uint8* data); WiiImage(Uint32 width, Uint32 height, Uint8* data);
~WiiImage(); ~WiiImage();
/*!
* \brief setWidth
* \param width
*/
void setWidth(const Uint32 width); void setWidth(const Uint32 width);
/*!
* \brief width
* \return
*/
Uint32 width() const; Uint32 width() const;
/*!
* \brief setHeight
* \param height
*/
void setHeight(const Uint32 height); void setHeight(const Uint32 height);
/*!
* \brief height
* \return
*/
Uint32 height() const; Uint32 height() const;
/*!
* \brief setData
* \param data
*/
void setData(const Uint8* data); void setData(const Uint8* data);
/*!
* \brief data
* \return
*/
Uint8* data(); Uint8* data();
/*!
* \brief toRGBA32 DOES NOT WORK!!! DO NOT USE!!!
* \return
*/
Uint8* toRGBA32(); Uint8* toRGBA32();
private: private:
@ -44,41 +89,156 @@ private:
Uint8* m_data; Uint8* m_data;
}; };
/*! \class WiiBanner
* \brief Wii banner container class
*
* Contains all relevant data for a Wii banner.
*/
class WiiBanner class WiiBanner
{ {
public: public:
enum { NoCopy = 0x00000001, Bounce = 0x00000010, NoCopyBounce = NoCopy | Bounce }; enum
{
NoCopy = 0x00000001,
Bounce = 0x00000010,
NoCopyBounce = NoCopy | Bounce
};
/*!
* \brief WiiBanner
*/
WiiBanner(); WiiBanner();
/*!
* \brief WiiBanner
* \param gameId
* \param title
* \param subtitle
* \param m_banner
* \param icons
*/
WiiBanner(Uint32 gameId, const std::string& title, const std::string& subtitle, WiiImage* m_banner, std::vector<WiiImage*> icons); WiiBanner(Uint32 gameId, const std::string& title, const std::string& subtitle, WiiImage* m_banner, std::vector<WiiImage*> icons);
virtual ~WiiBanner(); virtual ~WiiBanner();
/*!
* \brief setGameID
* \param id
*/
void setGameID(Uint64 id); void setGameID(Uint64 id);
/*!
* \brief gameID
* \return
*/
Uint64 gameID() const; Uint64 gameID() const;
/*!
* \brief setBannerImage
* \param banner
*/
void setBannerImage(WiiImage* banner); void setBannerImage(WiiImage* banner);
/*!
* \brief bannerImage
* \return
*/
WiiImage* bannerImage() const; WiiImage* bannerImage() const;
/*!
* \brief setBannerSize
* \param size
*/
void setBannerSize(Uint32 size); void setBannerSize(Uint32 size);
/*!
* \brief bannerSize
* \return
*/
Uint32 bannerSize() const; Uint32 bannerSize() const;
/*!
* \brief setTitle
* \param title
*/
void setTitle(const std::string& title); void setTitle(const std::string& title);
/*!
* \brief title
* \return
*/
std::string title() const; std::string title() const;
void setSubtitle(const std::string& subtitle); /*!
* \brief setSubtitle
* \param subtitle
*/
void setSubtitle(const std::string& subtitle);
/*!
* \brief subtitle
* \return
*/
std::string subtitle() const; std::string subtitle() const;
/*!
* \brief addIcon
* \param icon
*/
void addIcon(WiiImage* icon); void addIcon(WiiImage* icon);
/*!
* \brief setIcon
* \param id
* \param icon
*/
void setIcon(Uint32 id, WiiImage* icon); void setIcon(Uint32 id, WiiImage* icon);
/*!
* \brief getIcon
* \param id
* \return
*/
WiiImage* getIcon(Uint32 id) const; WiiImage* getIcon(Uint32 id) const;
/*!
* \brief icons
* \return
*/
std::vector<WiiImage*> icons() const; std::vector<WiiImage*> icons() const;
/*!
* \brief setAnimationSpeed
* \param animSpeed
*/
void setAnimationSpeed(Uint16 animSpeed); void setAnimationSpeed(Uint16 animSpeed);
/*!
* \brief animationSpeed
* \return
*/
Uint16 animationSpeed() const; Uint16 animationSpeed() const;
/*!
* \brief setPermissions
* \param permissions
*/
void setPermissions(Uint8 permissions); void setPermissions(Uint8 permissions);
/*!
* \brief permissions
* \return
*/
Uint8 permissions() const; Uint8 permissions() const;
/*!
* \brief setFlags
* \param flags
*/
void setFlags(Uint32 flags); void setFlags(Uint32 flags);
/*!
* \brief flags
* \return
*/
Uint32 flags() const; Uint32 flags() const;
protected: protected:
private: private:
@ -92,5 +252,6 @@ private:
std::string m_title; std::string m_title;
std::string m_subtitle; std::string m_subtitle;
}; };
} // zelda
#endif // WIIBANNER_H #endif // WIIBANNER_H

View File

@ -19,9 +19,22 @@
#include <map> #include <map>
#include <Types.hpp> #include <Types.hpp>
namespace zelda
{
/*! \class WiiFile
* \brief Wii file container class
*
* Contains all relevant data for a file in a data.bin file.
*/
class WiiFile class WiiFile
{ {
public: public:
/*! \enum Permission
* \brief The Wii uses a bastardized unix permissions system so these flags
* reflect the file's individual permissions.
*/
enum Permission enum Permission
{ {
OtherRead = 0x01, OtherRead = 0x01,
@ -32,11 +45,14 @@ public:
OwnerWrite = 0x20, OwnerWrite = 0x20,
// Mask values; // Mask values;
OtherRW = (OtherRead|OtherWrite), OtherRW = (OtherRead|OtherWrite), //!< Mask to get the Other group permissions
GroupRW = (GroupRead|GroupWrite), GroupRW = (GroupRead|GroupWrite),
OwnerRW = (OwnerRead|OwnerWrite) OwnerRW = (OwnerRead|OwnerWrite)
}; };
/*!
* \brief The Type enum
*/
enum Type enum Type
{ {
File = 0x01, File = 0x01,
@ -44,29 +60,104 @@ public:
}; };
WiiFile(); WiiFile();
/*!
* \brief WiiFile
* \param filename
*/
WiiFile(const std::string& filename); WiiFile(const std::string& filename);
/*!
* \brief WiiFile
* \param filename
* \param permissions
* \param data
* \param length
*/
WiiFile(const std::string& filename, Uint8 permissions, const Uint8* data, Uint32 length); WiiFile(const std::string& filename, Uint8 permissions, const Uint8* data, Uint32 length);
virtual ~WiiFile(); virtual ~WiiFile();
/*!
* \brief setFilename
* \param filename
*/
void setFilename(const std::string& filename); void setFilename(const std::string& filename);
/*!
* \brief filename
* \return
*/
std::string filename() const; std::string filename() const;
/*!
* \brief setData
* \param data
*/
void setData(const Uint8* data); void setData(const Uint8* data);
Uint8* data() const; /*!
* \brief data
* \return
*/
Uint8* data() const;
/*!
* \brief setLength
* \param len
*/
void setLength(const int len); void setLength(const int len);
int length() const;
/*!
* \brief length
* \return
*/
int length() const;
/*!
* \brief setPermissions
* \param permissions
*/
void setPermissions(const Uint8 permissions); void setPermissions(const Uint8 permissions);
/*!
* \brief permissions
* \return
*/
Uint8 permissions() const; Uint8 permissions() const;
/*!
* \brief setAttributes
* \param attr
*/
void setAttributes(const Uint8 attr); void setAttributes(const Uint8 attr);
/*!
* \brief attributes
* \return
*/
Uint8 attributes() const; Uint8 attributes() const;
/*!
* \brief setType
* \param type
*/
void setType(Type type); void setType(Type type);
/*!
* \brief type
* \return
*/
Type type() const; Type type() const;
/*!
* \brief isDirectory
* \return
*/
bool isDirectory() const; bool isDirectory() const;
/*!
* \brief isFile
* \return
*/
bool isFile() const; bool isFile() const;
protected: protected:
@ -79,4 +170,5 @@ private:
Uint8* m_fileData; Uint8* m_fileData;
}; };
} // zelda
#endif // WIIFILE_H #endif // WIIFILE_H

View File

@ -19,25 +19,67 @@
#include <string> #include <string>
#include <Types.hpp> #include <Types.hpp>
namespace zelda
{
class WiiFile; class WiiFile;
class WiiBanner; class WiiBanner;
class WiiImage; class WiiImage;
class BinaryReader; class BinaryReader;
class BinaryWriter; class BinaryWriter;
/*! \class WiiSave
* \brief Wii data.bin container class
*
* Contains all relevant data for a Wii data.bin file.
*/
class WiiSave class WiiSave
{ {
public: public:
/*!
* \brief FileIterator
*/
typedef std::unordered_map<std::string, WiiFile*>::const_iterator FileIterator; typedef std::unordered_map<std::string, WiiFile*>::const_iterator FileIterator;
/*!
* \brief WiiSave
*/
WiiSave(); WiiSave();
/*!
* \brief ~WiiSave
*/
virtual ~WiiSave(); virtual ~WiiSave();
/*!
* \brief addFile
* \param filename
* \param file
*/
void addFile(const std::string& filename, WiiFile* file); void addFile(const std::string& filename, WiiFile* file);
/*!
* \brief file
* \param filename
* \return
*/
WiiFile* file(const std::string& filename) const; WiiFile* file(const std::string& filename) const;
/*!
* \brief fileList
* \return
*/
std::unordered_map<std::string, WiiFile*>& fileList(); std::unordered_map<std::string, WiiFile*>& fileList();
/*!
* \brief setBanner
* \param banner
*/
void setBanner(WiiBanner* banner); void setBanner(WiiBanner* banner);
/*!
* \brief banner
* \return
*/
WiiBanner* banner() const; WiiBanner* banner() const;
protected: protected:
@ -48,4 +90,5 @@ private:
}; };
} // zelda
#endif // __WII__SAVE_HPP__ #endif // __WII__SAVE_HPP__

View File

@ -19,17 +19,41 @@
#include <utility.hpp> #include <utility.hpp>
#include <BinaryReader.hpp> #include <BinaryReader.hpp>
namespace zelda
{
class WiiSave; class WiiSave;
class WiiBanner; class WiiBanner;
class WiiFile; class WiiFile;
class WiiImage; class WiiImage;
class WiiSaveReader : public BinaryReader /*! \class WiiSaveReader
* \brief Wii data.bin reader class
*
* A Class for reading binary data from a wii data.bin file,
* all work is done using a memory buffer, and not read directly from the disk.
* \sa BinaryReader
*/
class WiiSaveReader : public io::BinaryReader
{ {
public: public:
/*! \brief This constructor takes an existing buffer to read from.
*
* \param data The existing buffer
* \param length The length of the existing buffer
*/
WiiSaveReader(const Uint8*, Uint64); WiiSaveReader(const Uint8*, Uint64);
/*! \brief This constructor creates an instance from a file on disk.
*
* \param filename The file to create the stream from
*/
WiiSaveReader(const std::string&); WiiSaveReader(const std::string&);
/*!
* \brief readSave
* \return
*/
WiiSave* readSave(); WiiSave* readSave();
private: private:
WiiBanner* readBanner(); WiiBanner* readBanner();
@ -37,4 +61,6 @@ private:
WiiImage* readImage(Uint32 width, Uint32 height); WiiImage* readImage(Uint32 width, Uint32 height);
void readCerts(Uint32 totalSize); void readCerts(Uint32 totalSize);
}; };
} // zelda
#endif // __WII_SAVE_READER_HPP__ #endif // __WII_SAVE_READER_HPP__

View File

@ -12,23 +12,49 @@
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with libZelda. If not, see <http://www.gnu.org/licenses/> // along with libZelda. If not, see <http://www.gnu.org/licenses/>
#ifndef __WII_SAVE_WRITER_HPP__ #ifndef __WII_SAVE_WRITER_HPP__
#define __WII_SAVE_WRITER_HPP__ #define __WII_SAVE_WRITER_HPP__
#include <Types.hpp> #include "Types.hpp"
#include <utility.hpp> #include "utility.hpp"
#include <BinaryWriter.hpp> #include "BinaryWriter.hpp"
namespace zelda
{
class WiiSave; class WiiSave;
class WiiBanner; class WiiBanner;
class WiiFile; class WiiFile;
class WiiImage; class WiiImage;
class WiiSaveWriter : public BinaryWriter /*! \class WiiSaveWriter
* \brief Wii data.bin writer class
*
* A Class for writing binary data to a wii data.bin file,
* all work is done using a memory buffer, and not written directly to the disk.
* \sa BinaryReader
*/
class WiiSaveWriter : public io::BinaryWriter
{ {
public: public:
/*! \brief This constructor creates an instance from a file on disk.
*
* \param filename The file to create the stream from
*/
WiiSaveWriter(const std::string&); WiiSaveWriter(const std::string&);
/*!
* \brief writeSave
* \param save
* \param macAddress
* \param ngId
* \param ngPriv
* \param ngSig
* \param ngKeyId
* \param filepath
* \return
*/
bool writeSave(WiiSave* save, Uint8* macAddress, Uint32 ngId, Uint8* ngPriv, Uint8* ngSig, Uint32 ngKeyId, const std::string& filepath = ""); bool writeSave(WiiSave* save, Uint8* macAddress, Uint32 ngId, Uint8* ngPriv, Uint8* ngSig, Uint32 ngKeyId, const std::string& filepath = "");
private: private:
@ -38,4 +64,5 @@ private:
void writeCerts(Uint32 filesSize, Uint32 ngId, Uint8* ngPriv, Uint8* ngSig, Uint32 ngKeyId); void writeCerts(Uint32 filesSize, Uint32 ngId, Uint8* ngPriv, Uint8* ngSig, Uint32 ngKeyId);
}; };
} // zelda
#endif // __WII_SAVE_WRITER_HPP__ #endif // __WII_SAVE_WRITER_HPP__

View File

@ -16,5 +16,3 @@ void aes_set_key(const Uint8 *key );
#endif #endif
#endif //__AES_H_ #endif //__AES_H_

View File

@ -1,6 +1,8 @@
#ifndef BN_H #ifndef BN_H
#define BN_H #define BN_H
#ifndef __DOXYGEN_IGNORE__
#include <Types.hpp> #include <Types.hpp>
int bn_compare(Uint8 *a, Uint8 *b, Uint32 n); int bn_compare(Uint8 *a, Uint8 *b, Uint32 n);
@ -10,4 +12,5 @@ void bn_mul(Uint8 *d, Uint8 *a, Uint8 *b, Uint8 *N, Uint32 n);
void bn_exp(Uint8 *d, Uint8 *a, Uint8 *N, Uint32 n, Uint8 *e, Uint32 en); void bn_exp(Uint8 *d, Uint8 *a, Uint8 *N, Uint32 n, Uint8 *e, Uint32 en);
void bn_inv(Uint8 *d, Uint8 *a, Uint8 *N, Uint32 n); void bn_inv(Uint8 *d, Uint8 *a, Uint8 *N, Uint32 n);
#endif // __DOXYGEN_IGNORE__
#endif // BN_H #endif // BN_H

View File

@ -1,241 +1,244 @@
#ifndef MD5_H #ifndef MD5_H
#define MD5_H #define MD5_H
#ifndef __DOXYGEN_IGNORE__
#ifdef __cplusplus #ifdef __cplusplus
extern "C" extern "C"
{ {
#endif #endif
/* ========================================================================== ** /* ========================================================================== **
* *
* MD5.h * MD5.h
* *
* Copyright: * Copyright:
* Copyright (C) 2003-2005 by Christopher R. Hertel * Copyright (C) 2003-2005 by Christopher R. Hertel
* *
* Email: crh@ubiqx.mn.org * Email: crh@ubiqx.mn.org
* *
* $Id: MD5.h,v 0.6 2005/06/08 18:35:59 crh Exp $ * $Id: MD5.h,v 0.6 2005/06/08 18:35:59 crh Exp $
* *
* Modifications and additions by dimok * Modifications and additions by dimok
* *
* -------------------------------------------------------------------------- ** * -------------------------------------------------------------------------- **
* *
* Description: * Description:
* Implements the MD5 hash algorithm, as described in RFC 1321. * Implements the MD5 hash algorithm, as described in RFC 1321.
* *
* -------------------------------------------------------------------------- ** * -------------------------------------------------------------------------- **
* *
* License: * License:
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* *
* -------------------------------------------------------------------------- ** * -------------------------------------------------------------------------- **
* *
* Notes: * Notes:
* *
* None of this will make any sense unless you're studying RFC 1321 as you * None of this will make any sense unless you're studying RFC 1321 as you
* read the code. * read the code.
* *
* MD5 is described in RFC 1321. * MD5 is described in RFC 1321.
* The MD*4* algorithm is described in RFC 1320 (that's 1321 - 1). * The MD*4* algorithm is described in RFC 1320 (that's 1321 - 1).
* MD5 is very similar to MD4, but not quite similar enough to justify * MD5 is very similar to MD4, but not quite similar enough to justify
* putting the two into a single module. Besides, I wanted to add a few * putting the two into a single module. Besides, I wanted to add a few
* extra functions to this one to expand its usability. * extra functions to this one to expand its usability.
* *
* There are three primary motivations for this particular implementation. * There are three primary motivations for this particular implementation.
* 1) Programmer's pride. I wanted to be able to say I'd done it, and I * 1) Programmer's pride. I wanted to be able to say I'd done it, and I
* wanted to learn from the experience. * wanted to learn from the experience.
* 2) Portability. I wanted an implementation that I knew to be portable * 2) Portability. I wanted an implementation that I knew to be portable
* to a reasonable number of platforms. In particular, the algorithm is * to a reasonable number of platforms. In particular, the algorithm is
* designed with little-endian platforms in mind, but I wanted an * designed with little-endian platforms in mind, but I wanted an
* endian-agnostic implementation. * endian-agnostic implementation.
* 3) Compactness. While not an overriding goal, I thought it worth-while * 3) Compactness. While not an overriding goal, I thought it worth-while
* to see if I could reduce the overall size of the result. This is in * to see if I could reduce the overall size of the result. This is in
* keeping with my hopes that this library will be suitable for use in * keeping with my hopes that this library will be suitable for use in
* some embedded environments. * some embedded environments.
* Beyond that, cleanliness and clarity are always worth pursuing. * Beyond that, cleanliness and clarity are always worth pursuing.
* *
* As mentioned above, the code really only makes sense if you are familiar * As mentioned above, the code really only makes sense if you are familiar
* with the MD5 algorithm or are using RFC 1321 as a guide. This code is * with the MD5 algorithm or are using RFC 1321 as a guide. This code is
* quirky, however, so you'll want to be reading carefully. * quirky, however, so you'll want to be reading carefully.
* *
* Yeah...most of the comments are cut-and-paste from my MD4 implementation. * Yeah...most of the comments are cut-and-paste from my MD4 implementation.
* *
* -------------------------------------------------------------------------- ** * -------------------------------------------------------------------------- **
* *
* References: * References:
* IETF RFC 1321: The MD5 Message-Digest Algorithm * IETF RFC 1321: The MD5 Message-Digest Algorithm
* Ron Rivest. IETF, April, 1992 * Ron Rivest. IETF, April, 1992
* *
* ========================================================================== ** * ========================================================================== **
*/ */
/* -------------------------------------------------------------------------- ** /* -------------------------------------------------------------------------- **
* Typedefs: * Typedefs:
*/ */
typedef struct typedef struct
{ {
unsigned int len; unsigned int len;
unsigned int ABCD[4]; unsigned int ABCD[4];
int b_used; int b_used;
unsigned char block[64]; unsigned char block[64];
} auth_md5Ctx; } auth_md5Ctx;
/* -------------------------------------------------------------------------- ** /* -------------------------------------------------------------------------- **
* Functions: * Functions:
*/ */
auth_md5Ctx *auth_md5InitCtx(auth_md5Ctx *ctx); auth_md5Ctx *auth_md5InitCtx(auth_md5Ctx *ctx);
/* ------------------------------------------------------------------------ ** /* ------------------------------------------------------------------------ **
* Initialize an MD5 context. * Initialize an MD5 context.
* *
* Input: ctx - A pointer to the MD5 context structure to be initialized. * Input: ctx - A pointer to the MD5 context structure to be initialized.
* Contexts are typically created thusly: * Contexts are typically created thusly:
* ctx = (auth_md5Ctx *)malloc( sizeof(auth_md5Ctx) ); * ctx = (auth_md5Ctx *)malloc( sizeof(auth_md5Ctx) );
* *
* Output: A pointer to the initialized context (same as <ctx>). * Output: A pointer to the initialized context (same as <ctx>).
* *
* Notes: The purpose of the context is to make it possible to generate * Notes: The purpose of the context is to make it possible to generate
* an MD5 Message Digest in stages, rather than having to pass a * an MD5 Message Digest in stages, rather than having to pass a
* single large block to a single MD5 function. The context * single large block to a single MD5 function. The context
* structure keeps track of various bits of state information. * structure keeps track of various bits of state information.
* *
* Once the context is initialized, the blocks of message data * Once the context is initialized, the blocks of message data
* are passed to the <auth_md5SumCtx()> function. Once the * are passed to the <auth_md5SumCtx()> function. Once the
* final bit of data has been handed to <auth_md5SumCtx()> the * final bit of data has been handed to <auth_md5SumCtx()> the
* context can be closed out by calling <auth_md5CloseCtx()>, * context can be closed out by calling <auth_md5CloseCtx()>,
* which also calculates the final MD5 result. * which also calculates the final MD5 result.
* *
* Don't forget to free an allocated context structure when * Don't forget to free an allocated context structure when
* you've finished using it. * you've finished using it.
* *
* See Also: <auth_md5SumCtx()>, <auth_md5CloseCtx()> * See Also: <auth_md5SumCtx()>, <auth_md5CloseCtx()>
* *
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
auth_md5Ctx *auth_md5SumCtx(auth_md5Ctx *ctx, const unsigned char *src, const int len); auth_md5Ctx *auth_md5SumCtx(auth_md5Ctx *ctx, const unsigned char *src, const int len);
/* ------------------------------------------------------------------------ ** /* ------------------------------------------------------------------------ **
* Build an MD5 Message Digest within the given context. * Build an MD5 Message Digest within the given context.
* *
* Input: ctx - Pointer to the context in which the MD5 sum is being * Input: ctx - Pointer to the context in which the MD5 sum is being
* built. * built.
* src - A chunk of source data. This will be used to drive * src - A chunk of source data. This will be used to drive
* the MD5 algorithm. * the MD5 algorithm.
* len - The number of bytes in <src>. * len - The number of bytes in <src>.
* *
* Output: A pointer to the updated context (same as <ctx>). * Output: A pointer to the updated context (same as <ctx>).
* *
* See Also: <auth_md5InitCtx()>, <auth_md5CloseCtx()>, <auth_md5Sum()> * See Also: <auth_md5InitCtx()>, <auth_md5CloseCtx()>, <auth_md5Sum()>
* *
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
auth_md5Ctx *auth_md5CloseCtx(auth_md5Ctx *ctx, unsigned char *dst); auth_md5Ctx *auth_md5CloseCtx(auth_md5Ctx *ctx, unsigned char *dst);
/* ------------------------------------------------------------------------ ** /* ------------------------------------------------------------------------ **
* Close an MD5 Message Digest context and generate the final MD5 sum. * Close an MD5 Message Digest context and generate the final MD5 sum.
* *
* Input: ctx - Pointer to the context in which the MD5 sum is being * Input: ctx - Pointer to the context in which the MD5 sum is being
* built. * built.
* dst - A pointer to at least 16 bytes of memory, which will * dst - A pointer to at least 16 bytes of memory, which will
* receive the finished MD5 sum. * receive the finished MD5 sum.
* *
* Output: A pointer to the closed context (same as <ctx>). * Output: A pointer to the closed context (same as <ctx>).
* You might use this to free a malloc'd context structure. :) * You might use this to free a malloc'd context structure. :)
* *
* Notes: The context (<ctx>) is returned in an undefined state. * Notes: The context (<ctx>) is returned in an undefined state.
* It must be re-initialized before re-use. * It must be re-initialized before re-use.
* *
* See Also: <auth_md5InitCtx()>, <auth_md5SumCtx()> * See Also: <auth_md5InitCtx()>, <auth_md5SumCtx()>
* *
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
unsigned char * MD5(unsigned char * hash, const unsigned char *src, const int len); unsigned char * MD5(unsigned char * hash, const unsigned char *src, const int len);
/* ------------------------------------------------------------------------ ** /* ------------------------------------------------------------------------ **
* Compute an MD5 message digest. * Compute an MD5 message digest.
* *
* Input: dst - Destination buffer into which the result will be written. * Input: dst - Destination buffer into which the result will be written.
* Must be 16 bytes, minimum. * Must be 16 bytes, minimum.
* src - Source data block to be MD5'd. * src - Source data block to be MD5'd.
* len - The length, in bytes, of the source block. * len - The length, in bytes, of the source block.
* (Note that the length is given in bytes, not bits.) * (Note that the length is given in bytes, not bits.)
* *
* Output: A pointer to <dst>, which will contain the calculated 16-byte * Output: A pointer to <dst>, which will contain the calculated 16-byte
* MD5 message digest. * MD5 message digest.
* *
* Notes: This function is a shortcut. It takes a single input block. * Notes: This function is a shortcut. It takes a single input block.
* For more drawn-out operations, see <auth_md5InitCtx()>. * For more drawn-out operations, see <auth_md5InitCtx()>.
* *
* This function is interface-compatible with the * This function is interface-compatible with the
* <auth_md4Sum()> function in the MD4 module. * <auth_md4Sum()> function in the MD4 module.
* *
* The MD5 algorithm is designed to work on data with an * The MD5 algorithm is designed to work on data with an
* arbitrary *bit* length. Most implementations, this one * arbitrary *bit* length. Most implementations, this one
* included, handle the input data in byte-sized chunks. * included, handle the input data in byte-sized chunks.
* *
* The MD5 algorithm does much of its work using four-byte * The MD5 algorithm does much of its work using four-byte
* words, and so can be tuned for speed based on the endian-ness * words, and so can be tuned for speed based on the endian-ness
* of the host. This implementation is intended to be * of the host. This implementation is intended to be
* endian-neutral, which may make it a teeny bit slower than * endian-neutral, which may make it a teeny bit slower than
* others. ...maybe. * others. ...maybe.
* *
* See Also: <auth_md5InitCtx()> * See Also: <auth_md5InitCtx()>
* *
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
unsigned char * MD5fromFile(unsigned char *dst, const char *src); unsigned char * MD5fromFile(unsigned char *dst, const char *src);
/* ------------------------------------------------------------------------ ** /* ------------------------------------------------------------------------ **
* Compute an MD5 message digest. * Compute an MD5 message digest.
* *
* Input: dst - Destination buffer into which the result will be written. * Input: dst - Destination buffer into which the result will be written.
* Must be 16 bytes, minimum. * Must be 16 bytes, minimum.
* src - filepath to the file to be MD5'd. * src - filepath to the file to be MD5'd.
* *
* Output: A pointer to <dst>, which will contain the calculated 16-byte * Output: A pointer to <dst>, which will contain the calculated 16-byte
* MD5 message digest. * MD5 message digest.
* *
* Notes: This function is a shortcut. It takes a single input block. * Notes: This function is a shortcut. It takes a single input block.
* For more drawn-out operations, see <auth_md5InitCtx()>. * For more drawn-out operations, see <auth_md5InitCtx()>.
* *
* This function is interface-compatible with the * This function is interface-compatible with the
* <auth_md4Sum()> function in the MD4 module. * <auth_md4Sum()> function in the MD4 module.
* *
* The MD5 algorithm is designed to work on data with an * The MD5 algorithm is designed to work on data with an
* arbitrary *bit* length. Most implementations, this one * arbitrary *bit* length. Most implementations, this one
* included, handle the input data in byte-sized chunks. * included, handle the input data in byte-sized chunks.
* *
* The MD5 algorithm does much of its work using four-byte * The MD5 algorithm does much of its work using four-byte
* words, and so can be tuned for speed based on the endian-ness * words, and so can be tuned for speed based on the endian-ness
* of the host. This implementation is intended to be * of the host. This implementation is intended to be
* endian-neutral, which may make it a teeny bit slower than * endian-neutral, which may make it a teeny bit slower than
* others. ...maybe. * others. ...maybe.
* *
* See Also: <auth_md5InitCtx()> * See Also: <auth_md5InitCtx()>
* *
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
const char * MD5ToString(const unsigned char *hash, char *dst); const char * MD5ToString(const unsigned char *hash, char *dst);
unsigned char * StringToMD5(const char * hash, unsigned char * dst); unsigned char * StringToMD5(const char * hash, unsigned char * dst);
/* ========================================================================== */ /* ========================================================================== */
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif // __DOXYGEN_IGNORE__
#endif /* AUTH_MD5_H */ #endif /* AUTH_MD5_H */

View File

@ -1,9 +1,9 @@
#ifndef _SHA1_H_ #ifndef _SHA1_H_
#define _SHA1_H_ #define _SHA1_H_
#include <Types.hpp> #include <Types.hpp>
#ifndef __DOXYGEN_IGNORE__
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
@ -32,8 +32,8 @@ typedef struct SHA1Context
void SHA1Reset(SHA1Context *); void SHA1Reset(SHA1Context *);
int SHA1Result(SHA1Context *); int SHA1Result(SHA1Context *);
void SHA1Input( SHA1Context *, void SHA1Input( SHA1Context *,
const unsigned char *, const unsigned char *,
unsigned); unsigned);
@ -43,4 +43,5 @@ Uint8* getSha1( Uint8 * stuff, Uint32 stuff_size );
} }
#endif #endif
#endif // __DOXYGEN_IGNORE__
#endif #endif

View File

@ -33,292 +33,292 @@ DEALINGS IN THE SOFTWARE.
namespace utf8 namespace utf8
{ {
// Base for the exceptions that may be thrown from the library // Base for the exceptions that may be thrown from the library
class exception : public ::std::exception { class exception : public ::std::exception {
}; };
// Exceptions that may be thrown from the library functions. // Exceptions that may be thrown from the library functions.
class invalid_code_point : public exception { class invalid_code_point : public exception {
uint32_t cp; uint32_t cp;
public: public:
invalid_code_point(uint32_t cp) : cp(cp) {} invalid_code_point(uint32_t cp) : cp(cp) {}
virtual const char* what() const throw() { return "Invalid code point"; } virtual const char* what() const throw() { return "Invalid code point"; }
uint32_t code_point() const {return cp;} uint32_t code_point() const {return cp;}
}; };
class invalid_utf8 : public exception { class invalid_utf8 : public exception {
uint8_t u8; uint8_t u8;
public: public:
invalid_utf8 (uint8_t u) : u8(u) {} invalid_utf8 (uint8_t u) : u8(u) {}
virtual const char* what() const throw() { return "Invalid UTF-8"; } virtual const char* what() const throw() { return "Invalid UTF-8"; }
uint8_t utf8_octet() const {return u8;} uint8_t utf8_octet() const {return u8;}
}; };
class invalid_utf16 : public exception { class invalid_utf16 : public exception {
uint16_t u16; uint16_t u16;
public: public:
invalid_utf16 (uint16_t u) : u16(u) {} invalid_utf16 (uint16_t u) : u16(u) {}
virtual const char* what() const throw() { return "Invalid UTF-16"; } virtual const char* what() const throw() { return "Invalid UTF-16"; }
uint16_t utf16_word() const {return u16;} uint16_t utf16_word() const {return u16;}
}; };
class not_enough_room : public exception { class not_enough_room : public exception {
public: public:
virtual const char* what() const throw() { return "Not enough space"; } virtual const char* what() const throw() { return "Not enough space"; }
}; };
/// The library API - functions intended to be called by the users /// The library API - functions intended to be called by the users
template <typename octet_iterator> template <typename octet_iterator>
octet_iterator append(uint32_t cp, octet_iterator result) octet_iterator append(uint32_t cp, octet_iterator result)
{ {
if (!utf8::internal::is_code_point_valid(cp)) if (!utf8::internal::is_code_point_valid(cp))
throw invalid_code_point(cp); throw invalid_code_point(cp);
if (cp < 0x80) // one octet if (cp < 0x80) // one octet
*(result++) = static_cast<uint8_t>(cp); *(result++) = static_cast<uint8_t>(cp);
else if (cp < 0x800) { // two octets else if (cp < 0x800) { // two octets
*(result++) = static_cast<uint8_t>((cp >> 6) | 0xc0); *(result++) = static_cast<uint8_t>((cp >> 6) | 0xc0);
*(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
}
else if (cp < 0x10000) { // three octets
*(result++) = static_cast<uint8_t>((cp >> 12) | 0xe0);
*(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80);
*(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
}
else { // four octets
*(result++) = static_cast<uint8_t>((cp >> 18) | 0xf0);
*(result++) = static_cast<uint8_t>(((cp >> 12) & 0x3f) | 0x80);
*(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80);
*(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
}
return result;
} }
else if (cp < 0x10000) { // three octets
template <typename octet_iterator, typename output_iterator> *(result++) = static_cast<uint8_t>((cp >> 12) | 0xe0);
output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement) *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80);
{ *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
while (start != end) {
octet_iterator sequence_start = start;
internal::utf_error err_code = utf8::internal::validate_next(start, end);
switch (err_code) {
case internal::UTF8_OK :
for (octet_iterator it = sequence_start; it != start; ++it)
*out++ = *it;
break;
case internal::NOT_ENOUGH_ROOM:
throw not_enough_room();
case internal::INVALID_LEAD:
utf8::append (replacement, out);
++start;
break;
case internal::INCOMPLETE_SEQUENCE:
case internal::OVERLONG_SEQUENCE:
case internal::INVALID_CODE_POINT:
utf8::append (replacement, out);
++start;
// just one replacement mark for the sequence
while (start != end && utf8::internal::is_trail(*start))
++start;
break;
}
}
return out;
} }
else { // four octets
template <typename octet_iterator, typename output_iterator> *(result++) = static_cast<uint8_t>((cp >> 18) | 0xf0);
inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) *(result++) = static_cast<uint8_t>(((cp >> 12) & 0x3f) | 0x80);
{ *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80);
static const uint32_t replacement_marker = utf8::internal::mask16(0xfffd); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
return utf8::replace_invalid(start, end, out, replacement_marker);
} }
return result;
}
template <typename octet_iterator> template <typename octet_iterator, typename output_iterator>
uint32_t next(octet_iterator& it, octet_iterator end) output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement)
{ {
uint32_t cp = 0; while (start != end) {
internal::utf_error err_code = utf8::internal::validate_next(it, end, cp); octet_iterator sequence_start = start;
internal::utf_error err_code = utf8::internal::validate_next(start, end);
switch (err_code) { switch (err_code) {
case internal::UTF8_OK : case internal::UTF8_OK :
for (octet_iterator it = sequence_start; it != start; ++it)
*out++ = *it;
break; break;
case internal::NOT_ENOUGH_ROOM : case internal::NOT_ENOUGH_ROOM:
throw not_enough_room(); throw not_enough_room();
case internal::INVALID_LEAD : case internal::INVALID_LEAD:
case internal::INCOMPLETE_SEQUENCE : utf8::append (replacement, out);
case internal::OVERLONG_SEQUENCE : ++start;
throw invalid_utf8(*it); break;
case internal::INVALID_CODE_POINT : case internal::INCOMPLETE_SEQUENCE:
throw invalid_code_point(cp); case internal::OVERLONG_SEQUENCE:
case internal::INVALID_CODE_POINT:
utf8::append (replacement, out);
++start;
// just one replacement mark for the sequence
while (start != end && utf8::internal::is_trail(*start))
++start;
break;
} }
return cp;
} }
return out;
}
template <typename octet_iterator> template <typename octet_iterator, typename output_iterator>
uint32_t peek_next(octet_iterator it, octet_iterator end) inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out)
{ {
return utf8::next(it, end); static const uint32_t replacement_marker = utf8::internal::mask16(0xfffd);
} return utf8::replace_invalid(start, end, out, replacement_marker);
}
template <typename octet_iterator> template <typename octet_iterator>
uint32_t prior(octet_iterator& it, octet_iterator start) uint32_t next(octet_iterator& it, octet_iterator end)
{ {
// can't do much if it == start uint32_t cp = 0;
if (it == start) internal::utf_error err_code = utf8::internal::validate_next(it, end, cp);
switch (err_code) {
case internal::UTF8_OK :
break;
case internal::NOT_ENOUGH_ROOM :
throw not_enough_room(); throw not_enough_room();
case internal::INVALID_LEAD :
octet_iterator end = it; case internal::INCOMPLETE_SEQUENCE :
// Go back until we hit either a lead octet or start case internal::OVERLONG_SEQUENCE :
while (utf8::internal::is_trail(*(--it))) throw invalid_utf8(*it);
if (it == start) case internal::INVALID_CODE_POINT :
throw invalid_utf8(*it); // error - no lead byte in the sequence throw invalid_code_point(cp);
return utf8::peek_next(it, end);
} }
return cp;
}
/// Deprecated in versions that include "prior" template <typename octet_iterator>
template <typename octet_iterator> uint32_t peek_next(octet_iterator it, octet_iterator end)
uint32_t previous(octet_iterator& it, octet_iterator pass_start) {
{ return utf8::next(it, end);
octet_iterator end = it; }
while (utf8::internal::is_trail(*(--it)))
if (it == pass_start)
throw invalid_utf8(*it); // error - no lead byte in the sequence
octet_iterator temp = it;
return utf8::next(temp, end);
}
template <typename octet_iterator, typename distance_type> template <typename octet_iterator>
void advance (octet_iterator& it, distance_type n, octet_iterator end) uint32_t prior(octet_iterator& it, octet_iterator start)
{ {
for (distance_type i = 0; i < n; ++i) // can't do much if it == start
utf8::next(it, end); if (it == start)
} throw not_enough_room();
template <typename octet_iterator> octet_iterator end = it;
typename std::iterator_traits<octet_iterator>::difference_type // Go back until we hit either a lead octet or start
distance (octet_iterator first, octet_iterator last) while (utf8::internal::is_trail(*(--it)))
{ if (it == start)
typename std::iterator_traits<octet_iterator>::difference_type dist; throw invalid_utf8(*it); // error - no lead byte in the sequence
for (dist = 0; first < last; ++dist) return utf8::peek_next(it, end);
utf8::next(first, last); }
return dist;
}
template <typename u16bit_iterator, typename octet_iterator> /// Deprecated in versions that include "prior"
octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) template <typename octet_iterator>
{ uint32_t previous(octet_iterator& it, octet_iterator pass_start)
while (start != end) { {
uint32_t cp = utf8::internal::mask16(*start++); octet_iterator end = it;
// Take care of surrogate pairs first while (utf8::internal::is_trail(*(--it)))
if (utf8::internal::is_lead_surrogate(cp)) { if (it == pass_start)
if (start != end) { throw invalid_utf8(*it); // error - no lead byte in the sequence
uint32_t trail_surrogate = utf8::internal::mask16(*start++); octet_iterator temp = it;
if (utf8::internal::is_trail_surrogate(trail_surrogate)) return utf8::next(temp, end);
cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; }
else
throw invalid_utf16(static_cast<uint16_t>(trail_surrogate)); template <typename octet_iterator, typename distance_type>
} void advance (octet_iterator& it, distance_type n, octet_iterator end)
{
for (distance_type i = 0; i < n; ++i)
utf8::next(it, end);
}
template <typename octet_iterator>
typename std::iterator_traits<octet_iterator>::difference_type
distance (octet_iterator first, octet_iterator last)
{
typename std::iterator_traits<octet_iterator>::difference_type dist;
for (dist = 0; first < last; ++dist)
utf8::next(first, last);
return dist;
}
template <typename u16bit_iterator, typename octet_iterator>
octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result)
{
while (start != end) {
uint32_t cp = utf8::internal::mask16(*start++);
// Take care of surrogate pairs first
if (utf8::internal::is_lead_surrogate(cp)) {
if (start != end) {
uint32_t trail_surrogate = utf8::internal::mask16(*start++);
if (utf8::internal::is_trail_surrogate(trail_surrogate))
cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET;
else else
throw invalid_utf16(static_cast<uint16_t>(cp)); throw invalid_utf16(static_cast<uint16_t>(trail_surrogate));
}
// Lone trail surrogate
else if (utf8::internal::is_trail_surrogate(cp))
throw invalid_utf16(static_cast<uint16_t>(cp));
result = utf8::append(cp, result);
}
return result;
}
template <typename u16bit_iterator, typename octet_iterator>
u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result)
{
while (start != end) {
uint32_t cp = utf8::next(start, end);
if (cp > 0xffff) { //make a surrogate pair
*result++ = static_cast<uint16_t>((cp >> 10) + internal::LEAD_OFFSET);
*result++ = static_cast<uint16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN);
} }
else else
*result++ = static_cast<uint16_t>(cp); throw invalid_utf16(static_cast<uint16_t>(cp));
} }
return result; // Lone trail surrogate
} else if (utf8::internal::is_trail_surrogate(cp))
throw invalid_utf16(static_cast<uint16_t>(cp));
template <typename octet_iterator, typename u32bit_iterator> result = utf8::append(cp, result);
octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) }
return result;
}
template <typename u16bit_iterator, typename octet_iterator>
u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result)
{
while (start != end) {
uint32_t cp = utf8::next(start, end);
if (cp > 0xffff) { //make a surrogate pair
*result++ = static_cast<uint16_t>((cp >> 10) + internal::LEAD_OFFSET);
*result++ = static_cast<uint16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN);
}
else
*result++ = static_cast<uint16_t>(cp);
}
return result;
}
template <typename octet_iterator, typename u32bit_iterator>
octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result)
{
while (start != end)
result = utf8::append(*(start++), result);
return result;
}
template <typename octet_iterator, typename u32bit_iterator>
u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result)
{
while (start != end)
(*result++) = utf8::next(start, end);
return result;
}
// The iterator class
template <typename octet_iterator>
class iterator : public std::iterator <std::bidirectional_iterator_tag, uint32_t> {
octet_iterator it;
octet_iterator range_start;
octet_iterator range_end;
public:
iterator () {};
explicit iterator (const octet_iterator& octet_it,
const octet_iterator& range_start,
const octet_iterator& range_end) :
it(octet_it), range_start(range_start), range_end(range_end)
{ {
while (start != end) if (it < range_start || it > range_end)
result = utf8::append(*(start++), result); throw std::out_of_range("Invalid utf-8 iterator position");
return result;
} }
// the default "big three" are OK
template <typename octet_iterator, typename u32bit_iterator> octet_iterator base () const { return it; }
u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) uint32_t operator * () const
{ {
while (start != end) octet_iterator temp = it;
(*result++) = utf8::next(start, end); return utf8::next(temp, range_end);
return result;
} }
bool operator == (const iterator& rhs) const
// The iterator class {
template <typename octet_iterator> if (range_start != rhs.range_start || range_end != rhs.range_end)
class iterator : public std::iterator <std::bidirectional_iterator_tag, uint32_t> { throw std::logic_error("Comparing utf-8 iterators defined with different ranges");
octet_iterator it; return (it == rhs.it);
octet_iterator range_start; }
octet_iterator range_end; bool operator != (const iterator& rhs) const
public: {
iterator () {}; return !(operator == (rhs));
explicit iterator (const octet_iterator& octet_it, }
const octet_iterator& range_start, iterator& operator ++ ()
const octet_iterator& range_end) : {
it(octet_it), range_start(range_start), range_end(range_end) utf8::next(it, range_end);
{ return *this;
if (it < range_start || it > range_end) }
throw std::out_of_range("Invalid utf-8 iterator position"); iterator operator ++ (int)
} {
// the default "big three" are OK iterator temp = *this;
octet_iterator base () const { return it; } utf8::next(it, range_end);
uint32_t operator * () const return temp;
{ }
octet_iterator temp = it; iterator& operator -- ()
return utf8::next(temp, range_end); {
} utf8::prior(it, range_start);
bool operator == (const iterator& rhs) const return *this;
{ }
if (range_start != rhs.range_start || range_end != rhs.range_end) iterator operator -- (int)
throw std::logic_error("Comparing utf-8 iterators defined with different ranges"); {
return (it == rhs.it); iterator temp = *this;
} utf8::prior(it, range_start);
bool operator != (const iterator& rhs) const return temp;
{ }
return !(operator == (rhs)); }; // class iterator
}
iterator& operator ++ ()
{
utf8::next(it, range_end);
return *this;
}
iterator operator ++ (int)
{
iterator temp = *this;
utf8::next(it, range_end);
return temp;
}
iterator& operator -- ()
{
utf8::prior(it, range_start);
return *this;
}
iterator operator -- (int)
{
iterator temp = *this;
utf8::prior(it, range_start);
return temp;
}
}; // class iterator
} // namespace utf8 } // namespace utf8

View File

@ -32,296 +32,296 @@ DEALINGS IN THE SOFTWARE.
namespace utf8 namespace utf8
{ {
// The typedefs for 8-bit, 16-bit and 32-bit unsigned integers // The typedefs for 8-bit, 16-bit and 32-bit unsigned integers
// You may need to change them to match your system. // You may need to change them to match your system.
// These typedefs have the same names as ones from cstdint, or boost/cstdint // These typedefs have the same names as ones from cstdint, or boost/cstdint
typedef unsigned char uint8_t; typedef unsigned char uint8_t;
typedef unsigned short uint16_t; typedef unsigned short uint16_t;
typedef unsigned int uint32_t; typedef unsigned int uint32_t;
// Helper code - not intended to be directly called by the library users. May be changed at any time // Helper code - not intended to be directly called by the library users. May be changed at any time
namespace internal namespace internal
{ {
// Unicode constants // Unicode constants
// Leading (high) surrogates: 0xd800 - 0xdbff // Leading (high) surrogates: 0xd800 - 0xdbff
// Trailing (low) surrogates: 0xdc00 - 0xdfff // Trailing (low) surrogates: 0xdc00 - 0xdfff
const uint16_t LEAD_SURROGATE_MIN = 0xd800u; const uint16_t LEAD_SURROGATE_MIN = 0xd800u;
const uint16_t LEAD_SURROGATE_MAX = 0xdbffu; const uint16_t LEAD_SURROGATE_MAX = 0xdbffu;
const uint16_t TRAIL_SURROGATE_MIN = 0xdc00u; const uint16_t TRAIL_SURROGATE_MIN = 0xdc00u;
const uint16_t TRAIL_SURROGATE_MAX = 0xdfffu; const uint16_t TRAIL_SURROGATE_MAX = 0xdfffu;
const uint16_t LEAD_OFFSET = LEAD_SURROGATE_MIN - (0x10000 >> 10); const uint16_t LEAD_OFFSET = LEAD_SURROGATE_MIN - (0x10000 >> 10);
const uint32_t SURROGATE_OFFSET = 0x10000u - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN; const uint32_t SURROGATE_OFFSET = 0x10000u - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN;
// Maximum valid value for a Unicode code point // Maximum valid value for a Unicode code point
const uint32_t CODE_POINT_MAX = 0x0010ffffu; const uint32_t CODE_POINT_MAX = 0x0010ffffu;
template<typename octet_type> template<typename octet_type>
inline uint8_t mask8(octet_type oc) inline uint8_t mask8(octet_type oc)
{ {
return static_cast<uint8_t>(0xff & oc); return static_cast<uint8_t>(0xff & oc);
}
template<typename u16_type>
inline uint16_t mask16(u16_type oc)
{
return static_cast<uint16_t>(0xffff & oc);
}
template<typename octet_type>
inline bool is_trail(octet_type oc)
{
return ((utf8::internal::mask8(oc) >> 6) == 0x2);
}
template <typename u16>
inline bool is_lead_surrogate(u16 cp)
{
return (cp >= LEAD_SURROGATE_MIN && cp <= LEAD_SURROGATE_MAX);
}
template <typename u16>
inline bool is_trail_surrogate(u16 cp)
{
return (cp >= TRAIL_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX);
}
template <typename u16>
inline bool is_surrogate(u16 cp)
{
return (cp >= LEAD_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX);
}
template <typename u32>
inline bool is_code_point_valid(u32 cp)
{
return (cp <= CODE_POINT_MAX && !utf8::internal::is_surrogate(cp));
}
template <typename octet_iterator>
inline typename std::iterator_traits<octet_iterator>::difference_type
sequence_length(octet_iterator lead_it)
{
uint8_t lead = utf8::internal::mask8(*lead_it);
if (lead < 0x80)
return 1;
else if ((lead >> 5) == 0x6)
return 2;
else if ((lead >> 4) == 0xe)
return 3;
else if ((lead >> 3) == 0x1e)
return 4;
else
return 0;
}
template <typename octet_difference_type>
inline bool is_overlong_sequence(uint32_t cp, octet_difference_type length)
{
if (cp < 0x80) {
if (length != 1)
return true;
} }
template<typename u16_type> else if (cp < 0x800) {
inline uint16_t mask16(u16_type oc) if (length != 2)
{ return true;
return static_cast<uint16_t>(0xffff & oc);
} }
template<typename octet_type> else if (cp < 0x10000) {
inline bool is_trail(octet_type oc) if (length != 3)
{ return true;
return ((utf8::internal::mask8(oc) >> 6) == 0x2);
} }
template <typename u16> return false;
inline bool is_lead_surrogate(u16 cp) }
{
return (cp >= LEAD_SURROGATE_MIN && cp <= LEAD_SURROGATE_MAX);
}
template <typename u16> enum utf_error {UTF8_OK, NOT_ENOUGH_ROOM, INVALID_LEAD, INCOMPLETE_SEQUENCE, OVERLONG_SEQUENCE, INVALID_CODE_POINT};
inline bool is_trail_surrogate(u16 cp)
{
return (cp >= TRAIL_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX);
}
template <typename u16> /// Helper for get_sequence_x
inline bool is_surrogate(u16 cp) template <typename octet_iterator>
{ utf_error increase_safely(octet_iterator& it, octet_iterator end)
return (cp >= LEAD_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX); {
} if (++it == end)
return NOT_ENOUGH_ROOM;
template <typename u32> if (!utf8::internal::is_trail(*it))
inline bool is_code_point_valid(u32 cp) return INCOMPLETE_SEQUENCE;
{
return (cp <= CODE_POINT_MAX && !utf8::internal::is_surrogate(cp));
}
template <typename octet_iterator> return UTF8_OK;
inline typename std::iterator_traits<octet_iterator>::difference_type }
sequence_length(octet_iterator lead_it)
{
uint8_t lead = utf8::internal::mask8(*lead_it);
if (lead < 0x80)
return 1;
else if ((lead >> 5) == 0x6)
return 2;
else if ((lead >> 4) == 0xe)
return 3;
else if ((lead >> 3) == 0x1e)
return 4;
else
return 0;
}
template <typename octet_difference_type> #define UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(IT, END) {utf_error ret = increase_safely(IT, END); if (ret != UTF8_OK) return ret;}
inline bool is_overlong_sequence(uint32_t cp, octet_difference_type length)
{
if (cp < 0x80) {
if (length != 1)
return true;
}
else if (cp < 0x800) {
if (length != 2)
return true;
}
else if (cp < 0x10000) {
if (length != 3)
return true;
}
return false; /// get_sequence_x functions decode utf-8 sequences of the length x
} template <typename octet_iterator>
utf_error get_sequence_1(octet_iterator& it, octet_iterator end, uint32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
enum utf_error {UTF8_OK, NOT_ENOUGH_ROOM, INVALID_LEAD, INCOMPLETE_SEQUENCE, OVERLONG_SEQUENCE, INVALID_CODE_POINT}; code_point = utf8::internal::mask8(*it);
/// Helper for get_sequence_x return UTF8_OK;
template <typename octet_iterator> }
utf_error increase_safely(octet_iterator& it, octet_iterator end)
{
if (++it == end)
return NOT_ENOUGH_ROOM;
if (!utf8::internal::is_trail(*it)) template <typename octet_iterator>
return INCOMPLETE_SEQUENCE; utf_error get_sequence_2(octet_iterator& it, octet_iterator end, uint32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
return UTF8_OK; code_point = utf8::internal::mask8(*it);
}
#define UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(IT, END) {utf_error ret = increase_safely(IT, END); if (ret != UTF8_OK) return ret;} UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
/// get_sequence_x functions decode utf-8 sequences of the length x code_point = ((code_point << 6) & 0x7ff) + ((*it) & 0x3f);
template <typename octet_iterator>
utf_error get_sequence_1(octet_iterator& it, octet_iterator end, uint32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
code_point = utf8::internal::mask8(*it); return UTF8_OK;
}
return UTF8_OK; template <typename octet_iterator>
} utf_error get_sequence_3(octet_iterator& it, octet_iterator end, uint32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
template <typename octet_iterator> code_point = utf8::internal::mask8(*it);
utf_error get_sequence_2(octet_iterator& it, octet_iterator end, uint32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
code_point = utf8::internal::mask8(*it); UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) code_point = ((code_point << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff);
code_point = ((code_point << 6) & 0x7ff) + ((*it) & 0x3f); UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
return UTF8_OK; code_point += (*it) & 0x3f;
}
template <typename octet_iterator> return UTF8_OK;
utf_error get_sequence_3(octet_iterator& it, octet_iterator end, uint32_t& code_point) }
{
if (it == end)
return NOT_ENOUGH_ROOM;
code_point = utf8::internal::mask8(*it); template <typename octet_iterator>
utf_error get_sequence_4(octet_iterator& it, octet_iterator end, uint32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) code_point = utf8::internal::mask8(*it);
code_point = ((code_point << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff); UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) code_point = ((code_point << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff);
code_point += (*it) & 0x3f; UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
return UTF8_OK; code_point += (utf8::internal::mask8(*it) << 6) & 0xfff;
}
template <typename octet_iterator> UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
utf_error get_sequence_4(octet_iterator& it, octet_iterator end, uint32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
code_point = utf8::internal::mask8(*it); code_point += (*it) & 0x3f;
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) return UTF8_OK;
}
code_point = ((code_point << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff); #undef UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) template <typename octet_iterator>
utf_error validate_next(octet_iterator& it, octet_iterator end, uint32_t& code_point)
{
// Save the original value of it so we can go back in case of failure
// Of course, it does not make much sense with i.e. stream iterators
octet_iterator original_it = it;
code_point += (utf8::internal::mask8(*it) << 6) & 0xfff; uint32_t cp = 0;
// Determine the sequence length based on the lead octet
typedef typename std::iterator_traits<octet_iterator>::difference_type octet_difference_type;
const octet_difference_type length = utf8::internal::sequence_length(it);
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) // Get trail octets and calculate the code point
utf_error err = UTF8_OK;
code_point += (*it) & 0x3f; switch (length) {
case 0:
return UTF8_OK; return INVALID_LEAD;
} case 1:
err = utf8::internal::get_sequence_1(it, end, cp);
#undef UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR
template <typename octet_iterator>
utf_error validate_next(octet_iterator& it, octet_iterator end, uint32_t& code_point)
{
// Save the original value of it so we can go back in case of failure
// Of course, it does not make much sense with i.e. stream iterators
octet_iterator original_it = it;
uint32_t cp = 0;
// Determine the sequence length based on the lead octet
typedef typename std::iterator_traits<octet_iterator>::difference_type octet_difference_type;
const octet_difference_type length = utf8::internal::sequence_length(it);
// Get trail octets and calculate the code point
utf_error err = UTF8_OK;
switch (length) {
case 0:
return INVALID_LEAD;
case 1:
err = utf8::internal::get_sequence_1(it, end, cp);
break;
case 2:
err = utf8::internal::get_sequence_2(it, end, cp);
break; break;
case 3: case 2:
err = utf8::internal::get_sequence_3(it, end, cp); err = utf8::internal::get_sequence_2(it, end, cp);
break; break;
case 4: case 3:
err = utf8::internal::get_sequence_4(it, end, cp); err = utf8::internal::get_sequence_3(it, end, cp);
break; break;
} case 4:
err = utf8::internal::get_sequence_4(it, end, cp);
break;
}
if (err == UTF8_OK) { if (err == UTF8_OK) {
// Decoding succeeded. Now, security checks... // Decoding succeeded. Now, security checks...
if (utf8::internal::is_code_point_valid(cp)) { if (utf8::internal::is_code_point_valid(cp)) {
if (!utf8::internal::is_overlong_sequence(cp, length)){ if (!utf8::internal::is_overlong_sequence(cp, length)){
// Passed! Return here. // Passed! Return here.
code_point = cp; code_point = cp;
++it; ++it;
return UTF8_OK; return UTF8_OK;
}
else
err = OVERLONG_SEQUENCE;
} }
else else
err = INVALID_CODE_POINT; err = OVERLONG_SEQUENCE;
} }
else
// Failure branch - restore the original value of the iterator err = INVALID_CODE_POINT;
it = original_it;
return err;
} }
template <typename octet_iterator> // Failure branch - restore the original value of the iterator
inline utf_error validate_next(octet_iterator& it, octet_iterator end) { it = original_it;
uint32_t ignored; return err;
return utf8::internal::validate_next(it, end, ignored); }
}
template <typename octet_iterator>
inline utf_error validate_next(octet_iterator& it, octet_iterator end) {
uint32_t ignored;
return utf8::internal::validate_next(it, end, ignored);
}
} // namespace internal } // namespace internal
/// The library API - functions intended to be called by the users /// The library API - functions intended to be called by the users
// Byte order mark // Byte order mark
const uint8_t bom[] = {0xef, 0xbb, 0xbf}; const uint8_t bom[] = {0xef, 0xbb, 0xbf};
template <typename octet_iterator> template <typename octet_iterator>
octet_iterator find_invalid(octet_iterator start, octet_iterator end) octet_iterator find_invalid(octet_iterator start, octet_iterator end)
{ {
octet_iterator result = start; octet_iterator result = start;
while (result != end) { while (result != end) {
utf8::internal::utf_error err_code = utf8::internal::validate_next(result, end); utf8::internal::utf_error err_code = utf8::internal::validate_next(result, end);
if (err_code != internal::UTF8_OK) if (err_code != internal::UTF8_OK)
return result; return result;
}
return result;
} }
return result;
}
template <typename octet_iterator> template <typename octet_iterator>
inline bool is_valid(octet_iterator start, octet_iterator end) inline bool is_valid(octet_iterator start, octet_iterator end)
{ {
return (utf8::find_invalid(start, end) == end); return (utf8::find_invalid(start, end) == end);
} }
template <typename octet_iterator> template <typename octet_iterator>
inline bool starts_with_bom (octet_iterator it, octet_iterator end) inline bool starts_with_bom (octet_iterator it, octet_iterator end)
{ {
return ( return (
((it != end) && (utf8::internal::mask8(*it++)) == bom[0]) && ((it != end) && (utf8::internal::mask8(*it++)) == bom[0]) &&
((it != end) && (utf8::internal::mask8(*it++)) == bom[1]) && ((it != end) && (utf8::internal::mask8(*it++)) == bom[1]) &&
((it != end) && (utf8::internal::mask8(*it)) == bom[2]) ((it != end) && (utf8::internal::mask8(*it)) == bom[2])
); );
} }
//Deprecated in release 2.3 //Deprecated in release 2.3
template <typename octet_iterator> template <typename octet_iterator>
inline bool is_bom (octet_iterator it) inline bool is_bom (octet_iterator it)
{ {
return ( return (
(utf8::internal::mask8(*it++)) == bom[0] && (utf8::internal::mask8(*it++)) == bom[0] &&
(utf8::internal::mask8(*it++)) == bom[1] && (utf8::internal::mask8(*it++)) == bom[1] &&
(utf8::internal::mask8(*it)) == bom[2] (utf8::internal::mask8(*it)) == bom[2]
); );
} }
} // namespace utf8 } // namespace utf8
#endif // header guard #endif // header guard

View File

@ -32,195 +32,195 @@ DEALINGS IN THE SOFTWARE.
namespace utf8 namespace utf8
{ {
namespace unchecked namespace unchecked
{ {
template <typename octet_iterator> template <typename octet_iterator>
octet_iterator append(uint32_t cp, octet_iterator result) octet_iterator append(uint32_t cp, octet_iterator result)
{ {
if (cp < 0x80) // one octet if (cp < 0x80) // one octet
*(result++) = static_cast<uint8_t>(cp); *(result++) = static_cast<uint8_t>(cp);
else if (cp < 0x800) { // two octets else if (cp < 0x800) { // two octets
*(result++) = static_cast<uint8_t>((cp >> 6) | 0xc0); *(result++) = static_cast<uint8_t>((cp >> 6) | 0xc0);
*(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
} }
else if (cp < 0x10000) { // three octets else if (cp < 0x10000) { // three octets
*(result++) = static_cast<uint8_t>((cp >> 12) | 0xe0); *(result++) = static_cast<uint8_t>((cp >> 12) | 0xe0);
*(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80);
*(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
} }
else { // four octets else { // four octets
*(result++) = static_cast<uint8_t>((cp >> 18) | 0xf0); *(result++) = static_cast<uint8_t>((cp >> 18) | 0xf0);
*(result++) = static_cast<uint8_t>(((cp >> 12) & 0x3f)| 0x80); *(result++) = static_cast<uint8_t>(((cp >> 12) & 0x3f)| 0x80);
*(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80);
*(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
} }
return result; return result;
} }
template <typename octet_iterator> template <typename octet_iterator>
uint32_t next(octet_iterator& it) uint32_t next(octet_iterator& it)
{ {
uint32_t cp = utf8::internal::mask8(*it); uint32_t cp = utf8::internal::mask8(*it);
typename std::iterator_traits<octet_iterator>::difference_type length = utf8::internal::sequence_length(it); typename std::iterator_traits<octet_iterator>::difference_type length = utf8::internal::sequence_length(it);
switch (length) { switch (length) {
case 1: case 1:
break; break;
case 2: case 2:
it++; it++;
cp = ((cp << 6) & 0x7ff) + ((*it) & 0x3f); cp = ((cp << 6) & 0x7ff) + ((*it) & 0x3f);
break; break;
case 3: case 3:
++it;
cp = ((cp << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff);
++it;
cp += (*it) & 0x3f;
break;
case 4:
++it;
cp = ((cp << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff);
++it;
cp += (utf8::internal::mask8(*it) << 6) & 0xfff;
++it;
cp += (*it) & 0x3f;
break;
}
++it; ++it;
return cp; cp = ((cp << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff);
++it;
cp += (*it) & 0x3f;
break;
case 4:
++it;
cp = ((cp << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff);
++it;
cp += (utf8::internal::mask8(*it) << 6) & 0xfff;
++it;
cp += (*it) & 0x3f;
break;
}
++it;
return cp;
}
template <typename octet_iterator>
uint32_t peek_next(octet_iterator it)
{
return utf8::unchecked::next(it);
}
template <typename octet_iterator>
uint32_t prior(octet_iterator& it)
{
while (utf8::internal::is_trail(*(--it))) ;
octet_iterator temp = it;
return utf8::unchecked::next(temp);
}
// Deprecated in versions that include prior, but only for the sake of consistency (see utf8::previous)
template <typename octet_iterator>
inline uint32_t previous(octet_iterator& it)
{
return utf8::unchecked::prior(it);
}
template <typename octet_iterator, typename distance_type>
void advance (octet_iterator& it, distance_type n)
{
for (distance_type i = 0; i < n; ++i)
utf8::unchecked::next(it);
}
template <typename octet_iterator>
typename std::iterator_traits<octet_iterator>::difference_type
distance (octet_iterator first, octet_iterator last)
{
typename std::iterator_traits<octet_iterator>::difference_type dist;
for (dist = 0; first < last; ++dist)
utf8::unchecked::next(first);
return dist;
}
template <typename u16bit_iterator, typename octet_iterator>
octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result)
{
while (start != end) {
uint32_t cp = utf8::internal::mask16(*start++);
// Take care of surrogate pairs first
if (utf8::internal::is_lead_surrogate(cp)) {
uint32_t trail_surrogate = utf8::internal::mask16(*start++);
cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET;
} }
result = utf8::unchecked::append(cp, result);
}
return result;
}
template <typename octet_iterator> template <typename u16bit_iterator, typename octet_iterator>
uint32_t peek_next(octet_iterator it) u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result)
{ {
return utf8::unchecked::next(it); while (start < end) {
uint32_t cp = utf8::unchecked::next(start);
if (cp > 0xffff) { //make a surrogate pair
*result++ = static_cast<uint16_t>((cp >> 10) + internal::LEAD_OFFSET);
*result++ = static_cast<uint16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN);
} }
else
*result++ = static_cast<uint16_t>(cp);
}
return result;
}
template <typename octet_iterator> template <typename octet_iterator, typename u32bit_iterator>
uint32_t prior(octet_iterator& it) octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result)
{ {
while (utf8::internal::is_trail(*(--it))) ; while (start != end)
octet_iterator temp = it; result = utf8::unchecked::append(*(start++), result);
return utf8::unchecked::next(temp);
}
// Deprecated in versions that include prior, but only for the sake of consistency (see utf8::previous) return result;
template <typename octet_iterator> }
inline uint32_t previous(octet_iterator& it)
{
return utf8::unchecked::prior(it);
}
template <typename octet_iterator, typename distance_type> template <typename octet_iterator, typename u32bit_iterator>
void advance (octet_iterator& it, distance_type n) u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result)
{ {
for (distance_type i = 0; i < n; ++i) while (start < end)
utf8::unchecked::next(it); (*result++) = utf8::unchecked::next(start);
}
template <typename octet_iterator> return result;
typename std::iterator_traits<octet_iterator>::difference_type }
distance (octet_iterator first, octet_iterator last)
{
typename std::iterator_traits<octet_iterator>::difference_type dist;
for (dist = 0; first < last; ++dist)
utf8::unchecked::next(first);
return dist;
}
template <typename u16bit_iterator, typename octet_iterator> // The iterator class
octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) template <typename octet_iterator>
{ class iterator : public std::iterator <std::bidirectional_iterator_tag, uint32_t> {
while (start != end) { octet_iterator it;
uint32_t cp = utf8::internal::mask16(*start++); public:
// Take care of surrogate pairs first iterator () {};
if (utf8::internal::is_lead_surrogate(cp)) { explicit iterator (const octet_iterator& octet_it): it(octet_it) {}
uint32_t trail_surrogate = utf8::internal::mask16(*start++); // the default "big three" are OK
cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; octet_iterator base () const { return it; }
} uint32_t operator * () const
result = utf8::unchecked::append(cp, result); {
} octet_iterator temp = it;
return result; return utf8::unchecked::next(temp);
} }
bool operator == (const iterator& rhs) const
{
return (it == rhs.it);
}
bool operator != (const iterator& rhs) const
{
return !(operator == (rhs));
}
iterator& operator ++ ()
{
::std::advance(it, utf8::internal::sequence_length(it));
return *this;
}
iterator operator ++ (int)
{
iterator temp = *this;
::std::advance(it, utf8::internal::sequence_length(it));
return temp;
}
iterator& operator -- ()
{
utf8::unchecked::prior(it);
return *this;
}
iterator operator -- (int)
{
iterator temp = *this;
utf8::unchecked::prior(it);
return temp;
}
}; // class iterator
template <typename u16bit_iterator, typename octet_iterator> } // namespace utf8::unchecked
u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result)
{
while (start < end) {
uint32_t cp = utf8::unchecked::next(start);
if (cp > 0xffff) { //make a surrogate pair
*result++ = static_cast<uint16_t>((cp >> 10) + internal::LEAD_OFFSET);
*result++ = static_cast<uint16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN);
}
else
*result++ = static_cast<uint16_t>(cp);
}
return result;
}
template <typename octet_iterator, typename u32bit_iterator>
octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result)
{
while (start != end)
result = utf8::unchecked::append(*(start++), result);
return result;
}
template <typename octet_iterator, typename u32bit_iterator>
u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result)
{
while (start < end)
(*result++) = utf8::unchecked::next(start);
return result;
}
// The iterator class
template <typename octet_iterator>
class iterator : public std::iterator <std::bidirectional_iterator_tag, uint32_t> {
octet_iterator it;
public:
iterator () {};
explicit iterator (const octet_iterator& octet_it): it(octet_it) {}
// the default "big three" are OK
octet_iterator base () const { return it; }
uint32_t operator * () const
{
octet_iterator temp = it;
return utf8::unchecked::next(temp);
}
bool operator == (const iterator& rhs) const
{
return (it == rhs.it);
}
bool operator != (const iterator& rhs) const
{
return !(operator == (rhs));
}
iterator& operator ++ ()
{
::std::advance(it, utf8::internal::sequence_length(it));
return *this;
}
iterator operator ++ (int)
{
iterator temp = *this;
::std::advance(it, utf8::internal::sequence_length(it));
return temp;
}
iterator& operator -- ()
{
utf8::unchecked::prior(it);
return *this;
}
iterator operator -- (int)
{
iterator temp = *this;
utf8::unchecked::prior(it);
return temp;
}
}; // class iterator
} // namespace utf8::unchecked
} // namespace utf8 } // namespace utf8

View File

@ -22,17 +22,18 @@
bool isEmpty(Int8*, size_t); bool isEmpty(Int8*, size_t);
unsigned short swapU16(unsigned short val ); unsigned short swapU16(unsigned short val );
short swap16 (short val ); short swap16 (short val );
unsigned int swapU32(unsigned int val); unsigned int swapU32(unsigned int val);
int swap32 (int val ); int swap32 (int val );
long long swap64 (long long val); long long swap64 (long long val);
float swapFloat(float val); float swapFloat(float val);
double swapDouble(double val); double swapDouble(double val);
bool isSystemBigEndian(); bool isSystemBigEndian();
void fillRandom(Uint8 * rndArea, Uint8 count); void fillRandom(Uint8 * rndArea, Uint8 count);
void yaz0Decode(Uint8* src, Uint8* dst, Uint32 uncompressedSize);
#endif #endif

View File

@ -61,7 +61,7 @@ OUTPUT_DIRECTORY = doc
# source files, where putting all generated files in the same directory would # source files, where putting all generated files in the same directory would
# otherwise cause performance problems for the file system. # otherwise cause performance problems for the file system.
CREATE_SUBDIRS = NO CREATE_SUBDIRS = Yes
# The OUTPUT_LANGUAGE tag is used to specify the language in which all # The OUTPUT_LANGUAGE tag is used to specify the language in which all
# documentation generated by doxygen is written. Doxygen will use this # documentation generated by doxygen is written. Doxygen will use this
@ -1586,7 +1586,7 @@ INCLUDE_FILE_PATTERNS =
# undefined via #undef or recursively expanded use the := operator # undefined via #undef or recursively expanded use the := operator
# instead of the = operator. # instead of the = operator.
PREDEFINED = PREDEFINED = __DOXYGEN_IGNORE__
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
# this tag can be used to specify a list of macro names that should be expanded. # this tag can be used to specify a list of macro names that should be expanded.

View File

@ -1,7 +1,7 @@
CONFIG += staticlib CONFIG += staticlib
TEMPLATE=lib TEMPLATE=lib
TARGET=zelda TARGET=zelda
QMAKE_CXXFLAGS = -std=c++11 QMAKE_CXXFLAGS += -std=c++0x
INCLUDEPATH += include INCLUDEPATH += include
HEADERS += \ HEADERS += \
@ -35,7 +35,13 @@ HEADERS += \
include/ALTTPFileWriter.hpp \ include/ALTTPFileWriter.hpp \
include/ALTTPFileReader.hpp \ include/ALTTPFileReader.hpp \
include/ALTTPFile.hpp \ include/ALTTPFile.hpp \
include/ALTTPEnums.hpp include/ALTTPEnums.hpp \
include/MCFileReader.hpp \
include/MCFile.hpp \
include/MCFileWriter.hpp \
include/ZQuestFileWriter.hpp \
include/ZQuestFileReader.hpp \
include/ZQuest.hpp
SOURCES += \ SOURCES += \
src/utility.cpp \ src/utility.cpp \
@ -53,12 +59,19 @@ SOURCES += \
src/ec.cpp \ src/ec.cpp \
src/md5.c \ src/md5.c \
src/sha1.cpp \ src/sha1.cpp \
src/ALTTPStructs.cpp \
src/ALTTPQuest.cpp \ src/ALTTPQuest.cpp \
src/ALTTPFileWriter.cpp \ src/ALTTPFileWriter.cpp \
src/ALTTPFileReader.cpp \ src/ALTTPFileReader.cpp \
src/ALTTPFile.cpp src/ALTTPFile.cpp \
src/MCFileReader.cpp \
src/MCFile.cpp \
src/MCFileWriter.cpp \
src/RARCFileReader.cpp \
src/RARCFileEntry.cpp \
src/ZQuestFileWriter.cpp \
src/ZQuestFileReader.cpp \
src/ZQuest.cpp
system("exec doxygen libzelda.conf") system("exec doxygen libzelda.conf")
system("cd doc/latex && make") #system("cd doc/latex && make")
system("cd ../../") system("cd ../../")

View File

@ -16,8 +16,10 @@
#include "ALTTPFile.hpp" #include "ALTTPFile.hpp"
#include "ALTTPQuest.hpp" #include "ALTTPQuest.hpp"
#include <InvalidOperationException.hpp> #include "InvalidOperationException.hpp"
namespace zelda
{
ALTTPFile::ALTTPFile() ALTTPFile::ALTTPFile()
{} {}
@ -51,3 +53,4 @@ Uint32 ALTTPFile::questCount() const
{ {
return m_quests.size(); return m_quests.size();
} }
} // zelda

View File

@ -18,6 +18,9 @@
#include "ALTTPQuest.hpp" #include "ALTTPQuest.hpp"
#include <iostream> #include <iostream>
namespace zelda
{
ALTTPFileReader::ALTTPFileReader(Uint8* data, Uint64 length) ALTTPFileReader::ALTTPFileReader(Uint8* data, Uint64 length)
: BinaryReader(data, length) : BinaryReader(data, length)
{ {
@ -35,6 +38,7 @@ ALTTPFile* ALTTPFileReader::readFile()
for (Uint32 i = 0; i < 6; i++) for (Uint32 i = 0; i < 6; i++)
{ {
// Temporary values to use for each save
ALTTPQuest* quest = new ALTTPQuest(); ALTTPQuest* quest = new ALTTPQuest();
std::vector<ALTTPRoomFlags*> roomFlags; std::vector<ALTTPRoomFlags*> roomFlags;
std::vector<ALTTPOverworldEvent*> owEvents; std::vector<ALTTPOverworldEvent*> owEvents;
@ -192,35 +196,37 @@ ALTTPRoomFlags* ALTTPFileReader::readRoomFlags()
ALTTPOverworldEvent* ALTTPFileReader::readOverworldEvent() ALTTPOverworldEvent* ALTTPFileReader::readOverworldEvent()
{ {
ALTTPOverworldEvent* event = new ALTTPOverworldEvent; ALTTPOverworldEvent* event = new ALTTPOverworldEvent;
event->Unused1 = readBit(); event->Unused1 = readBit();
event->HeartPiece= readBit(); event->HeartPiece = readBit();
event->Overlay= readBit(); event->Overlay = readBit();
event->Unused2= readBit(); event->Unused2 = readBit();
event->Unused3= readBit(); event->Unused3 = readBit();
event->Unused4= readBit(); event->Unused4 = readBit();
event->Set= readBit(); event->Set = readBit();
event->Unused5= readBit(); event->Unused5 = readBit();
return event; return event;
} }
ALTTPDungeonItemFlags ALTTPFileReader::readDungeonFlags() ALTTPDungeonItemFlags ALTTPFileReader::readDungeonFlags()
{ {
ALTTPDungeonItemFlags flags; ALTTPDungeonItemFlags flags;
flags.Unused1 = readBit(); flags.Unused1 = readBit();
flags.GanonsTower = readBit(); flags.GanonsTower = readBit();
flags.TurtleRock = readBit(); flags.TurtleRock = readBit();
flags.GargoylesDomain = readBit(); flags.GargoylesDomain = readBit();
flags.TowerOfHera = readBit(); flags.TowerOfHera = readBit();
flags.IcePalace = readBit(); flags.IcePalace = readBit();
flags.SkullWoods = readBit(); flags.SkullWoods = readBit();
flags.MiseryMire = readBit(); flags.MiseryMire = readBit();
flags.DarkPalace = readBit(); flags.DarkPalace = readBit();
flags.SwampPalace = readBit(); flags.SwampPalace = readBit();
flags.HyruleCastle2 = readBit(); flags.HyruleCastle2 = readBit();
flags.DesertPalace = readBit(); flags.DesertPalace = readBit();
flags.EasternPalace = readBit(); flags.EasternPalace = readBit();
flags.HyruleCastle = readBit(); flags.HyruleCastle = readBit();
flags.SewerPassage = readBit(); flags.SewerPassage = readBit();
return flags; return flags;
} }
} // zelda

View File

@ -18,6 +18,9 @@
#include "ALTTPQuest.hpp" #include "ALTTPQuest.hpp"
#include <iostream> #include <iostream>
namespace zelda
{
ALTTPFileWriter::ALTTPFileWriter(Uint8* data, Uint64 length) ALTTPFileWriter::ALTTPFileWriter(Uint8* data, Uint64 length)
: BinaryWriter(data, length) : BinaryWriter(data, length)
{ {
@ -180,9 +183,36 @@ void ALTTPFileWriter::writeDungeonItems(ALTTPDungeonItemFlags flags)
Uint16 ALTTPFileWriter::calculateChecksum(Uint32 game) Uint16 ALTTPFileWriter::calculateChecksum(Uint32 game)
{ {
Uint16 sum = 0x5a5a; /*
for (Uint32 i = 0; i < 0x4FE; i += 2) * ALTTP's checksum is very basic
sum -= *(Uint16*)(m_data + (i + (0x500 * game))); * It adds each word up and then subtracts the sum from 0x5a5a
* The number seems pretty arbitrary, but it enables the game to differentiate
* it from a number that just happens to equal the sum outright, preventing "false positives."
*
* Ignoring the algorithm for figuring out it's position in the buffer the equation is basically:
* s = s + w
* s = (0x5a5a - s);
* s == sum
* w == current word
*
* For those who don't know a word is a two byte pair, i.e 0xFF and 0xFE constitutes a word.
*/
return sum; // First we start at 0
Uint16 sum = 0;
for (Uint32 i = 0; i < 0x4FE; i += 2)
// Add each word one by one
sum += *(Uint16*)(m_data + (i + (0x500 * game)));
// Subtract it from 0x5a5a to get our true checksum
return (0x5a5a - sum);
/*
* There is one caveat to this algorithm however,
* It makes it difficult to manually edit this in a hex editor since it's not a common
* algorithm and most hexeditor with built in checksum calculators won't have it, however it's
* it's extremely basic, making it a non-issue really.
*/
} }
} // zelda

View File

@ -17,6 +17,9 @@
#include "InvalidOperationException.hpp" #include "InvalidOperationException.hpp"
#include <iostream> #include <iostream>
namespace zelda
{
ALTTPQuest::ALTTPQuest() ALTTPQuest::ALTTPQuest()
{ {
} }
@ -676,3 +679,5 @@ Uint16 ALTTPQuest::checksum() const
{ {
return m_checksum; return m_checksum;
} }
} // zelda

View File

@ -24,6 +24,11 @@
#include <vector> #include <vector>
#include <iostream> #include <iostream>
namespace zelda
{
namespace io
{
BinaryReader::BinaryReader(const Stream& stream) : BinaryReader::BinaryReader(const Stream& stream) :
Stream(stream) Stream(stream)
{ {
@ -67,7 +72,7 @@ BinaryReader::BinaryReader(const std::string& filename)
break; break;
done += blocksize; done += blocksize;
}while (done < length); } while (done < length);
fclose(in); fclose(in);
m_length = length; m_length = length;
@ -85,7 +90,6 @@ void BinaryReader::writeBytes(Int8*, Int64)
throw IOException("BinaryReader::writeBytes() -> Stream not open for writing"); throw IOException("BinaryReader::writeBytes() -> Stream not open for writing");
} }
Int16 BinaryReader::readInt16() Int16 BinaryReader::readInt16()
{ {
if (m_bitPosition > 0) if (m_bitPosition > 0)
@ -99,7 +103,7 @@ Int16 BinaryReader::readInt16()
Int16 ret = *(Int16*)(m_data + m_position); Int16 ret = *(Int16*)(m_data + m_position);
m_position += 2; m_position += 2;
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
ret = swap16(ret); ret = swap16(ret);
return ret; return ret;
} }
@ -116,7 +120,7 @@ Uint16 BinaryReader::readUInt16()
Uint16 ret = *(Uint16*)(m_data + m_position); Uint16 ret = *(Uint16*)(m_data + m_position);
m_position += 2; m_position += 2;
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
ret = swapU16(ret); ret = swapU16(ret);
return ret; return ret;
@ -134,7 +138,7 @@ Int32 BinaryReader::readInt32()
Int32 ret = *(Int32*)(m_data + m_position); Int32 ret = *(Int32*)(m_data + m_position);
m_position += 4; m_position += 4;
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
ret = swap32(ret); ret = swap32(ret);
return ret; return ret;
} }
@ -152,7 +156,7 @@ Uint32 BinaryReader::readUInt32()
Uint32 ret = *(Uint32*)(m_data + m_position); Uint32 ret = *(Uint32*)(m_data + m_position);
m_position += 4; m_position += 4;
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
ret = swapU32(ret); ret = swapU32(ret);
return ret; return ret;
} }
@ -170,7 +174,7 @@ Int64 BinaryReader::readInt64()
Int64 ret = *(Int64*)(m_data + m_position); Int64 ret = *(Int64*)(m_data + m_position);
m_position += 8; m_position += 8;
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
ret = swap64(ret); ret = swap64(ret);
return ret; return ret;
} }
@ -187,7 +191,7 @@ Uint64 BinaryReader::readUInt64()
Uint64 ret = *(Uint64*)(m_data + m_position); Uint64 ret = *(Uint64*)(m_data + m_position);
m_position += 8; m_position += 8;
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
ret = swap64(ret); ret = swap64(ret);
return ret; return ret;
} }
@ -205,7 +209,7 @@ float BinaryReader::readFloat()
float ret = *(float*)(m_data + m_position); float ret = *(float*)(m_data + m_position);
m_position += 4; m_position += 4;
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
ret = swapFloat(ret); ret = swapFloat(ret);
return ret; return ret;
} }
@ -223,7 +227,7 @@ double BinaryReader::readDouble()
double ret = *(double*)(m_data + m_position); double ret = *(double*)(m_data + m_position);
m_position += 8; m_position += 8;
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
ret = swapDouble(ret); ret = swapDouble(ret);
return ret; return ret;
@ -262,8 +266,23 @@ std::string BinaryReader::readUnicode()
return ret; return ret;
} }
std::string BinaryReader::readString()
{
std::string ret = "";
Uint8 chr = readByte();
while (chr != 0)
{
ret += chr;
chr = readByte();
}
return ret;
}
bool BinaryReader::isOpenForWriting() bool BinaryReader::isOpenForWriting()
{ {
return false; return false;
} }
}
}

View File

@ -24,6 +24,10 @@
#include <vector> #include <vector>
#include <iostream> #include <iostream>
namespace zelda
{
namespace io
{
BinaryWriter::BinaryWriter(const Uint8* data, Uint64 length) BinaryWriter::BinaryWriter(const Uint8* data, Uint64 length)
: Stream(data, length) : Stream(data, length)
@ -72,7 +76,6 @@ void BinaryWriter::save(const std::string& filename)
break; break;
done += blocksize; done += blocksize;
std::cout << "Wrote " << done << " bytes" << std::endl;
}while (done < m_length); }while (done < m_length);
fclose(out); fclose(out);
@ -101,7 +104,7 @@ void BinaryWriter::writeInt16(Int16 val)
else if (m_position > m_length) else if (m_position > m_length)
throw IOException("BinaryWriter::WriteInt16() -> Position outside stream bounds"); throw IOException("BinaryWriter::WriteInt16() -> Position outside stream bounds");
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
val = swap16(val); val = swap16(val);
*(Int16*)(m_data + m_position) = val; *(Int16*)(m_data + m_position) = val;
@ -122,7 +125,7 @@ void BinaryWriter::writeUInt16(Uint16 val)
throw IOException("BinaryWriter::WriteUInt16() -> Position outside stream bounds"); throw IOException("BinaryWriter::WriteUInt16() -> Position outside stream bounds");
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
val = swapU16(val); val = swapU16(val);
*(Uint16*)(m_data + m_position) = val; *(Uint16*)(m_data + m_position) = val;
@ -142,7 +145,7 @@ void BinaryWriter::writeInt32(Int32 val)
else if (m_position > m_length) else if (m_position > m_length)
throw IOException("BinaryWriter::WriteInt32() -> Position outside stream bounds"); throw IOException("BinaryWriter::WriteInt32() -> Position outside stream bounds");
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
val = swap32(val); val = swap32(val);
*(Int32*)(m_data + m_position) = val; *(Int32*)(m_data + m_position) = val;
@ -162,7 +165,7 @@ void BinaryWriter::writeUInt32(Uint32 val)
else if (m_position > m_length) else if (m_position > m_length)
throw IOException("BinaryWriter::WriteUInt32() -> Position outside stream bounds"); throw IOException("BinaryWriter::WriteUInt32() -> Position outside stream bounds");
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
val = swap32(val); val = swap32(val);
*(Uint32*)(m_data + m_position) = val; *(Uint32*)(m_data + m_position) = val;
@ -183,7 +186,7 @@ void BinaryWriter::writeInt64(Int64 val)
throw IOException("BinaryWriter::WriteInt64() -> Position outside stream bounds"); throw IOException("BinaryWriter::WriteInt64() -> Position outside stream bounds");
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
val = swap64(val); val = swap64(val);
*(Int64*)(m_data + m_position) = val; *(Int64*)(m_data + m_position) = val;
@ -203,7 +206,7 @@ void BinaryWriter::writeUInt64(Uint64 val)
else if (m_position > m_length) else if (m_position > m_length)
throw IOException("BinaryWriter::WriteUInt64() -> Position outside stream bounds"); throw IOException("BinaryWriter::WriteUInt64() -> Position outside stream bounds");
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
val = swap64(val); val = swap64(val);
*(Uint64*)(m_data + m_position) = val; *(Uint64*)(m_data + m_position) = val;
@ -223,7 +226,7 @@ void BinaryWriter::writeFloat(float val)
else if (m_position > m_length) else if (m_position > m_length)
throw IOException("BinaryWriter::WriteFloat() -> Position outside stream bounds"); throw IOException("BinaryWriter::WriteFloat() -> Position outside stream bounds");
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
val = swapFloat(val); val = swapFloat(val);
*(float*)(m_data + m_position) = val; *(float*)(m_data + m_position) = val;
@ -243,7 +246,7 @@ void BinaryWriter::writeDouble(double val)
else if (m_position > m_length) else if (m_position > m_length)
throw IOException("BinaryWriter::WriteDouble() -> Position outside stream bounds"); throw IOException("BinaryWriter::WriteDouble() -> Position outside stream bounds");
if ((!isSystemBigEndian() && m_endian == Stream::BigEndian) || (isSystemBigEndian() && m_endian == Stream::LittleEndian)) if ((!isSystemBigEndian() && m_endian == BigEndian) || (isSystemBigEndian() && m_endian == LittleEndian))
val = swapDouble(val); val = swapDouble(val);
*(double*)(m_data + m_position)= val; *(double*)(m_data + m_position)= val;
@ -287,4 +290,5 @@ bool BinaryWriter::isOpenForReading()
{ {
return false; return false;
} }
} // io
} // zelda

25
src/MCFile.cpp Normal file
View File

@ -0,0 +1,25 @@
// This file is part of libZelda.
//
// libZelda is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libZelda is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libZelda. If not, see <http://www.gnu.org/licenses/>
#include "MCFile.hpp"
namespace zelda
{
MCFile::MCFile()
{
}
} // zelda

31
src/MCFileReader.cpp Normal file
View File

@ -0,0 +1,31 @@
// This file is part of libZelda.
//
// libZelda is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libZelda is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libZelda. If not, see <http://www.gnu.org/licenses/>
#include "MCFileReader.hpp"
namespace zelda
{
MCFileReader::MCFileReader(Uint8* data, Uint64 length)
: BinaryReader(data, length)
{
}
MCFileReader::MCFileReader(const std::string& filename)
: BinaryReader(filename)
{
}
} // zelda

96
src/MCFileWriter.cpp Normal file
View File

@ -0,0 +1,96 @@
// This file is part of libZelda.
//
// libZelda is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libZelda is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libZelda. If not, see <http://www.gnu.org/licenses/>
#include "MCFileWriter.hpp"
namespace zelda
{
MCFileWriter::MCFileWriter(Uint8* data, Uint64 length)
: io::BinaryWriter(data, length)
{
}
MCFileWriter::MCFileWriter(const std::string& filename)
: io::BinaryWriter(filename)
{
}
// TODO: Check the implementation, it seems to work fine, however it's not exactly correct,
// looking at the disassembly, MC seems to do some weird checking that isn't being done with this solution
// need to figure out what it's doing and whether it's relevant to the checksum.
Uint16 MCFileWriter::calculateSlotChecksum(Uint32 game)
{
Uint16 first = calculateChecksum((m_data + 0x34 + (0x10 * game)), 4);
Uint16 second = calculateChecksum((m_data + 0x80 + (0x500 * game)), 0x500);
first = (first + second) & 0xFFFF;
Uint16 result = first << 16;
second = ~first&0xFFFF;
second += 1;
result += second;
return result;
}
Uint16 MCFileWriter::calculateChecksum(Uint8 *data, Uint32 length)
{
Uint16 sum = 0;
int i = length;
for (Uint32 j = 0; j < length; j += 2)
{
sum += *(Uint16*)(data + j) ^ i;
i -= 2;
}
sum &= 0xFFFF;
return sum;
}
// TODO: Rewrite this to be more optimized, the current solution takes quite a few cycles
Uint8* MCFileWriter::reverse(Uint8* data, Uint32 length)
{
Uint32 a = 0;
Uint32 swap;
for (;a<--length; a++)
{
swap = data[a];
data[a] = data[length];
data[length] = swap;
}
return data;
}
// TODO: Rewrite this to be more optimized, unroll more??
void MCFileWriter::unscramble()
{
if (!m_data)
return;
for (Uint32 i = 0; i < m_length; i += 4)
{
Uint32 block1 = *(Uint32*)reverse((m_data + i), 4);
Uint32 block2 = *(Uint32*)reverse((m_data + i + 4), 4);
*(Uint32*)(m_data + i) = block2;
*(Uint32*)(m_data + i + 4) = block1;
}
}
} // zelda

View File

@ -19,6 +19,10 @@
#include <string.h> #include <string.h>
#include <sstream> #include <sstream>
namespace zelda
{
namespace io
{
const Uint32 Stream::BLOCKSZ = 512; const Uint32 Stream::BLOCKSZ = 512;
@ -26,7 +30,7 @@ Stream::Stream() :
m_bitPosition(0), m_bitPosition(0),
m_position(0), m_position(0),
m_length(0), m_length(0),
m_endian(Stream::LittleEndian), m_endian(LittleEndian),
m_data(NULL), m_data(NULL),
m_autoResize(true) m_autoResize(true)
{} {}
@ -34,7 +38,7 @@ Stream::Stream() :
Stream::Stream(const Uint8* data, Uint64 length) : Stream::Stream(const Uint8* data, Uint64 length) :
m_bitPosition(0), m_bitPosition(0),
m_position(0), m_position(0),
m_endian(Stream::LittleEndian), m_endian(LittleEndian),
m_autoResize(true) m_autoResize(true)
{ {
if (length <= 0) if (length <= 0)
@ -97,6 +101,11 @@ void Stream::writeBit(bool val)
} }
} }
void Stream::writeUByte(Uint8 byte)
{
writeByte((Int8)byte);
}
void Stream::writeByte(Int8 byte) void Stream::writeByte(Int8 byte)
{ {
if (m_bitPosition > 0) if (m_bitPosition > 0)
@ -113,6 +122,11 @@ void Stream::writeByte(Int8 byte)
m_position++; m_position++;
} }
void Stream::writeUBytes(Uint8* data, Int64 length)
{
writeBytes((Int8*)data, length);
}
void Stream::writeBytes(Int8* data, Int64 length) void Stream::writeBytes(Int8* data, Int64 length)
{ {
if (m_bitPosition > 0) if (m_bitPosition > 0)
@ -302,7 +316,10 @@ void Stream::setEndianess(Endian endian)
m_endian = endian; m_endian = endian;
} }
Stream::Endian Stream::endianness() const Endian Stream::endian() const
{ {
return m_endian; return m_endian;
} }
} // io
} // zelda

View File

@ -19,6 +19,10 @@
#include "InvalidOperationException.hpp" #include "InvalidOperationException.hpp"
#include "IOException.hpp" #include "IOException.hpp"
namespace zelda
{
namespace io
{
TextStream::TextStream(const std::string& filename, TextMode fileMode, AccessMode accessMode) : TextStream::TextStream(const std::string& filename, TextMode fileMode, AccessMode accessMode) :
m_filename(filename), m_filename(filename),
m_textmode(fileMode), m_textmode(fileMode),
@ -256,3 +260,7 @@ void TextStream::loadLines()
m_lines.push_back(line); m_lines.push_back(line);
} }
} }
} // io
} // zelda

View File

@ -17,6 +17,9 @@
#include <utility.hpp> #include <utility.hpp>
#include <string.h> #include <string.h>
namespace zelda
{
WiiImage::WiiImage(Uint32 width, Uint32 height, Uint8* data) : WiiImage::WiiImage(Uint32 width, Uint32 height, Uint8* data) :
m_width(width), m_width(width),
m_height(height), m_height(height),
@ -178,3 +181,4 @@ Uint32 WiiBanner::flags() const
return m_flags; return m_flags;
} }
} // zelda

View File

@ -15,6 +15,11 @@
#include "WiiFile.hpp" #include "WiiFile.hpp"
namespace zelda
{
//! TODO: Remove this?
WiiFile::WiiFile() : WiiFile::WiiFile() :
m_permissions(WiiFile::GroupRW|WiiFile::OtherRW|WiiFile::OwnerRW), m_permissions(WiiFile::GroupRW|WiiFile::OtherRW|WiiFile::OwnerRW),
m_attributes(0), m_attributes(0),
@ -128,3 +133,4 @@ bool WiiFile::isFile() const
return (m_type == WiiFile::File); return (m_type == WiiFile::File);
} }
} // zelda

View File

@ -21,7 +21,7 @@
#include "IOException.hpp" #include "IOException.hpp"
#include "aes.h" #include "aes.h"
#include "ec.h" #include "ec.h"
#include <utility.hpp> #include "utility.hpp"
#include "md5.h" #include "md5.h"
#include "sha1.h" #include "sha1.h"
@ -33,6 +33,9 @@
#include <iomanip> #include <iomanip>
namespace zelda
{
WiiSave::WiiSave() WiiSave::WiiSave()
: m_banner(NULL) : m_banner(NULL)
{ {
@ -79,3 +82,5 @@ WiiBanner* WiiSave::banner() const
{ {
return m_banner; return m_banner;
} }
} // zelda

View File

@ -27,6 +27,8 @@
#include <IOException.hpp> #include <IOException.hpp>
#include <string.h> #include <string.h>
namespace zelda
{
const Uint8 SD_KEY[16] = {0xab, 0x01, 0xb9, 0xd8, 0xe1, 0x62, 0x2b, 0x08, 0xaf, 0xba, 0xd8, 0x4d, 0xbf, 0xc2, 0xa5, 0x5d}; const Uint8 SD_KEY[16] = {0xab, 0x01, 0xb9, 0xd8, 0xe1, 0x62, 0x2b, 0x08, 0xaf, 0xba, 0xd8, 0x4d, 0xbf, 0xc2, 0xa5, 0x5d};
const Uint8 SD_IV[16] = {0x21, 0x67, 0x12, 0xe6, 0xaa, 0x1f, 0x68, 0x9f, 0x95, 0xc5, 0xa2, 0x23, 0x24, 0xdc, 0x6a, 0x98}; const Uint8 SD_IV[16] = {0x21, 0x67, 0x12, 0xe6, 0xaa, 0x1f, 0x68, 0x9f, 0x95, 0xc5, 0xa2, 0x23, 0x24, 0xdc, 0x6a, 0x98};
@ -288,3 +290,5 @@ void WiiSaveReader::readCerts(Uint32 totalSize)
check_ec(ngCert, apCert, sig, hash2); check_ec(ngCert, apCert, sig, hash2);
} }
} // zelda

View File

@ -36,6 +36,9 @@
#include <iomanip> #include <iomanip>
namespace zelda
{
const Uint8 SD_KEY[16] = {0xab, 0x01, 0xb9, 0xd8, 0xe1, 0x62, 0x2b, 0x08, 0xaf, 0xba, 0xd8, 0x4d, 0xbf, 0xc2, 0xa5, 0x5d}; const Uint8 SD_KEY[16] = {0xab, 0x01, 0xb9, 0xd8, 0xe1, 0x62, 0x2b, 0x08, 0xaf, 0xba, 0xd8, 0x4d, 0xbf, 0xc2, 0xa5, 0x5d};
const Uint8 SD_IV[16] = {0x21, 0x67, 0x12, 0xe6, 0xaa, 0x1f, 0x68, 0x9f, 0x95, 0xc5, 0xa2, 0x23, 0x24, 0xdc, 0x6a, 0x98}; const Uint8 SD_IV[16] = {0x21, 0x67, 0x12, 0xe6, 0xaa, 0x1f, 0x68, 0x9f, 0x95, 0xc5, 0xa2, 0x23, 0x24, 0xdc, 0x6a, 0x98};
const Uint8 MD5_BLANKER[16] = {0x0e, 0x65, 0x37, 0x81, 0x99, 0xbe, 0x45, 0x17, 0xab, 0x06, 0xec, 0x22, 0x45, 0x1a, 0x57, 0x93}; const Uint8 MD5_BLANKER[16] = {0x0e, 0x65, 0x37, 0x81, 0x99, 0xbe, 0x45, 0x17, 0xab, 0x06, 0xec, 0x22, 0x45, 0x1a, 0x57, 0x93};
@ -44,7 +47,7 @@ WiiSaveWriter::WiiSaveWriter(const std::string &filename)
: BinaryWriter(filename) : BinaryWriter(filename)
{ {
this->setAutoResizing(true); this->setAutoResizing(true);
this->setEndianess(Stream::BigEndian); this->setEndianess(BigEndian);
} }
@ -89,7 +92,7 @@ bool WiiSaveWriter::writeSave(WiiSave *save, Uint8 *macAddress, Uint32 ngId, Uin
void WiiSaveWriter::writeBanner(WiiBanner *banner) void WiiSaveWriter::writeBanner(WiiBanner *banner)
{ {
this->setEndianess(Stream::BigEndian); this->setEndianess(BigEndian);
this->setAutoResizing(true); this->setAutoResizing(true);
this->writeInt64(banner->gameID()); this->writeInt64(banner->gameID());
this->writeInt32((0x60a0+0x1200)*banner->icons().size()); this->writeInt32((0x60a0+0x1200)*banner->icons().size());
@ -249,3 +252,5 @@ void WiiSaveWriter::writeCerts(Uint32 filesSize, Uint32 ngId, Uint8 *ngPriv, Uin
this->writeBytes((Int8*)ngCert, 0x180); this->writeBytes((Int8*)ngCert, 0x180);
this->writeBytes((Int8*)apCert, 0x180); this->writeBytes((Int8*)apCert, 0x180);
} }
} // zelda

140
src/aes.c
View File

@ -126,7 +126,7 @@ void gentables(void)
int i; int i;
u8 y,b[4]; u8 y,b[4];
/* use 3 as primitive root to generate power and log tables */ /* use 3 as primitive root to generate power and log tables */
ltab[0]=0; ltab[0]=0;
ptab[0]=1; ltab[1]=0; ptab[0]=1; ltab[1]=0;
@ -137,7 +137,7 @@ void gentables(void)
ltab[ptab[i]]=i; ltab[ptab[i]]=i;
} }
/* affine transformation:- each bit is xored with itself shifted one bit */ /* affine transformation:- each bit is xored with itself shifted one bit */
fbsub[0]=0x63; fbsub[0]=0x63;
rbsub[0x63]=0; rbsub[0x63]=0;
@ -153,7 +153,7 @@ void gentables(void)
y=xtime(y); y=xtime(y);
} }
/* calculate forward and reverse tables */ /* calculate forward and reverse tables */
for (i=0;i<256;i++) for (i=0;i<256;i++)
{ {
y=fbsub[i]; y=fbsub[i];
@ -170,16 +170,16 @@ void gentables(void)
void gkey(int nb,int nk,u8 *key) void gkey(int nb,int nk,u8 *key)
{ /* blocksize=32*nb bits. Key=32*nk bits */ { /* blocksize=32*nb bits. Key=32*nk bits */
/* currently nb,bk = 4, 6 or 8 */ /* currently nb,bk = 4, 6 or 8 */
/* key comes as 4*Nk bytes */ /* key comes as 4*Nk bytes */
/* Key Scheduler. Create expanded encryption key */ /* Key Scheduler. Create expanded encryption key */
int i,j,k,m,N; int i,j,k,m,N;
int C1,C2,C3; int C1,C2,C3;
u32 CipherKey[8]; u32 CipherKey[8];
Nb=nb; Nk=nk; Nb=nb; Nk=nk;
/* Nr is number of rounds */ /* Nr is number of rounds */
if (Nb>=Nk) Nr=6+Nb; if (Nb>=Nk) Nr=6+Nb;
else Nr=6+Nk; else Nr=6+Nk;
@ -187,7 +187,7 @@ void gkey(int nb,int nk,u8 *key)
if (Nb<8) { C2=2; C3=3; } if (Nb<8) { C2=2; C3=3; }
else { C2=3; C3=4; } else { C2=3; C3=4; }
/* pre-calculate forward and reverse increments */ /* pre-calculate forward and reverse increments */
for (m=j=0;j<nb;j++,m+=3) for (m=j=0;j<nb;j++,m+=3)
{ {
fi[m]=(j+C1)%nb; fi[m]=(j+C1)%nb;
@ -224,7 +224,7 @@ void gkey(int nb,int nk,u8 *key)
} }
/* now for the expanded decrypt key in reverse order */ /* now for the expanded decrypt key in reverse order */
for (j=0;j<Nb;j++) rkey[j+N-Nb]=fkey[j]; for (j=0;j<Nb;j++) rkey[j+N-Nb]=fkey[j];
for (i=Nb;i<N-Nb;i+=Nb) for (i=Nb;i<N-Nb;i+=Nb)
@ -253,31 +253,31 @@ void encrypt(u8 *buff)
k=Nb; k=Nb;
x=a; y=b; x=a; y=b;
/* State alternates between a and b */ /* State alternates between a and b */
for (i=1;i<Nr;i++) for (i=1;i<Nr;i++)
{ /* Nr is number of rounds. May be odd. */ { /* Nr is number of rounds. May be odd. */
/* if Nb is fixed - unroll this next /* if Nb is fixed - unroll this next
loop and hard-code in the values of fi[] */ loop and hard-code in the values of fi[] */
for (m=j=0;j<Nb;j++,m+=3) for (m=j=0;j<Nb;j++,m+=3)
{ /* deal with each 32-bit element of the State */ { /* deal with each 32-bit element of the State */
/* This is the time-critical bit */ /* This is the time-critical bit */
y[j]=fkey[k++]^ftable[(u8)x[j]]^ y[j]=fkey[k++]^ftable[(u8)x[j]]^
ROTL8(ftable[(u8)(x[fi[m]]>>8)])^ ROTL8(ftable[(u8)(x[fi[m]]>>8)])^
ROTL16(ftable[(u8)(x[fi[m+1]]>>16)])^ ROTL16(ftable[(u8)(x[fi[m+1]]>>16)])^
ROTL24(ftable[(u8)(x[fi[m+2]]>>24)]); ROTL24(ftable[(u8)(x[fi[m+2]]>>24)]);
} }
t=x; x=y; y=t; /* swap pointers */ t=x; x=y; y=t; /* swap pointers */
} }
/* Last Round - unroll if possible */ /* Last Round - unroll if possible */
for (m=j=0;j<Nb;j++,m+=3) for (m=j=0;j<Nb;j++,m+=3)
{ {
y[j]=fkey[k++]^(u32)fbsub[(u8)x[j]]^ y[j]=fkey[k++]^(u32)fbsub[(u8)x[j]]^
ROTL8((u32)fbsub[(u8)(x[fi[m]]>>8)])^ ROTL8((u32)fbsub[(u8)(x[fi[m]]>>8)])^
ROTL16((u32)fbsub[(u8)(x[fi[m+1]]>>16)])^ ROTL16((u32)fbsub[(u8)(x[fi[m+1]]>>16)])^
ROTL24((u32)fbsub[(u8)(x[fi[m+2]]>>24)]); ROTL24((u32)fbsub[(u8)(x[fi[m+2]]>>24)]);
} }
for (i=j=0;i<Nb;i++,j+=4) for (i=j=0;i<Nb;i++,j+=4)
{ {
@ -300,30 +300,30 @@ void decrypt(u8 *buff)
k=Nb; k=Nb;
x=a; y=b; x=a; y=b;
/* State alternates between a and b */ /* State alternates between a and b */
for (i=1;i<Nr;i++) for (i=1;i<Nr;i++)
{ /* Nr is number of rounds. May be odd. */ { /* Nr is number of rounds. May be odd. */
/* if Nb is fixed - unroll this next /* if Nb is fixed - unroll this next
loop and hard-code in the values of ri[] */ loop and hard-code in the values of ri[] */
for (m=j=0;j<Nb;j++,m+=3) for (m=j=0;j<Nb;j++,m+=3)
{ /* This is the time-critical bit */ { /* This is the time-critical bit */
y[j]=rkey[k++]^rtable[(u8)x[j]]^ y[j]=rkey[k++]^rtable[(u8)x[j]]^
ROTL8(rtable[(u8)(x[ri[m]]>>8)])^ ROTL8(rtable[(u8)(x[ri[m]]>>8)])^
ROTL16(rtable[(u8)(x[ri[m+1]]>>16)])^ ROTL16(rtable[(u8)(x[ri[m+1]]>>16)])^
ROTL24(rtable[(u8)(x[ri[m+2]]>>24)]); ROTL24(rtable[(u8)(x[ri[m+2]]>>24)]);
} }
t=x; x=y; y=t; /* swap pointers */ t=x; x=y; y=t; /* swap pointers */
} }
/* Last Round - unroll if possible */ /* Last Round - unroll if possible */
for (m=j=0;j<Nb;j++,m+=3) for (m=j=0;j<Nb;j++,m+=3)
{ {
y[j]=rkey[k++]^(u32)rbsub[(u8)x[j]]^ y[j]=rkey[k++]^(u32)rbsub[(u8)x[j]]^
ROTL8((u32)rbsub[(u8)(x[ri[m]]>>8)])^ ROTL8((u32)rbsub[(u8)(x[ri[m]]>>8)])^
ROTL16((u32)rbsub[(u8)(x[ri[m+1]]>>16)])^ ROTL16((u32)rbsub[(u8)(x[ri[m+1]]>>16)])^
ROTL24((u32)rbsub[(u8)(x[ri[m+2]]>>24)]); ROTL24((u32)rbsub[(u8)(x[ri[m+2]]>>24)]);
} }
for (i=j=0;i<Nb;i++,j+=4) for (i=j=0;i<Nb;i++,j+=4)
{ {
@ -334,69 +334,69 @@ void decrypt(u8 *buff)
} }
void aes_set_key(u8 *key) { void aes_set_key(u8 *key) {
gentables(); gentables();
gkey(4, 4, key); gkey(4, 4, key);
} }
// CBC mode decryption // CBC mode decryption
void aes_decrypt(u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len) { void aes_decrypt(u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len) {
u8 block[16]; u8 block[16];
u8* ctext_ptr; u8* ctext_ptr;
unsigned int blockno = 0, i; unsigned int blockno = 0, i;
//fprintf( stderr,"aes_decrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len ); //fprintf( stderr,"aes_decrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len );
//printf("aes_decrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len); //printf("aes_decrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len);
for (blockno = 0; blockno <= (len / sizeof(block)); blockno++) { for (blockno = 0; blockno <= (len / sizeof(block)); blockno++) {
unsigned int fraction; unsigned int fraction;
if (blockno == (len / sizeof(block))) { // last block if (blockno == (len / sizeof(block))) { // last block
fraction = len % sizeof(block); fraction = len % sizeof(block);
if (fraction == 0) break; if (fraction == 0) break;
memset(block, 0, sizeof(block)); memset(block, 0, sizeof(block));
} else fraction = 16; } else fraction = 16;
// debug_printf("block %d: fraction = %d\n", blockno, fraction); // debug_printf("block %d: fraction = %d\n", blockno, fraction);
memcpy(block, inbuf + blockno * sizeof(block), fraction); memcpy(block, inbuf + blockno * sizeof(block), fraction);
decrypt(block); decrypt(block);
if (blockno == 0) ctext_ptr = iv; if (blockno == 0) ctext_ptr = iv;
else ctext_ptr = inbuf + (blockno-1) * sizeof(block); else ctext_ptr = inbuf + (blockno-1) * sizeof(block);
for(i=0; i < fraction; i++) for(i=0; i < fraction; i++)
outbuf[blockno * sizeof(block) + i] = outbuf[blockno * sizeof(block) + i] =
ctext_ptr[i] ^ block[i]; ctext_ptr[i] ^ block[i];
// debug_printf("Block %d output: ", blockno); // debug_printf("Block %d output: ", blockno);
// hexdump(outbuf + blockno*sizeof(block), 16); // hexdump(outbuf + blockno*sizeof(block), 16);
} }
} }
// CBC mode encryption // CBC mode encryption
void aes_encrypt(u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len) { void aes_encrypt(u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len) {
u8 block[16]; u8 block[16];
unsigned int blockno = 0, i; unsigned int blockno = 0, i;
//printf("aes_decrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len); //printf("aes_decrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len);
//fprintf( stderr,"aes_encrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len); //fprintf( stderr,"aes_encrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len);
for (blockno = 0; blockno <= (len / sizeof(block)); blockno++) { for (blockno = 0; blockno <= (len / sizeof(block)); blockno++) {
unsigned int fraction; unsigned int fraction;
if (blockno == (len / sizeof(block))) { // last block if (blockno == (len / sizeof(block))) { // last block
fraction = len % sizeof(block); fraction = len % sizeof(block);
if (fraction == 0) break; if (fraction == 0) break;
memset(block, 0, sizeof(block)); memset(block, 0, sizeof(block));
} else fraction = 16; } else fraction = 16;
// debug_printf("block %d: fraction = %d\n", blockno, fraction); // debug_printf("block %d: fraction = %d\n", blockno, fraction);
memcpy(block, inbuf + blockno * sizeof(block), fraction); memcpy(block, inbuf + blockno * sizeof(block), fraction);
for(i=0; i < fraction; i++) for(i=0; i < fraction; i++)
block[i] = inbuf[blockno * sizeof(block) + i] ^ iv[i]; block[i] = inbuf[blockno * sizeof(block) + i] ^ iv[i];
encrypt(block); encrypt(block);
memcpy(iv, block, sizeof(block)); memcpy(iv, block, sizeof(block));
memcpy(outbuf + blockno * sizeof(block), block, sizeof(block)); memcpy(outbuf + blockno * sizeof(block), block, sizeof(block));
// debug_printf("Block %d output: ", blockno); // debug_printf("Block %d output: ", blockno);
// hexdump(outbuf + blockno*sizeof(block), 16); // hexdump(outbuf + blockno*sizeof(block), 16);
} }
} }

View File

@ -9,26 +9,26 @@
static void bn_zero(Uint8 *d, Uint32 n) static void bn_zero(Uint8 *d, Uint32 n)
{ {
memset(d, 0, n); memset(d, 0, n);
} }
static void bn_copy(Uint8 *d, Uint8 *a, Uint32 n) static void bn_copy(Uint8 *d, Uint8 *a, Uint32 n)
{ {
memcpy(d, a, n); memcpy(d, a, n);
} }
int bn_compare(Uint8 *a, Uint8 *b, Uint32 n) int bn_compare(Uint8 *a, Uint8 *b, Uint32 n)
{ {
Uint32 i; Uint32 i;
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
if (a[i] < b[i]) if (a[i] < b[i])
return -1; return -1;
if (a[i] > b[i]) if (a[i] > b[i])
return 1; return 1;
} }
return 0; return 0;
} }
void bn_sub_modulus(Uint8 *a, Uint8 *N, Uint32 n) void bn_sub_modulus(Uint8 *a, Uint8 *N, Uint32 n)
@ -37,12 +37,12 @@ void bn_sub_modulus(Uint8 *a, Uint8 *N, Uint32 n)
Uint32 dig; Uint32 dig;
Uint8 c; Uint8 c;
c = 0; c = 0;
for (i = n - 1; i < n; i--) { for (i = n - 1; i < n; i--) {
dig = N[i] + c; dig = N[i] + c;
c = (a[i] < dig); c = (a[i] < dig);
a[i] -= dig; a[i] -= dig;
} }
} }
void bn_add(Uint8 *d, Uint8 *a, Uint8 *b, Uint8 *N, Uint32 n) void bn_add(Uint8 *d, Uint8 *a, Uint8 *b, Uint8 *N, Uint32 n)
@ -51,18 +51,18 @@ void bn_add(Uint8 *d, Uint8 *a, Uint8 *b, Uint8 *N, Uint32 n)
Uint32 dig; Uint32 dig;
Uint8 c; Uint8 c;
c = 0; c = 0;
for (i = n - 1; i < n; i--) { for (i = n - 1; i < n; i--) {
dig = a[i] + b[i] + c; dig = a[i] + b[i] + c;
c = (dig >= 0x100); c = (dig >= 0x100);
d[i] = dig; d[i] = dig;
} }
if (c) if (c)
bn_sub_modulus(d, N, n); bn_sub_modulus(d, N, n);
if (bn_compare(d, N, n) >= 0) if (bn_compare(d, N, n) >= 0)
bn_sub_modulus(d, N, n); bn_sub_modulus(d, N, n);
} }
void bn_mul(Uint8 *d, Uint8 *a, Uint8 *b, Uint8 *N, Uint32 n) void bn_mul(Uint8 *d, Uint8 *a, Uint8 *b, Uint8 *N, Uint32 n)
@ -70,14 +70,14 @@ void bn_mul(Uint8 *d, Uint8 *a, Uint8 *b, Uint8 *N, Uint32 n)
Uint32 i; Uint32 i;
Uint8 mask; Uint8 mask;
bn_zero(d, n); bn_zero(d, n);
for (i = 0; i < n; i++) for (i = 0; i < n; i++)
for (mask = 0x80; mask != 0; mask >>= 1) { for (mask = 0x80; mask != 0; mask >>= 1) {
bn_add(d, d, d, N, n); bn_add(d, d, d, N, n);
if ((a[i] & mask) != 0) if ((a[i] & mask) != 0)
bn_add(d, d, b, N, n); bn_add(d, d, b, N, n);
} }
} }
void bn_exp(Uint8 *d, Uint8 *a, Uint8 *N, Uint32 n, Uint8 *e, Uint32 en) void bn_exp(Uint8 *d, Uint8 *a, Uint8 *N, Uint32 n, Uint8 *e, Uint32 en)
@ -86,16 +86,16 @@ void bn_exp(Uint8 *d, Uint8 *a, Uint8 *N, Uint32 n, Uint8 *e, Uint32 en)
Uint32 i; Uint32 i;
Uint8 mask; Uint8 mask;
bn_zero(d, n); bn_zero(d, n);
d[n-1] = 1; d[n-1] = 1;
for (i = 0; i < en; i++) for (i = 0; i < en; i++)
for (mask = 0x80; mask != 0; mask >>= 1) { for (mask = 0x80; mask != 0; mask >>= 1) {
bn_mul(t, d, d, N, n); bn_mul(t, d, d, N, n);
if ((e[i] & mask) != 0) if ((e[i] & mask) != 0)
bn_mul(d, t, a, N, n); bn_mul(d, t, a, N, n);
else else
bn_copy(d, t, n); bn_copy(d, t, n);
} }
} }
// only for prime N -- stupid but lazy, see if I care // only for prime N -- stupid but lazy, see if I care
@ -103,9 +103,9 @@ void bn_inv(Uint8 *d, Uint8 *a, Uint8 *N, Uint32 n)
{ {
Uint8 t[512], s[512]; Uint8 t[512], s[512];
bn_copy(t, N, n); bn_copy(t, N, n);
bn_zero(s, n); bn_zero(s, n);
s[n-1] = 2; s[n-1] = 2;
bn_sub_modulus(t, s, n); bn_sub_modulus(t, s, n);
bn_exp(d, a, N, n, t, n); bn_exp(d, a, N, n, t, n);
} }

View File

@ -2,6 +2,11 @@
// Licensed under the terms of the GNU GPL, version 2 // Licensed under the terms of the GNU GPL, version 2
// http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt // http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
// TODO: Clean this code up and prune
// NOTE: It's pretty much been gutted from it's original form, does the original license even apply anymore?
// Not all of these headers are necessary, figure out which ones are actually used and prune those that are irrelevant.
#include <string.h> #include <string.h>
#include <iostream> #include <iostream>
#include <time.h> #include <time.h>
@ -14,57 +19,57 @@
// y**2 + x*y = x**3 + x + b // y**2 + x*y = x**3 + x + b
/*static u8 ec_b[30] = { 0x00, 0x66, 0x64, 0x7e, 0xde, 0x6c, 0x33, 0x2c, 0x7f, 0x8c, 0x09, 0x23, 0xbb, 0x58, 0x21, /*static u8 ec_b[30] = { 0x00, 0x66, 0x64, 0x7e, 0xde, 0x6c, 0x33, 0x2c, 0x7f, 0x8c, 0x09, 0x23, 0xbb, 0x58, 0x21,
0x3b, 0x33, 0x3b, 0x20, 0xe9, 0xce, 0x42, 0x81, 0xfe, 0x11, 0x5f, 0x7d, 0x8f, 0x90, 0xad }; 0x3b, 0x33, 0x3b, 0x20, 0xe9, 0xce, 0x42, 0x81, 0xfe, 0x11, 0x5f, 0x7d, 0x8f, 0x90, 0xad };
*/ */
// order of the addition group of points // order of the addition group of points
static Uint8 ec_N[30] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, static Uint8 ec_N[30] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x13, 0xe9, 0x74, 0xe7, 0x2f, 0x8a, 0x69, 0x22, 0x03, 0x1d, 0x26, 0x03, 0xcf, 0xe0, 0xd7 }; 0x13, 0xe9, 0x74, 0xe7, 0x2f, 0x8a, 0x69, 0x22, 0x03, 0x1d, 0x26, 0x03, 0xcf, 0xe0, 0xd7 };
// base point // base point
static Uint8 ec_G[60] = { 0x00, 0xfa, 0xc9, 0xdf, 0xcb, 0xac, 0x83, 0x13, 0xbb, 0x21, 0x39, 0xf1, 0xbb, 0x75, 0x5f, static Uint8 ec_G[60] = { 0x00, 0xfa, 0xc9, 0xdf, 0xcb, 0xac, 0x83, 0x13, 0xbb, 0x21, 0x39, 0xf1, 0xbb, 0x75, 0x5f,
0xef, 0x65, 0xbc, 0x39, 0x1f, 0x8b, 0x36, 0xf8, 0xf8, 0xeb, 0x73, 0x71, 0xfd, 0x55, 0x8b, 0xef, 0x65, 0xbc, 0x39, 0x1f, 0x8b, 0x36, 0xf8, 0xf8, 0xeb, 0x73, 0x71, 0xfd, 0x55, 0x8b,
0x01, 0x00, 0x6a, 0x08, 0xa4, 0x19, 0x03, 0x35, 0x06, 0x78, 0xe5, 0x85, 0x28, 0xbe, 0xbf, 0x01, 0x00, 0x6a, 0x08, 0xa4, 0x19, 0x03, 0x35, 0x06, 0x78, 0xe5, 0x85, 0x28, 0xbe, 0xbf,
0x8a, 0x0b, 0xef, 0xf8, 0x67, 0xa7, 0xca, 0x36, 0x71, 0x6f, 0x7e, 0x01, 0xf8, 0x10, 0x52 }; 0x8a, 0x0b, 0xef, 0xf8, 0x67, 0xa7, 0xca, 0x36, 0x71, 0x6f, 0x7e, 0x01, 0xf8, 0x10, 0x52 };
/* /*
static void elt_print(char *name, u8 *a) static void elt_print(char *name, u8 *a)
{ {
u32 i; u32 i;
printf("%s = ", name); printf("%s = ", name);
for (i = 0; i < 30; i++) for (i = 0; i < 30; i++)
printf("%02x", a[i]); printf("%02x", a[i]);
printf("\n"); printf("\n");
} }
*/ */
static void elt_copy(Uint8 *d, Uint8 *a) static void elt_copy(Uint8 *d, Uint8 *a)
{ {
memcpy(d, a, 30); memcpy(d, a, 30);
} }
static void elt_zero(Uint8 *d) static void elt_zero(Uint8 *d)
{ {
memset(d, 0, 30); memset(d, 0, 30);
} }
static int elt_is_zero(Uint8 *d) static int elt_is_zero(Uint8 *d)
{ {
Uint32 i; Uint32 i;
for (i = 0; i < 30; i++) for (i = 0; i < 30; i++)
if (d[i] != 0) if (d[i] != 0)
return 0; return 0;
return 1; return 1;
} }
static void elt_add(Uint8 *d, Uint8 *a, Uint8 *b) static void elt_add(Uint8 *d, Uint8 *a, Uint8 *b)
{ {
Uint32 i; Uint32 i;
for (i = 0; i < 30; i++) for (i = 0; i < 30; i++)
d[i] = a[i] ^ b[i]; d[i] = a[i] ^ b[i];
} }
static void elt_mul_x(Uint8 *d, Uint8 *a) static void elt_mul_x(Uint8 *d, Uint8 *a)
@ -72,17 +77,17 @@ static void elt_mul_x(Uint8 *d, Uint8 *a)
Uint8 carry, x, y; Uint8 carry, x, y;
Uint32 i; Uint32 i;
carry = a[0] & 1; carry = a[0] & 1;
x = 0; x = 0;
for (i = 0; i < 29; i++) { for (i = 0; i < 29; i++) {
y = a[i + 1]; y = a[i + 1];
d[i] = x ^ (y >> 7); d[i] = x ^ (y >> 7);
x = y << 1; x = y << 1;
} }
d[29] = x ^ carry; d[29] = x ^ carry;
d[20] ^= carry << 2; d[20] ^= carry << 2;
} }
static void elt_mul(Uint8 *d, Uint8 *a, Uint8 *b) static void elt_mul(Uint8 *d, Uint8 *a, Uint8 *b)
@ -90,22 +95,22 @@ static void elt_mul(Uint8 *d, Uint8 *a, Uint8 *b)
Uint32 i, n; Uint32 i, n;
Uint8 mask; Uint8 mask;
elt_zero(d); elt_zero(d);
i = 0; i = 0;
mask = 1; mask = 1;
for (n = 0; n < 233; n++) { for (n = 0; n < 233; n++) {
elt_mul_x(d, d); elt_mul_x(d, d);
if ((a[i] & mask) != 0) if ((a[i] & mask) != 0)
elt_add(d, d, b); elt_add(d, d, b);
mask >>= 1; mask >>= 1;
if (mask == 0) { if (mask == 0) {
mask = 0x80; mask = 0x80;
i++; i++;
} }
} }
} }
static const Uint8 square[16] = { 0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15, 0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55 }; static const Uint8 square[16] = { 0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15, 0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55 };
@ -114,10 +119,10 @@ static void elt_square_to_wide(Uint8 *d, Uint8 *a)
{ {
Uint32 i; Uint32 i;
for (i = 0; i < 30; i++) { for (i = 0; i < 30; i++) {
d[2*i] = square[a[i] >> 4]; d[2*i] = square[a[i] >> 4];
d[2*i + 1] = square[a[i] & 15]; d[2*i + 1] = square[a[i] & 15];
} }
} }
static void wide_reduce(Uint8 *d) static void wide_reduce(Uint8 *d)
@ -125,47 +130,47 @@ static void wide_reduce(Uint8 *d)
Uint32 i; Uint32 i;
Uint8 x; Uint8 x;
for (i = 0; i < 30; i++) { for (i = 0; i < 30; i++) {
x = d[i]; x = d[i];
d[i + 19] ^= x >> 7; d[i + 19] ^= x >> 7;
d[i + 20] ^= x << 1; d[i + 20] ^= x << 1;
d[i + 29] ^= x >> 1; d[i + 29] ^= x >> 1;
d[i + 30] ^= x << 7; d[i + 30] ^= x << 7;
} }
x = d[30] & ~1; x = d[30] & ~1;
d[49] ^= x >> 7; d[49] ^= x >> 7;
d[50] ^= x << 1; d[50] ^= x << 1;
d[59] ^= x >> 1; d[59] ^= x >> 1;
d[30] &= 1; d[30] &= 1;
} }
static void elt_square(Uint8 *d, Uint8 *a) static void elt_square(Uint8 *d, Uint8 *a)
{ {
Uint8 wide[60]; Uint8 wide[60];
elt_square_to_wide(wide, a); elt_square_to_wide(wide, a);
wide_reduce(wide); wide_reduce(wide);
elt_copy(d, wide + 30); elt_copy(d, wide + 30);
} }
static void itoh_tsujii(Uint8 *d, Uint8 *a, Uint8 *b, Uint32 j) static void itoh_tsujii(Uint8 *d, Uint8 *a, Uint8 *b, Uint32 j)
{ {
Uint8 t[30]; Uint8 t[30];
elt_copy(t, a); elt_copy(t, a);
while (j--) { while (j--) {
elt_square(d, t); elt_square(d, t);
elt_copy(t, d); elt_copy(t, d);
} }
elt_mul(d, t, b); elt_mul(d, t, b);
} }
static void elt_inv(Uint8 *d, Uint8 *a) static void elt_inv(Uint8 *d, Uint8 *a)
@ -173,46 +178,46 @@ static void elt_inv(Uint8 *d, Uint8 *a)
Uint8 t[30]; Uint8 t[30];
Uint8 s[30]; Uint8 s[30];
itoh_tsujii(t, a, a, 1); itoh_tsujii(t, a, a, 1);
itoh_tsujii(s, t, a, 1); itoh_tsujii(s, t, a, 1);
itoh_tsujii(t, s, s, 3); itoh_tsujii(t, s, s, 3);
itoh_tsujii(s, t, a, 1); itoh_tsujii(s, t, a, 1);
itoh_tsujii(t, s, s, 7); itoh_tsujii(t, s, s, 7);
itoh_tsujii(s, t, t, 14); itoh_tsujii(s, t, t, 14);
itoh_tsujii(t, s, a, 1); itoh_tsujii(t, s, a, 1);
itoh_tsujii(s, t, t, 29); itoh_tsujii(s, t, t, 29);
itoh_tsujii(t, s, s, 58); itoh_tsujii(t, s, s, 58);
itoh_tsujii(s, t, t, 116); itoh_tsujii(s, t, t, 116);
elt_square(d, s); elt_square(d, s);
} }
/* /*
static int point_is_on_curve(u8 *p) static int point_is_on_curve(u8 *p)
{ {
u8 s[30], t[30]; u8 s[30], t[30];
u8 *x, *y; u8 *x, *y;
x = p; x = p;
y = p + 30; y = p + 30;
elt_square(t, x); elt_square(t, x);
elt_mul(s, t, x); elt_mul(s, t, x);
elt_add(s, s, t); elt_add(s, s, t);
elt_square(t, y); elt_square(t, y);
elt_add(s, s, t); elt_add(s, s, t);
elt_mul(t, x, y); elt_mul(t, x, y);
elt_add(s, s, t); elt_add(s, s, t);
elt_add(s, s, ec_b); elt_add(s, s, ec_b);
return elt_is_zero(s); return elt_is_zero(s);
} }
*/ */
static int point_is_zero(Uint8 *p) static int point_is_zero(Uint8 *p)
{ {
return elt_is_zero(p) && elt_is_zero(p + 30); return elt_is_zero(p) && elt_is_zero(p + 30);
} }
static void point_double(Uint8 *r, Uint8 *p) static void point_double(Uint8 *r, Uint8 *p)
@ -220,31 +225,31 @@ static void point_double(Uint8 *r, Uint8 *p)
Uint8 s[30], t[30]; Uint8 s[30], t[30];
Uint8 *px, *py, *rx, *ry; Uint8 *px, *py, *rx, *ry;
px = p; px = p;
py = p + 30; py = p + 30;
rx = r; rx = r;
ry = r + 30; ry = r + 30;
if (elt_is_zero(px)) { if (elt_is_zero(px)) {
elt_zero(rx); elt_zero(rx);
elt_zero(ry); elt_zero(ry);
return; return;
} }
elt_inv(t, px); elt_inv(t, px);
elt_mul(s, py, t); elt_mul(s, py, t);
elt_add(s, s, px); elt_add(s, s, px);
elt_square(t, px); elt_square(t, px);
elt_square(rx, s); elt_square(rx, s);
elt_add(rx, rx, s); elt_add(rx, rx, s);
rx[29] ^= 1; rx[29] ^= 1;
elt_mul(ry, s, rx); elt_mul(ry, s, rx);
elt_add(ry, ry, rx); elt_add(ry, ry, rx);
elt_add(ry, ry, t); elt_add(ry, ry, t);
} }
static void point_add(Uint8 *r, Uint8 *p, Uint8 *q) static void point_add(Uint8 *r, Uint8 *p, Uint8 *q)
@ -252,52 +257,52 @@ static void point_add(Uint8 *r, Uint8 *p, Uint8 *q)
Uint8 s[30], t[30], u[30]; Uint8 s[30], t[30], u[30];
Uint8 *px, *py, *qx, *qy, *rx, *ry; Uint8 *px, *py, *qx, *qy, *rx, *ry;
px = p; px = p;
py = p + 30; py = p + 30;
qx = q; qx = q;
qy = q + 30; qy = q + 30;
rx = r; rx = r;
ry = r + 30; ry = r + 30;
if (point_is_zero(p)) { if (point_is_zero(p)) {
elt_copy(rx, qx); elt_copy(rx, qx);
elt_copy(ry, qy); elt_copy(ry, qy);
return; return;
} }
if (point_is_zero(q)) { if (point_is_zero(q)) {
elt_copy(rx, px); elt_copy(rx, px);
elt_copy(ry, py); elt_copy(ry, py);
return; return;
} }
elt_add(u, px, qx); elt_add(u, px, qx);
if (elt_is_zero(u)) { if (elt_is_zero(u)) {
elt_add(u, py, qy); elt_add(u, py, qy);
if (elt_is_zero(u)) if (elt_is_zero(u))
point_double(r, p); point_double(r, p);
else { else {
elt_zero(rx); elt_zero(rx);
elt_zero(ry); elt_zero(ry);
} }
return; return;
} }
elt_inv(t, u); elt_inv(t, u);
elt_add(u, py, qy); elt_add(u, py, qy);
elt_mul(s, t, u); elt_mul(s, t, u);
elt_square(t, s); elt_square(t, s);
elt_add(t, t, s); elt_add(t, t, s);
elt_add(t, t, qx); elt_add(t, t, qx);
t[29] ^= 1; t[29] ^= 1;
elt_mul(u, s, t); elt_mul(u, s, t);
elt_add(s, u, py); elt_add(s, u, py);
elt_add(rx, t, px); elt_add(rx, t, px);
elt_add(ry, s, rx); elt_add(ry, s, rx);
} }
static void point_mul(Uint8 *d, Uint8 *a, Uint8 *b) // a is bignum static void point_mul(Uint8 *d, Uint8 *a, Uint8 *b) // a is bignum
@ -305,21 +310,23 @@ static void point_mul(Uint8 *d, Uint8 *a, Uint8 *b) // a is bignum
Uint32 i; Uint32 i;
Uint8 mask; Uint8 mask;
elt_zero(d); elt_zero(d);
elt_zero(d + 30); elt_zero(d + 30);
for (i = 0; i < 30; i++) for (i = 0; i < 30; i++)
for (mask = 0x80; mask != 0; mask >>= 1) { for (mask = 0x80; mask != 0; mask >>= 1) {
point_double(d, d); point_double(d, d);
if ((a[i] & mask) != 0) if ((a[i] & mask) != 0)
point_add(d, d, b); point_add(d, d, b);
} }
} }
// DUPE FUNCTION! NUKE IT!!
void sillyRandom(Uint8 * rndArea, Uint8 count) void sillyRandom(Uint8 * rndArea, Uint8 count)
{ {
for(Uint16 i = 0; i < count; i++) for(Uint16 i = 0; i < count; i++)
rndArea[i]=rand(); rndArea[i]=rand();
} }
void generate_ecdsa(Uint8 *R, Uint8 *S, Uint8 *k, Uint8 *hash) void generate_ecdsa(Uint8 *R, Uint8 *S, Uint8 *k, Uint8 *hash)
@ -329,30 +336,30 @@ void generate_ecdsa(Uint8 *R, Uint8 *S, Uint8 *k, Uint8 *hash)
Uint8 m[30]; Uint8 m[30];
Uint8 minv[30]; Uint8 minv[30];
Uint8 mG[60]; Uint8 mG[60];
//FILE *fp; //FILE *fp;
elt_zero(e); elt_zero(e);
memcpy(e + 10, hash, 20); memcpy(e + 10, hash, 20);
sillyRandom(m, sizeof(m)); sillyRandom(m, sizeof(m));
m[0] = 0; m[0] = 0;
// R = (mG).x // R = (mG).x
point_mul(mG, m, ec_G); point_mul(mG, m, ec_G);
elt_copy(R, mG); elt_copy(R, mG);
if (bn_compare(R, ec_N, 30) >= 0) if (bn_compare(R, ec_N, 30) >= 0)
bn_sub_modulus(R, ec_N, 30); bn_sub_modulus(R, ec_N, 30);
// S = m**-1*(e + Rk) (mod N) // S = m**-1*(e + Rk) (mod N)
elt_copy(kk, k); elt_copy(kk, k);
if (bn_compare(kk, ec_N, 30) >= 0) if (bn_compare(kk, ec_N, 30) >= 0)
bn_sub_modulus(kk, ec_N, 30); bn_sub_modulus(kk, ec_N, 30);
bn_mul(S, R, kk, ec_N, 30); bn_mul(S, R, kk, ec_N, 30);
bn_add(kk, S, e, ec_N, 30); bn_add(kk, S, e, ec_N, 30);
bn_inv(minv, m, ec_N, 30); bn_inv(minv, m, ec_N, 30);
bn_mul(S, minv, kk, ec_N, 30); bn_mul(S, minv, kk, ec_N, 30);
} }
bool check_ecdsa(Uint8 *Q, Uint8 *R, Uint8 *S, Uint8 *hash) bool check_ecdsa(Uint8 *Q, Uint8 *R, Uint8 *S, Uint8 *hash)
@ -362,28 +369,28 @@ bool check_ecdsa(Uint8 *Q, Uint8 *R, Uint8 *S, Uint8 *hash)
Uint8 w1[30], w2[30]; Uint8 w1[30], w2[30];
Uint8 r1[60], r2[60]; Uint8 r1[60], r2[60];
bn_inv(Sinv, S, ec_N, 30); bn_inv(Sinv, S, ec_N, 30);
elt_zero(e); elt_zero(e);
memcpy(e + 10, hash, 20); memcpy(e + 10, hash, 20);
bn_mul(w1, e, Sinv, ec_N, 30); bn_mul(w1, e, Sinv, ec_N, 30);
bn_mul(w2, R, Sinv, ec_N, 30); bn_mul(w2, R, Sinv, ec_N, 30);
point_mul(r1, w1, ec_G); point_mul(r1, w1, ec_G);
point_mul(r2, w2, Q); point_mul(r2, w2, Q);
point_add(r1, r1, r2); point_add(r1, r1, r2);
if (bn_compare(r1, ec_N, 30) >= 0) if (bn_compare(r1, ec_N, 30) >= 0)
bn_sub_modulus(r1, ec_N, 30); bn_sub_modulus(r1, ec_N, 30);
return (bn_compare(r1, R, 30) == 0); return (bn_compare(r1, R, 30) == 0);
} }
void ec_priv_to_pub(Uint8 *k, Uint8 *Q) void ec_priv_to_pub(Uint8 *k, Uint8 *Q)
{ {
point_mul(Q, k, ec_G); point_mul(Q, k, ec_G);
} }
bool check_ec(Uint8 *ng, Uint8 *ap, Uint8 *sig, Uint8 *sig_hash) bool check_ec(Uint8 *ng, Uint8 *ap, Uint8 *sig, Uint8 *sig_hash)
@ -392,28 +399,28 @@ bool check_ec(Uint8 *ng, Uint8 *ap, Uint8 *sig, Uint8 *sig_hash)
Uint8 *ng_Q, *ap_R, *ap_S; Uint8 *ng_Q, *ap_R, *ap_S;
Uint8 *ap_Q, *sig_R, *sig_S; Uint8 *ap_Q, *sig_R, *sig_S;
ng_Q = ng + 0x0108; ng_Q = ng + 0x0108;
ap_R = ap + 0x04; ap_R = ap + 0x04;
ap_S = ap + 0x22; ap_S = ap + 0x22;
ap_hash = getSha1(ap+0x80, 0x100); ap_hash = getSha1(ap+0x80, 0x100);
ap_Q = ap + 0x0108; ap_Q = ap + 0x0108;
sig_R = sig; sig_R = sig;
sig_S = sig + 30; sig_S = sig + 30;
return check_ecdsa(ng_Q, ap_R, ap_S, ap_hash) return check_ecdsa(ng_Q, ap_R, ap_S, ap_hash)
&& check_ecdsa(ap_Q, sig_R, sig_S, sig_hash); && check_ecdsa(ap_Q, sig_R, sig_S, sig_hash);
} }
void make_ec_cert(Uint8 *cert, Uint8 *sig, char *signer, char *name, Uint8 *priv, Uint32 key_id ) void make_ec_cert(Uint8 *cert, Uint8 *sig, char *signer, char *name, Uint8 *priv, Uint32 key_id )
{ {
memset(cert, 0, 0x180); memset(cert, 0, 0x180);
*(Uint32*)(cert) = swapU32(0x10002); *(Uint32*)(cert) = swapU32(0x10002);
memcpy((char*)cert + 4, sig, 60); memcpy((char*)cert + 4, sig, 60);
strcpy((char*)cert + 0x80, signer); strcpy((char*)cert + 0x80, signer);
*(Uint32*)(cert + 0xc0) = swapU32(2); *(Uint32*)(cert + 0xc0) = swapU32(2);
strcpy((char*)cert + 0xc4, name); strcpy((char*)cert + 0xc4, name);
*(Uint32*)(cert + 0x104) = swapU32(key_id); *(Uint32*)(cert + 0x104) = swapU32(key_id);
ec_priv_to_pub(priv, cert + 0x108); ec_priv_to_pub(priv, cert + 0x108);
} }

466
src/md5.c
View File

@ -110,33 +110,33 @@
*/ */
static const uint8_t K[3][16] = { static const uint8_t K[3][16] = {
/* Round 1: skipped (since it is simply sequential). */ /* Round 1: skipped (since it is simply sequential). */
{ 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12 }, /* R2 */ { 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12 }, /* R2 */
{ 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2 }, /* R3 */ { 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2 }, /* R3 */
{ 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9 } /* R4 */ { 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9 } /* R4 */
}; };
static const uint8_t S[4][4] = { { 7, 12, 17, 22 }, /* Round 1 */ static const uint8_t S[4][4] = { { 7, 12, 17, 22 }, /* Round 1 */
{ 5, 9, 14, 20 }, /* Round 2 */ { 5, 9, 14, 20 }, /* Round 2 */
{ 4, 11, 16, 23 }, /* Round 3 */ { 4, 11, 16, 23 }, /* Round 3 */
{ 6, 10, 15, 21 } /* Round 4 */ { 6, 10, 15, 21 } /* Round 4 */
}; };
static const uint32_t T[4][16] = { { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, /* Round 1 */ static const uint32_t T[4][16] = { { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, /* Round 1 */
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
0xa679438e, 0x49b40821 }, 0xa679438e, 0x49b40821 },
{ 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, /* Round 2 */ { 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, /* Round 2 */
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8,
0x676f02d9, 0x8d2a4c8a }, 0x676f02d9, 0x8d2a4c8a },
{ 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, /* Round 3 */ { 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, /* Round 3 */
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5,
0x1fa27cf8, 0xc4ac5665 }, 0x1fa27cf8, 0xc4ac5665 },
{ 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, /* Round 4 */ { 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, /* Round 4 */
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235,
0x2ad7d2bb, 0xeb86d391 }, }; 0x2ad7d2bb, 0xeb86d391 }, };
/* -------------------------------------------------------------------------- ** /* -------------------------------------------------------------------------- **
* Macros: * Macros:
@ -197,87 +197,87 @@ static void Permute(uint32_t ABCD[4], const unsigned char block[64])
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
{ {
int round; int round;
int i, j; int i, j;
uint8_t s; uint8_t s;
uint32_t a, b, c, d; uint32_t a, b, c, d;
uint32_t KeepABCD[4]; uint32_t KeepABCD[4];
uint32_t X[16]; uint32_t X[16];
/* Store the current ABCD values for later re-use. /* Store the current ABCD values for later re-use.
*/ */
for (i = 0; i < 4; i++) for (i = 0; i < 4; i++)
KeepABCD[i] = ABCD[i]; KeepABCD[i] = ABCD[i];
/* Convert the input block into an array of unsigned longs, taking care /* Convert the input block into an array of unsigned longs, taking care
* to read the block in Little Endian order (the algorithm assumes this). * to read the block in Little Endian order (the algorithm assumes this).
* The uint32_t values are then handled in host order. * The uint32_t values are then handled in host order.
*/ */
for (i = 0, j = 0; i < 16; i++) for (i = 0, j = 0; i < 16; i++)
{ {
X[i] = (uint32_t) block[j++]; X[i] = (uint32_t) block[j++];
X[i] |= ((uint32_t) block[j++] << 8); X[i] |= ((uint32_t) block[j++] << 8);
X[i] |= ((uint32_t) block[j++] << 16); X[i] |= ((uint32_t) block[j++] << 16);
X[i] |= ((uint32_t) block[j++] << 24); X[i] |= ((uint32_t) block[j++] << 24);
} }
/* This loop performs the four rounds of permutations. /* This loop performs the four rounds of permutations.
* The rounds are each very similar. The differences are in three areas: * The rounds are each very similar. The differences are in three areas:
* - The function (F, G, H, or I) used to perform bitwise permutations * - The function (F, G, H, or I) used to perform bitwise permutations
* on the registers, * on the registers,
* - The order in which values from X[] are chosen. * - The order in which values from X[] are chosen.
* - Changes to the number of bits by which the registers are rotated. * - Changes to the number of bits by which the registers are rotated.
* This implementation uses a switch statement to deal with some of the * This implementation uses a switch statement to deal with some of the
* differences between rounds. Other differences are handled by storing * differences between rounds. Other differences are handled by storing
* values in arrays and using the round number to select the correct set * values in arrays and using the round number to select the correct set
* of values. * of values.
* *
* (My implementation appears to be a poor compromise between speed, size, * (My implementation appears to be a poor compromise between speed, size,
* and clarity. Ugh. [crh]) * and clarity. Ugh. [crh])
*/ */
for (round = 0; round < 4; round++) for (round = 0; round < 4; round++)
{ {
for (i = 0; i < 16; i++) for (i = 0; i < 16; i++)
{ {
j = (4 - (i % 4)) & 0x3; /* <j> handles the rotation of ABCD. */ j = (4 - (i % 4)) & 0x3; /* <j> handles the rotation of ABCD. */
s = S[round][i % 4]; /* <s> is the bit shift for this iteration. */ s = S[round][i % 4]; /* <s> is the bit shift for this iteration. */
b = ABCD[(j + 1) & 0x3]; /* Copy the b,c,d values per ABCD rotation. */ b = ABCD[(j + 1) & 0x3]; /* Copy the b,c,d values per ABCD rotation. */
c = ABCD[(j + 2) & 0x3]; /* This isn't really necessary, it just looks */ c = ABCD[(j + 2) & 0x3]; /* This isn't really necessary, it just looks */
d = ABCD[(j + 3) & 0x3]; /* clean & will hopefully be optimized away. */ d = ABCD[(j + 3) & 0x3]; /* clean & will hopefully be optimized away. */
/* The actual perumation function. /* The actual perumation function.
* This is broken out to minimize the code within the switch(). * This is broken out to minimize the code within the switch().
*/ */
switch (round) switch (round)
{ {
case 0: case 0:
/* round 1 */ /* round 1 */
a = md5F( b, c, d ) + X[i]; a = md5F( b, c, d ) + X[i];
break; break;
case 1: case 1:
/* round 2 */ /* round 2 */
a = md5G( b, c, d ) + X[K[0][i]]; a = md5G( b, c, d ) + X[K[0][i]];
break; break;
case 2: case 2:
/* round 3 */ /* round 3 */
a = md5H( b, c, d ) + X[K[1][i]]; a = md5H( b, c, d ) + X[K[1][i]];
break; break;
default: default:
/* round 4 */ /* round 4 */
a = md5I( b, c, d ) + X[K[2][i]]; a = md5I( b, c, d ) + X[K[2][i]];
break; break;
} }
a = 0xFFFFFFFF & (ABCD[j] + a + T[round][i]); a = 0xFFFFFFFF & (ABCD[j] + a + T[round][i]);
ABCD[j] = b + (0xFFFFFFFF & ((a << s) | (a >> (32 - s)))); ABCD[j] = b + (0xFFFFFFFF & ((a << s) | (a >> (32 - s))));
} }
} }
/* Use the stored original A, B, C, D values to perform /* Use the stored original A, B, C, D values to perform
* one last convolution. * one last convolution.
*/ */
for (i = 0; i < 4; i++) for (i = 0; i < 4; i++)
ABCD[i] = 0xFFFFFFFF & (ABCD[i] + KeepABCD[i]); ABCD[i] = 0xFFFFFFFF & (ABCD[i] + KeepABCD[i]);
} /* Permute */ } /* Permute */
@ -314,22 +314,22 @@ auth_md5Ctx *auth_md5InitCtx(auth_md5Ctx *ctx)
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
{ {
ctx->len = 0; ctx->len = 0;
ctx->b_used = 0; ctx->b_used = 0;
ctx->ABCD[0] = 0x67452301; /* The array ABCD[] contains the four 4-byte */ ctx->ABCD[0] = 0x67452301; /* The array ABCD[] contains the four 4-byte */
ctx->ABCD[1] = 0xefcdab89; /* "registers" that are manipulated to */ ctx->ABCD[1] = 0xefcdab89; /* "registers" that are manipulated to */
ctx->ABCD[2] = 0x98badcfe; /* produce the MD5 digest. The input acts */ ctx->ABCD[2] = 0x98badcfe; /* produce the MD5 digest. The input acts */
ctx->ABCD[3] = 0x10325476; /* upon the registers, not the other way */ ctx->ABCD[3] = 0x10325476; /* upon the registers, not the other way */
/* 'round. The initial values are those */ /* 'round. The initial values are those */
/* given in RFC 1321 (pg. 4). Note, however, that RFC 1321 */ /* given in RFC 1321 (pg. 4). Note, however, that RFC 1321 */
/* provides these values as bytes, not as longwords, and the */ /* provides these values as bytes, not as longwords, and the */
/* bytes are arranged in little-endian order as if they were */ /* bytes are arranged in little-endian order as if they were */
/* the bytes of (little endian) 32-bit ints. That's */ /* the bytes of (little endian) 32-bit ints. That's */
/* confusing as all getout (to me, anyway). The values given */ /* confusing as all getout (to me, anyway). The values given */
/* here are provided as 32-bit values in C language format, */ /* here are provided as 32-bit values in C language format, */
/* so they are endian-agnostic. */ /* so they are endian-agnostic. */
return (ctx); return (ctx);
} /* auth_md5InitCtx */ } /* auth_md5InitCtx */
auth_md5Ctx *auth_md5SumCtx(auth_md5Ctx *ctx, const unsigned char *src, const int len) auth_md5Ctx *auth_md5SumCtx(auth_md5Ctx *ctx, const unsigned char *src, const int len)
@ -349,29 +349,29 @@ auth_md5Ctx *auth_md5SumCtx(auth_md5Ctx *ctx, const unsigned char *src, const in
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
{ {
int i; int i;
/* Add the new block's length to the total length. /* Add the new block's length to the total length.
*/ */
ctx->len += (uint32_t) len; ctx->len += (uint32_t) len;
/* Copy the new block's data into the context block. /* Copy the new block's data into the context block.
* Call the Permute() function whenever the context block is full. * Call the Permute() function whenever the context block is full.
*/ */
for (i = 0; i < len; i++) for (i = 0; i < len; i++)
{ {
ctx->block[ctx->b_used] = src[i]; ctx->block[ctx->b_used] = src[i];
(ctx->b_used)++; (ctx->b_used)++;
if (64 == ctx->b_used) if (64 == ctx->b_used)
{ {
Permute(ctx->ABCD, ctx->block); Permute(ctx->ABCD, ctx->block);
ctx->b_used = 0; ctx->b_used = 0;
} }
} }
/* Return the updated context. /* Return the updated context.
*/ */
return (ctx); return (ctx);
} /* auth_md5SumCtx */ } /* auth_md5SumCtx */
auth_md5Ctx *auth_md5CloseCtx(auth_md5Ctx *ctx, unsigned char *dst) auth_md5Ctx *auth_md5CloseCtx(auth_md5Ctx *ctx, unsigned char *dst)
@ -394,57 +394,57 @@ auth_md5Ctx *auth_md5CloseCtx(auth_md5Ctx *ctx, unsigned char *dst)
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
{ {
int i; int i;
uint32_t l; uint32_t l;
/* Add the required 0x80 padding initiator byte. /* Add the required 0x80 padding initiator byte.
* The auth_md5SumCtx() function always permutes and resets the context * The auth_md5SumCtx() function always permutes and resets the context
* block when it gets full, so we know that there must be at least one * block when it gets full, so we know that there must be at least one
* free byte in the context block. * free byte in the context block.
*/ */
ctx->block[ctx->b_used] = 0x80; ctx->block[ctx->b_used] = 0x80;
(ctx->b_used)++; (ctx->b_used)++;
/* Zero out any remaining free bytes in the context block. /* Zero out any remaining free bytes in the context block.
*/ */
for (i = ctx->b_used; i < 64; i++) for (i = ctx->b_used; i < 64; i++)
ctx->block[i] = 0; ctx->block[i] = 0;
/* We need 8 bytes to store the length field. /* We need 8 bytes to store the length field.
* If we don't have 8, call Permute() and reset the context block. * If we don't have 8, call Permute() and reset the context block.
*/ */
if (56 < ctx->b_used) if (56 < ctx->b_used)
{ {
Permute(ctx->ABCD, ctx->block); Permute(ctx->ABCD, ctx->block);
for (i = 0; i < 64; i++) for (i = 0; i < 64; i++)
ctx->block[i] = 0; ctx->block[i] = 0;
} }
/* Add the total length and perform the final perumation. /* Add the total length and perform the final perumation.
* Note: The 60'th byte is read from the *original* <ctx->len> value * Note: The 60'th byte is read from the *original* <ctx->len> value
* and shifted to the correct position. This neatly avoids * and shifted to the correct position. This neatly avoids
* any MAXINT numeric overflow issues. * any MAXINT numeric overflow issues.
*/ */
l = ctx->len << 3; l = ctx->len << 3;
for (i = 0; i < 4; i++) for (i = 0; i < 4; i++)
ctx->block[56 + i] |= GetLongByte( l, i ); ctx->block[56 + i] |= GetLongByte( l, i );
ctx->block[60] = ((GetLongByte( ctx->len, 3 ) & 0xE0) >> 5); /* See Above! */ ctx->block[60] = ((GetLongByte( ctx->len, 3 ) & 0xE0) >> 5); /* See Above! */
Permute(ctx->ABCD, ctx->block); Permute(ctx->ABCD, ctx->block);
/* Now copy the result into the output buffer and we're done. /* Now copy the result into the output buffer and we're done.
*/ */
for (i = 0; i < 4; i++) for (i = 0; i < 4; i++)
{ {
dst[0 + i] = GetLongByte( ctx->ABCD[0], i ); dst[0 + i] = GetLongByte( ctx->ABCD[0], i );
dst[4 + i] = GetLongByte( ctx->ABCD[1], i ); dst[4 + i] = GetLongByte( ctx->ABCD[1], i );
dst[8 + i] = GetLongByte( ctx->ABCD[2], i ); dst[8 + i] = GetLongByte( ctx->ABCD[2], i );
dst[12 + i] = GetLongByte( ctx->ABCD[3], i ); dst[12 + i] = GetLongByte( ctx->ABCD[3], i );
} }
/* Return the context. /* Return the context.
* This is done for compatibility with the other auth_md5*Ctx() functions. * This is done for compatibility with the other auth_md5*Ctx() functions.
*/ */
return (ctx); return (ctx);
} /* auth_md5CloseCtx */ } /* auth_md5CloseCtx */
unsigned char * MD5(unsigned char *dst, const unsigned char *src, const int len) unsigned char * MD5(unsigned char *dst, const unsigned char *src, const int len)
@ -481,13 +481,13 @@ unsigned char * MD5(unsigned char *dst, const unsigned char *src, const int len)
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
{ {
auth_md5Ctx ctx[1]; auth_md5Ctx ctx[1];
(void) auth_md5InitCtx(ctx); /* Open a context. */ (void) auth_md5InitCtx(ctx); /* Open a context. */
(void) auth_md5SumCtx(ctx, src, len); /* Pass only one block. */ (void) auth_md5SumCtx(ctx, src, len); /* Pass only one block. */
(void) auth_md5CloseCtx(ctx, dst); /* Close the context. */ (void) auth_md5CloseCtx(ctx, dst); /* Close the context. */
return (dst); /* Makes life easy. */ return (dst); /* Makes life easy. */
} /* auth_md5Sum */ } /* auth_md5Sum */
unsigned char * MD5fromFile(unsigned char *dst, const char *src) unsigned char * MD5fromFile(unsigned char *dst, const char *src)
@ -522,89 +522,89 @@ unsigned char * MD5fromFile(unsigned char *dst, const char *src)
* ------------------------------------------------------------------------ ** * ------------------------------------------------------------------------ **
*/ */
{ {
auth_md5Ctx ctx[1]; auth_md5Ctx ctx[1];
FILE * file; FILE * file;
unsigned int blksize = 0; unsigned int blksize = 0;
unsigned int read = 0; unsigned int read = 0;
unsigned int filesize; unsigned int filesize;
unsigned char* buffer; unsigned char* buffer;
file = fopen(src, "rb"); file = fopen(src, "rb");
if (file == NULL) if (file == NULL)
{ {
return NULL; return NULL;
} }
(void) auth_md5InitCtx(ctx); /* Open a context. */ (void) auth_md5InitCtx(ctx); /* Open a context. */
fseek(file, 0, SEEK_END); fseek(file, 0, SEEK_END);
filesize = ftell(file); filesize = ftell(file);
rewind(file); rewind(file);
if (filesize < 1048576) //1MB cache for files bigger than 1 MB if (filesize < 1048576) //1MB cache for files bigger than 1 MB
blksize = filesize; blksize = filesize;
else blksize = 1048576; else blksize = 1048576;
buffer = malloc(blksize); buffer = malloc(blksize);
if (buffer == NULL) if (buffer == NULL)
{ {
//no memory //no memory
fclose(file); fclose(file);
return NULL; return NULL;
} }
do do
{ {
read = fread(buffer, 1, blksize, file); read = fread(buffer, 1, blksize, file);
(void) auth_md5SumCtx(ctx, buffer, read); /* Pass only one block. */ (void) auth_md5SumCtx(ctx, buffer, read); /* Pass only one block. */
} while (read > 0); } while (read > 0);
fclose(file); fclose(file);
free(buffer); free(buffer);
(void) auth_md5CloseCtx(ctx, dst); /* Close the context. */ (void) auth_md5CloseCtx(ctx, dst); /* Close the context. */
return (dst); /* Makes life easy. */ return (dst); /* Makes life easy. */
} /* auth_md5Sum */ } /* auth_md5Sum */
const char * MD5ToString(const unsigned char * hash, char * dst) const char * MD5ToString(const unsigned char * hash, char * dst)
{ {
char hexchar[3]; char hexchar[3];
short i = 0, n = 0; short i = 0, n = 0;
for (i = 0; i < 16; i++) for (i = 0; i < 16; i++)
{ {
sprintf(hexchar, "%02X", hash[i]); sprintf(hexchar, "%02X", hash[i]);
dst[n++] = hexchar[0]; dst[n++] = hexchar[0];
dst[n++] = hexchar[1]; dst[n++] = hexchar[1];
} }
dst[n] = 0x00; dst[n] = 0x00;
return dst; return dst;
} }
unsigned char * StringToMD5(const char * hash, unsigned char * dst) unsigned char * StringToMD5(const char * hash, unsigned char * dst)
{ {
char hexchar[2]; char hexchar[2];
short i = 0, n = 0; short i = 0, n = 0;
for (i = 0; i < 16; i++) for (i = 0; i < 16; i++)
{ {
hexchar[0] = hash[n++]; hexchar[0] = hash[n++];
hexchar[1] = hash[n++]; hexchar[1] = hash[n++];
dst[i] = STR2HEX( hexchar[0] ); dst[i] = STR2HEX( hexchar[0] );
dst[i] <<= 4; dst[i] <<= 4;
dst[i] += STR2HEX( hexchar[1] ); dst[i] += STR2HEX( hexchar[1] );
} }
return dst; return dst;
} }
/* ========================================================================== */ /* ========================================================================== */

View File

@ -46,8 +46,8 @@
* Define the circular shift macro * Define the circular shift macro
*/ */
#define SHA1CircularShift(bits,word) \ #define SHA1CircularShift(bits,word) \
((((word) << (bits)) & 0xFFFFFFFF) | \ ((((word) << (bits)) & 0xFFFFFFFF) | \
((word) >> (32-(bits)))) ((word) >> (32-(bits))))
/* Function prototypes */ /* Function prototypes */
void SHA1ProcessMessageBlock(SHA1Context *); void SHA1ProcessMessageBlock(SHA1Context *);
@ -108,13 +108,13 @@ int SHA1Result(SHA1Context *context)
if (context->Corrupted) if (context->Corrupted)
{ {
return 0; return 0;
} }
if (!context->Computed) if (!context->Computed)
{ {
SHA1PadMessage(context); SHA1PadMessage(context);
context->Computed = 1; context->Computed = 1;
} }
return 1; return 1;
@ -143,46 +143,46 @@ int SHA1Result(SHA1Context *context)
* *
*/ */
void SHA1Input( SHA1Context *context, void SHA1Input( SHA1Context *context,
const unsigned char *message_array, const unsigned char *message_array,
unsigned length) unsigned length)
{ {
if (!length) if (!length)
{ {
return; return;
} }
if (context->Computed || context->Corrupted) if (context->Computed || context->Corrupted)
{ {
context->Corrupted = 1; context->Corrupted = 1;
return; return;
} }
while(length-- && !context->Corrupted) while(length-- && !context->Corrupted)
{ {
context->Message_Block[context->Message_Block_Index++] = context->Message_Block[context->Message_Block_Index++] =
(*message_array & 0xFF); (*message_array & 0xFF);
context->Length_Low += 8; context->Length_Low += 8;
/* Force it to 32 bits */ /* Force it to 32 bits */
context->Length_Low &= 0xFFFFFFFF; context->Length_Low &= 0xFFFFFFFF;
if (context->Length_Low == 0) if (context->Length_Low == 0)
{ {
context->Length_High++; context->Length_High++;
/* Force it to 32 bits */ /* Force it to 32 bits */
context->Length_High &= 0xFFFFFFFF; context->Length_High &= 0xFFFFFFFF;
if (context->Length_High == 0) if (context->Length_High == 0)
{ {
/* Message is too long */ /* Message is too long */
context->Corrupted = 1; context->Corrupted = 1;
} }
} }
if (context->Message_Block_Index == 64) if (context->Message_Block_Index == 64)
{ {
SHA1ProcessMessageBlock(context); SHA1ProcessMessageBlock(context);
} }
message_array++; message_array++;
} }
} }
@ -210,11 +210,11 @@ void SHA1ProcessMessageBlock(SHA1Context *context)
{ {
const unsigned K[] = /* Constants defined in SHA-1 */ const unsigned K[] = /* Constants defined in SHA-1 */
{ {
0x5A827999, 0x5A827999,
0x6ED9EBA1, 0x6ED9EBA1,
0x8F1BBCDC, 0x8F1BBCDC,
0xCA62C1D6 0xCA62C1D6
}; };
int t; /* Loop counter */ int t; /* Loop counter */
unsigned temp; /* Temporary word value */ unsigned temp; /* Temporary word value */
unsigned W[80]; /* Word sequence */ unsigned W[80]; /* Word sequence */
@ -225,15 +225,15 @@ void SHA1ProcessMessageBlock(SHA1Context *context)
*/ */
for(t = 0; t < 16; t++) for(t = 0; t < 16; t++)
{ {
W[t] = ((unsigned) context->Message_Block[t * 4]) << 24; W[t] = ((unsigned) context->Message_Block[t * 4]) << 24;
W[t] |= ((unsigned) context->Message_Block[t * 4 + 1]) << 16; W[t] |= ((unsigned) context->Message_Block[t * 4 + 1]) << 16;
W[t] |= ((unsigned) context->Message_Block[t * 4 + 2]) << 8; W[t] |= ((unsigned) context->Message_Block[t * 4 + 2]) << 8;
W[t] |= ((unsigned) context->Message_Block[t * 4 + 3]); W[t] |= ((unsigned) context->Message_Block[t * 4 + 3]);
} }
for(t = 16; t < 80; t++) for(t = 16; t < 80; t++)
{ {
W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
} }
A = context->Message_Digest[0]; A = context->Message_Digest[0];
@ -244,60 +244,60 @@ void SHA1ProcessMessageBlock(SHA1Context *context)
for(t = 0; t < 20; t++) for(t = 0; t < 20; t++)
{ {
temp = SHA1CircularShift(5,A) + temp = SHA1CircularShift(5,A) +
((B & C) | ((~B) & D)) + E + W[t] + K[0]; ((B & C) | ((~B) & D)) + E + W[t] + K[0];
temp &= 0xFFFFFFFF; temp &= 0xFFFFFFFF;
E = D; E = D;
D = C; D = C;
C = SHA1CircularShift(30,B); C = SHA1CircularShift(30,B);
B = A; B = A;
A = temp; A = temp;
} }
for(t = 20; t < 40; t++) for(t = 20; t < 40; t++)
{ {
temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1];
temp &= 0xFFFFFFFF; temp &= 0xFFFFFFFF;
E = D; E = D;
D = C; D = C;
C = SHA1CircularShift(30,B); C = SHA1CircularShift(30,B);
B = A; B = A;
A = temp; A = temp;
} }
for(t = 40; t < 60; t++) for(t = 40; t < 60; t++)
{ {
temp = SHA1CircularShift(5,A) + temp = SHA1CircularShift(5,A) +
((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2];
temp &= 0xFFFFFFFF; temp &= 0xFFFFFFFF;
E = D; E = D;
D = C; D = C;
C = SHA1CircularShift(30,B); C = SHA1CircularShift(30,B);
B = A; B = A;
A = temp; A = temp;
} }
for(t = 60; t < 80; t++) for(t = 60; t < 80; t++)
{ {
temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3];
temp &= 0xFFFFFFFF; temp &= 0xFFFFFFFF;
E = D; E = D;
D = C; D = C;
C = SHA1CircularShift(30,B); C = SHA1CircularShift(30,B);
B = A; B = A;
A = temp; A = temp;
} }
context->Message_Digest[0] = context->Message_Digest[0] =
(context->Message_Digest[0] + A) & 0xFFFFFFFF; (context->Message_Digest[0] + A) & 0xFFFFFFFF;
context->Message_Digest[1] = context->Message_Digest[1] =
(context->Message_Digest[1] + B) & 0xFFFFFFFF; (context->Message_Digest[1] + B) & 0xFFFFFFFF;
context->Message_Digest[2] = context->Message_Digest[2] =
(context->Message_Digest[2] + C) & 0xFFFFFFFF; (context->Message_Digest[2] + C) & 0xFFFFFFFF;
context->Message_Digest[3] = context->Message_Digest[3] =
(context->Message_Digest[3] + D) & 0xFFFFFFFF; (context->Message_Digest[3] + D) & 0xFFFFFFFF;
context->Message_Digest[4] = context->Message_Digest[4] =
(context->Message_Digest[4] + E) & 0xFFFFFFFF; (context->Message_Digest[4] + E) & 0xFFFFFFFF;
context->Message_Block_Index = 0; context->Message_Block_Index = 0;
} }
@ -335,26 +335,26 @@ void SHA1PadMessage(SHA1Context *context)
*/ */
if (context->Message_Block_Index > 55) if (context->Message_Block_Index > 55)
{ {
context->Message_Block[context->Message_Block_Index++] = 0x80; context->Message_Block[context->Message_Block_Index++] = 0x80;
while(context->Message_Block_Index < 64) while(context->Message_Block_Index < 64)
{ {
context->Message_Block[context->Message_Block_Index++] = 0; context->Message_Block[context->Message_Block_Index++] = 0;
} }
SHA1ProcessMessageBlock(context); SHA1ProcessMessageBlock(context);
while(context->Message_Block_Index < 56) while(context->Message_Block_Index < 56)
{ {
context->Message_Block[context->Message_Block_Index++] = 0; context->Message_Block[context->Message_Block_Index++] = 0;
} }
} }
else else
{ {
context->Message_Block[context->Message_Block_Index++] = 0x80; context->Message_Block[context->Message_Block_Index++] = 0x80;
while(context->Message_Block_Index < 56) while(context->Message_Block_Index < 56)
{ {
context->Message_Block[context->Message_Block_Index++] = 0; context->Message_Block[context->Message_Block_Index++] = 0;
} }
} }
/* /*
@ -374,23 +374,23 @@ void SHA1PadMessage(SHA1Context *context)
Uint8* getSha1( Uint8 * stuff, Uint32 stuff_size ) Uint8* getSha1( Uint8 * stuff, Uint32 stuff_size )
{ {
SHA1Context sha; SHA1Context sha;
SHA1Reset( &sha ); SHA1Reset( &sha );
SHA1Input( &sha, (const Uint8*)stuff, stuff_size ); SHA1Input( &sha, (const Uint8*)stuff, stuff_size );
if( !SHA1Result( &sha ) ) if( !SHA1Result( &sha ) )
return 0; return 0;
Uint8* ret = new Uint8[20]; Uint8* ret = new Uint8[20];
memset(ret, 0, 20); memset(ret, 0, 20);
for( int i = 0; i < 5 ; i++ ) for( int i = 0; i < 5 ; i++ )
{ {
int val = sha.Message_Digest[ i ]; int val = sha.Message_Digest[ i ];
if (!isSystemBigEndian()) if (!isSystemBigEndian())
val = swap32(val); val = swap32(val);
memcpy( (char*)ret + ( i * 4 ), &val, 4 ); memcpy( (char*)ret + ( i * 4 ), &val, 4 );
} }
return ret; return ret;
} }

View File

@ -95,10 +95,70 @@ double swapDouble(double val)
retFloat[1] = convFloat[6]; retFloat[1] = convFloat[6];
retFloat[2] = convFloat[5]; retFloat[2] = convFloat[5];
retFloat[3] = convFloat[4]; retFloat[3] = convFloat[4];
retFloat[0] = convFloat[3]; retFloat[4] = convFloat[3];
retFloat[1] = convFloat[2]; retFloat[5] = convFloat[2];
retFloat[2] = convFloat[1]; retFloat[6] = convFloat[1];
retFloat[3] = convFloat[0]; retFloat[7] = convFloat[0];
return (double)((Uint64)retVal); return (double)((Uint64)retVal);
} }
//src points to the yaz0 source data (to the "real" source data, not at the header!)
//dst points to a buffer uncompressedSize bytes large (you get uncompressedSize from
//the second 4 bytes in the Yaz0 header).
void yaz0Decode(Uint8* src, Uint8* dst, Uint32 uncompressedSize)
{
Uint32 srcPlace = 0, dstPlace = 0; //current read/write positions
Int32 validBitCount = 0; //number of valid bits left in "code" byte
Uint8 currCodeByte;
while(dstPlace < uncompressedSize)
{
//read new "code" byte if the current one is used up
if(validBitCount == 0)
{
currCodeByte = src[srcPlace];
++srcPlace;
validBitCount = 8;
}
if((currCodeByte & 0x80) != 0)
{
//straight copy
dst[dstPlace] = src[srcPlace];
dstPlace++;
srcPlace++;
}
else
{
//RLE part
Uint8 byte1 = src[srcPlace];
Uint8 byte2 = src[srcPlace + 1];
srcPlace += 2;
Uint32 dist = ((byte1 & 0xF) << 8) | byte2;
Uint32 copySource = dstPlace - (dist + 1);
Uint32 numBytes = byte1 >> 4;
if(numBytes == 0)
{
numBytes = src[srcPlace] + 0x12;
srcPlace++;
}
else
numBytes += 2;
//copy run
for(Uint32 i = 0; i < numBytes; ++i)
{
dst[dstPlace] = dst[copySource];
copySource++;
dstPlace++;
}
}
//use next bit from "code" byte
currCodeByte <<= 1;
validBitCount-=1;
}
}