CRLF -> LF

This commit is contained in:
Vitaly Takmazov 2015-10-15 16:20:02 +03:00
parent 43d2022093
commit a25edefbb8
37 changed files with 9964 additions and 9964 deletions

View file

@ -1,61 +1,61 @@
Prerequisites Prerequisites
============= =============
1. Microsoft Visual C++ 2010 Express or higher edition (http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express) 1. Microsoft Visual C++ 2010 Express or higher edition (http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express)
2. Git for Windows (http://code.google.com/p/msysgit/downloads/list) 2. Git for Windows (http://code.google.com/p/msysgit/downloads/list)
3. CMake 2.8 or newer (http://www.cmake.org/cmake/resources/software.html) 3. CMake 2.8 or newer (http://www.cmake.org/cmake/resources/software.html)
4. Python 2.x for Swiften build scripts (scons) (http://www.python.org) 4. Python 2.x for Swiften build scripts (scons) (http://www.python.org)
Libraries Libraries
========= =========
3. Swiften library (http://swift.im/git/swift) 3. Swiften library (http://swift.im/git/swift)
4. Boost 1.48 or newer (http://sourceforge.net/projects/boost/files/boost/1.49.0/) 4. Boost 1.48 or newer (http://sourceforge.net/projects/boost/files/boost/1.49.0/)
5. Google ProtoBuf library (http://code.google.com/p/protobuf/downloads/list) 5. Google ProtoBuf library (http://code.google.com/p/protobuf/downloads/list)
Environment Environment
=========== ===========
To create spectrum build environment do: To create spectrum build environment do:
0. Create directory where we'll install all dependencies, e.g. C:\env-msvc-x64. 0. Create directory where we'll install all dependencies, e.g. C:\env-msvc-x64.
Create C:\env-msvc-x64\bin and add it to %PATH%. Create C:\env-msvc-x64\bin and add it to %PATH%.
Assuming you have git, python and cmake in %PATH%, Assuming you have git, python and cmake in %PATH%,
launch "Visual Studio 2010 command prompt" or launch "Visual Studio 2010 command prompt" or
"Visual Studio 2010(x64) command prompt", depends on your target (Windows x86 or Windows x86_64). "Visual Studio 2010(x64) command prompt", depends on your target (Windows x86 or Windows x86_64).
1. unpack and build boost libraries: 1. unpack and build boost libraries:
bootstrap.bat bootstrap.bat
b2.exe --without-mpi --without-python b2.exe --without-mpi --without-python
b2.exe --without-mpi --without-python install --prefix=C:\env-msvc-x64 release b2.exe --without-mpi --without-python install --prefix=C:\env-msvc-x64 release
2. clone swift repository and build it. Don't forget to point it to our env directory: 2. clone swift repository and build it. Don't forget to point it to our env directory:
git clone git://swift.im/swift git clone git://swift.im/swift
cd swift cd swift
echo boost_includedir="c:/env-msvc-x64/include/boost-1_49" > config.py echo boost_includedir="c:/env-msvc-x64/include/boost-1_49" > config.py
echo boost_libdir="c:/env-msvc-x64/lib" >> config.py echo boost_libdir="c:/env-msvc-x64/lib" >> config.py
scons.bat debug=no SWIFTEN_INSTALLDIR=C:\env-msvc-x64 force_configure=1 scons.bat debug=no SWIFTEN_INSTALLDIR=C:\env-msvc-x64 force_configure=1
scons.bat debug=no SWIFTEN_INSTALLDIR=C:\env-msvc-x64 C:\env-msvc-x64 scons.bat debug=no SWIFTEN_INSTALLDIR=C:\env-msvc-x64 C:\env-msvc-x64
3. unpack and compile protobuf as described in its documentation. 3. unpack and compile protobuf as described in its documentation.
Run extract_includes.bat in vsprojects/ directory and move resulting vsprojects/include/google/ directory to our C:\env-msvc-x64\include Run extract_includes.bat in vsprojects/ directory and move resulting vsprojects/include/google/ directory to our C:\env-msvc-x64\include
Move protoc.exe to C:\env-msvc-x64\bin\ and libprotobuf.lib to C:\env-msvc-x64\lib Move protoc.exe to C:\env-msvc-x64\bin\ and libprotobuf.lib to C:\env-msvc-x64\lib
4. Install gtkmm 4. Install gtkmm
Download installer from https://live.gnome.org/gtkmm/MSWindows and install gtkmm into C:\env-msvc-x64\ Download installer from https://live.gnome.org/gtkmm/MSWindows and install gtkmm into C:\env-msvc-x64\
5. Install libpurple headers 5. Install libpurple headers
Download http://www.pidgin.im/download/source/ , extract it and copy libpurple directory in C:\env-msvc-x64\include Download http://www.pidgin.im/download/source/ , extract it and copy libpurple directory in C:\env-msvc-x64\include
6. You're ready! :) Clone libtransport into C:\env-msvc-x64\libtransport (You *must* clone it into this directory, because libtransport will try to find the dependencies in ../lib and ../include) 6. You're ready! :) Clone libtransport into C:\env-msvc-x64\libtransport (You *must* clone it into this directory, because libtransport will try to find the dependencies in ../lib and ../include)
Compile it as: Compile it as:
set CMAKE_INCLUDE_PATH=C:\env-msvc-x64\include set CMAKE_INCLUDE_PATH=C:\env-msvc-x64\include
cmake . -G "NMake Makefiles" -DBOOST_INCLUDEDIR=../include/boost-1_49 -DBOOST_LIBRARYDIR=../lib -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=C:\env-msvc-x64 -DGIT_EXECUTABLE="c:\Program Files (x86)\git\bin\git.exe" cmake . -G "NMake Makefiles" -DBOOST_INCLUDEDIR=../include/boost-1_49 -DBOOST_LIBRARYDIR=../lib -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=C:\env-msvc-x64 -DGIT_EXECUTABLE="c:\Program Files (x86)\git\bin\git.exe"
nmake nmake

View file

@ -1,12 +1,12 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
ADD_SUBDIRECTORY(dfrotz) ADD_SUBDIRECTORY(dfrotz)
FILE(GLOB SRC *.c *.cpp) FILE(GLOB SRC *.c *.cpp)
ADD_EXECUTABLE(spectrum2_frotz_backend ${SRC}) ADD_EXECUTABLE(spectrum2_frotz_backend ${SRC})
target_link_libraries(spectrum2_frotz_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES}) target_link_libraries(spectrum2_frotz_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
INSTALL(TARGETS spectrum2_frotz_backend RUNTIME DESTINATION bin) INSTALL(TARGETS spectrum2_frotz_backend RUNTIME DESTINATION bin)

View file

@ -1,9 +1,9 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SRC common/*.c dumb/*.c) FILE(GLOB SRC common/*.c dumb/*.c)
ADD_EXECUTABLE(dfrotz ${SRC}) ADD_EXECUTABLE(dfrotz ${SRC})
# target_link_libraries(dfrotz) # target_link_libraries(dfrotz)
INSTALL(TARGETS dfrotz RUNTIME DESTINATION bin) INSTALL(TARGETS dfrotz RUNTIME DESTINATION bin)

View file

@ -1,13 +1,13 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SRC *.cpp) FILE(GLOB SRC *.cpp)
FILE(GLOB HEADERS *.h) FILE(GLOB HEADERS *.h)
QT4_WRAP_CPP(SRC ${HEADERS} OPTIONS -DBOOST_TT_HAS_OPERATOR_HPP_INCLUDED) QT4_WRAP_CPP(SRC ${HEADERS} OPTIONS -DBOOST_TT_HAS_OPERATOR_HPP_INCLUDED)
ADD_EXECUTABLE(spectrum2_libcommuni_backend ${SRC}) ADD_EXECUTABLE(spectrum2_libcommuni_backend ${SRC})
if (NOT WIN32) if (NOT WIN32)
target_link_libraries(spectrum2_libcommuni_backend ${IRC_LIBRARY} ${QT_LIBRARIES} transport pthread) target_link_libraries(spectrum2_libcommuni_backend ${IRC_LIBRARY} ${QT_LIBRARIES} transport pthread)
else () else ()
target_link_libraries(spectrum2_libcommuni_backend ${IRC_LIBRARY} ${QT_LIBRARIES} transport) target_link_libraries(spectrum2_libcommuni_backend ${IRC_LIBRARY} ${QT_LIBRARIES} transport)
endif() endif()
INSTALL(TARGETS spectrum2_libcommuni_backend RUNTIME DESTINATION bin) INSTALL(TARGETS spectrum2_libcommuni_backend RUNTIME DESTINATION bin)

View file

@ -1,17 +1,17 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SRC *.cpp) FILE(GLOB SRC *.cpp)
ADD_EXECUTABLE(spectrum2_libpurple_backend ${SRC}) ADD_EXECUTABLE(spectrum2_libpurple_backend ${SRC})
if(CMAKE_COMPILER_IS_GNUCXX) if(CMAKE_COMPILER_IS_GNUCXX)
if (NOT WIN32) if (NOT WIN32)
target_link_libraries(spectrum2_libpurple_backend ${PURPLE_LIBRARY} ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport-plugin pthread) target_link_libraries(spectrum2_libpurple_backend ${PURPLE_LIBRARY} ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport-plugin pthread)
else() else()
target_link_libraries(spectrum2_libpurple_backend ${PURPLE_LIBRARY} ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport-plugin) target_link_libraries(spectrum2_libpurple_backend ${PURPLE_LIBRARY} ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport-plugin)
endif() endif()
else() else()
target_link_libraries(spectrum2_libpurple_backend sqlite3 ${PURPLE_LIBRARY} ${GLIB2_LIBRARIES} ${LIBXML2_LIBRARIES} ${EVENT_LIBRARIES} transport-plugin ${PROTOBUF_LIBRARY}) target_link_libraries(spectrum2_libpurple_backend sqlite3 ${PURPLE_LIBRARY} ${GLIB2_LIBRARIES} ${LIBXML2_LIBRARIES} ${EVENT_LIBRARIES} transport-plugin ${PROTOBUF_LIBRARY})
endif() endif()
INSTALL(TARGETS spectrum2_libpurple_backend RUNTIME DESTINATION bin) INSTALL(TARGETS spectrum2_libpurple_backend RUNTIME DESTINATION bin)

View file

@ -1,14 +1,14 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB_RECURSE SRC *.c *.cpp) FILE(GLOB_RECURSE SRC *.c *.cpp)
ADD_DEFINITIONS(-DHAVE_STDINT_H=1) ADD_DEFINITIONS(-DHAVE_STDINT_H=1)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/yahoo) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/yahoo)
ADD_EXECUTABLE(spectrum2_libyahoo2_backend ${SRC}) ADD_EXECUTABLE(spectrum2_libyahoo2_backend ${SRC})
target_link_libraries(spectrum2_libyahoo2_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES}) target_link_libraries(spectrum2_libyahoo2_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
INSTALL(TARGETS spectrum2_libyahoo2_backend RUNTIME DESTINATION bin) INSTALL(TARGETS spectrum2_libyahoo2_backend RUNTIME DESTINATION bin)

View file

@ -1,9 +1,9 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SRC *.cpp) FILE(GLOB SRC *.cpp)
ADD_EXECUTABLE(spectrum2_skype_backend ${SRC}) ADD_EXECUTABLE(spectrum2_skype_backend ${SRC})
target_link_libraries(spectrum2_skype_backend ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport pthread ${LIBDBUSGLIB_LIBRARIES}) target_link_libraries(spectrum2_skype_backend ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport pthread ${LIBDBUSGLIB_LIBRARIES})
INSTALL(TARGETS spectrum2_skype_backend RUNTIME DESTINATION bin) INSTALL(TARGETS spectrum2_skype_backend RUNTIME DESTINATION bin)

View file

@ -1,10 +1,10 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SRC *.c *.cpp) FILE(GLOB SRC *.c *.cpp)
ADD_EXECUTABLE(spectrum2_smstools3_backend ${SRC}) ADD_EXECUTABLE(spectrum2_smstools3_backend ${SRC})
target_link_libraries(spectrum2_smstools3_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES}) target_link_libraries(spectrum2_smstools3_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
INSTALL(TARGETS spectrum2_smstools3_backend RUNTIME DESTINATION bin) INSTALL(TARGETS spectrum2_smstools3_backend RUNTIME DESTINATION bin)

View file

@ -1,14 +1,14 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SRC *.cpp) FILE(GLOB SRC *.cpp)
ADD_EXECUTABLE(spectrum2_swiften_backend ${SRC}) ADD_EXECUTABLE(spectrum2_swiften_backend ${SRC})
IF (NOT WIN32) IF (NOT WIN32)
target_link_libraries(spectrum2_swiften_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES}) target_link_libraries(spectrum2_swiften_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
else() else()
target_link_libraries(spectrum2_swiften_backend transport ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES}) target_link_libraries(spectrum2_swiften_backend transport ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
endif() endif()
INSTALL(TARGETS spectrum2_swiften_backend RUNTIME DESTINATION bin) INSTALL(TARGETS spectrum2_swiften_backend RUNTIME DESTINATION bin)

View file

@ -1,18 +1,18 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SRC *.c *.cpp) FILE(GLOB SRC *.c *.cpp)
ADD_EXECUTABLE(spectrum2_template_backend ${SRC}) ADD_EXECUTABLE(spectrum2_template_backend ${SRC})
if (CMAKE_COMPILER_IS_GNUCXX) if (CMAKE_COMPILER_IS_GNUCXX)
if (NOT WIN32) if (NOT WIN32)
target_link_libraries(spectrum2_template_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES}) target_link_libraries(spectrum2_template_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
else() else()
target_link_libraries(spectrum2_template_backend transport ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES}) target_link_libraries(spectrum2_template_backend transport ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
endif() endif()
else() else()
target_link_libraries(spectrum2_template_backend transport ${PROTOBUF_LIBRARY} ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES}) target_link_libraries(spectrum2_template_backend transport ${PROTOBUF_LIBRARY} ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
endif() endif()
#INSTALL(TARGETS spectrum2_template_backend RUNTIME DESTINATION bin) #INSTALL(TARGETS spectrum2_template_backend RUNTIME DESTINATION bin)

View file

@ -1,64 +1,64 @@
//****************************************************************************** //******************************************************************************
//* HMAC_SHA1.cpp : Implementation of HMAC SHA1 algorithm //* HMAC_SHA1.cpp : Implementation of HMAC SHA1 algorithm
//* Comfort to RFC 2104 //* Comfort to RFC 2104
//* //*
//****************************************************************************** //******************************************************************************
#include "HMAC_SHA1.h" #include "HMAC_SHA1.h"
#include <iostream> #include <iostream>
#include <memory> #include <memory>
void CHMAC_SHA1::HMAC_SHA1(BYTE *text, int text_len, BYTE *key, int key_len, BYTE *digest) void CHMAC_SHA1::HMAC_SHA1(BYTE *text, int text_len, BYTE *key, int key_len, BYTE *digest)
{ {
memset(SHA1_Key, 0, SHA1_BLOCK_SIZE); memset(SHA1_Key, 0, SHA1_BLOCK_SIZE);
/* repeated 64 times for values in ipad and opad */ /* repeated 64 times for values in ipad and opad */
memset(m_ipad, 0x36, sizeof(m_ipad)); memset(m_ipad, 0x36, sizeof(m_ipad));
memset(m_opad, 0x5c, sizeof(m_opad)); memset(m_opad, 0x5c, sizeof(m_opad));
/* STEP 1 */ /* STEP 1 */
if (key_len > SHA1_BLOCK_SIZE) if (key_len > SHA1_BLOCK_SIZE)
{ {
CSHA1::Reset(); CSHA1::Reset();
CSHA1::Update((UINT_8 *)key, key_len); CSHA1::Update((UINT_8 *)key, key_len);
CSHA1::Final(); CSHA1::Final();
CSHA1::GetHash((UINT_8 *)SHA1_Key); CSHA1::GetHash((UINT_8 *)SHA1_Key);
} }
else else
memcpy(SHA1_Key, key, key_len); memcpy(SHA1_Key, key, key_len);
/* STEP 2 */ /* STEP 2 */
for (size_t i=0; i<sizeof(m_ipad); i++) for (size_t i=0; i<sizeof(m_ipad); i++)
{ {
m_ipad[i] ^= SHA1_Key[i]; m_ipad[i] ^= SHA1_Key[i];
} }
/* STEP 3 */ /* STEP 3 */
memcpy(AppendBuf1, m_ipad, sizeof(m_ipad)); memcpy(AppendBuf1, m_ipad, sizeof(m_ipad));
memcpy(AppendBuf1 + sizeof(m_ipad), text, text_len); memcpy(AppendBuf1 + sizeof(m_ipad), text, text_len);
/* STEP 4 */ /* STEP 4 */
CSHA1::Reset(); CSHA1::Reset();
CSHA1::Update((UINT_8 *)AppendBuf1, sizeof(m_ipad) + text_len); CSHA1::Update((UINT_8 *)AppendBuf1, sizeof(m_ipad) + text_len);
CSHA1::Final(); CSHA1::Final();
CSHA1::GetHash((UINT_8 *)szReport); CSHA1::GetHash((UINT_8 *)szReport);
/* STEP 5 */ /* STEP 5 */
for (size_t j=0; j<sizeof(m_opad); j++) for (size_t j=0; j<sizeof(m_opad); j++)
{ {
m_opad[j] ^= SHA1_Key[j]; m_opad[j] ^= SHA1_Key[j];
} }
/* STEP 6 */ /* STEP 6 */
memcpy(AppendBuf2, m_opad, sizeof(m_opad)); memcpy(AppendBuf2, m_opad, sizeof(m_opad));
memcpy(AppendBuf2 + sizeof(m_opad), szReport, SHA1_DIGEST_LENGTH); memcpy(AppendBuf2 + sizeof(m_opad), szReport, SHA1_DIGEST_LENGTH);
/*STEP 7 */ /*STEP 7 */
CSHA1::Reset(); CSHA1::Reset();
CSHA1::Update((UINT_8 *)AppendBuf2, sizeof(m_opad) + SHA1_DIGEST_LENGTH); CSHA1::Update((UINT_8 *)AppendBuf2, sizeof(m_opad) + SHA1_DIGEST_LENGTH);
CSHA1::Final(); CSHA1::Final();
CSHA1::GetHash((UINT_8 *)digest); CSHA1::GetHash((UINT_8 *)digest);
} }

View file

@ -1,53 +1,53 @@
/* /*
100% free public domain implementation of the HMAC-SHA1 algorithm 100% free public domain implementation of the HMAC-SHA1 algorithm
by Chien-Chung, Chung (Jim Chung) <jimchung1221@gmail.com> by Chien-Chung, Chung (Jim Chung) <jimchung1221@gmail.com>
*/ */
#ifndef __HMAC_SHA1_H__ #ifndef __HMAC_SHA1_H__
#define __HMAC_SHA1_H__ #define __HMAC_SHA1_H__
#include "SHA1.h" #include "SHA1.h"
typedef unsigned char BYTE ; typedef unsigned char BYTE ;
class CHMAC_SHA1 : public CSHA1 class CHMAC_SHA1 : public CSHA1
{ {
private: private:
BYTE m_ipad[64]; BYTE m_ipad[64];
BYTE m_opad[64]; BYTE m_opad[64];
char * szReport ; char * szReport ;
char * SHA1_Key ; char * SHA1_Key ;
char * AppendBuf1 ; char * AppendBuf1 ;
char * AppendBuf2 ; char * AppendBuf2 ;
public: public:
enum { enum {
SHA1_DIGEST_LENGTH = 20, SHA1_DIGEST_LENGTH = 20,
SHA1_BLOCK_SIZE = 64, SHA1_BLOCK_SIZE = 64,
HMAC_BUF_LEN = 4096 HMAC_BUF_LEN = 4096
} ; } ;
CHMAC_SHA1() CHMAC_SHA1()
:szReport(new char[HMAC_BUF_LEN]), :szReport(new char[HMAC_BUF_LEN]),
SHA1_Key(new char[HMAC_BUF_LEN]), SHA1_Key(new char[HMAC_BUF_LEN]),
AppendBuf1(new char[HMAC_BUF_LEN]), AppendBuf1(new char[HMAC_BUF_LEN]),
AppendBuf2(new char[HMAC_BUF_LEN]) AppendBuf2(new char[HMAC_BUF_LEN])
{} {}
~CHMAC_SHA1() ~CHMAC_SHA1()
{ {
delete[] szReport ; delete[] szReport ;
delete[] AppendBuf1 ; delete[] AppendBuf1 ;
delete[] AppendBuf2 ; delete[] AppendBuf2 ;
delete[] SHA1_Key ; delete[] SHA1_Key ;
} }
void HMAC_SHA1(BYTE *text, int text_len, BYTE *key, int key_len, BYTE *digest); void HMAC_SHA1(BYTE *text, int text_len, BYTE *key, int key_len, BYTE *digest);
}; };
#endif /* __HMAC_SHA1_H__ */ #endif /* __HMAC_SHA1_H__ */

View file

@ -1,274 +1,274 @@
/* /*
100% free public domain implementation of the SHA-1 algorithm 100% free public domain implementation of the SHA-1 algorithm
by Dominik Reichl <dominik.reichl@t-online.de> by Dominik Reichl <dominik.reichl@t-online.de>
Web: http://www.dominik-reichl.de/ Web: http://www.dominik-reichl.de/
Version 1.6 - 2005-02-07 (thanks to Howard Kapustein for patches) Version 1.6 - 2005-02-07 (thanks to Howard Kapustein for patches)
- You can set the endianness in your files, no need to modify the - You can set the endianness in your files, no need to modify the
header file of the CSHA1 class any more header file of the CSHA1 class any more
- Aligned data support - Aligned data support
- Made support/compilation of the utility functions (ReportHash - Made support/compilation of the utility functions (ReportHash
and HashFile) optional (useful, if bytes count, for example in and HashFile) optional (useful, if bytes count, for example in
embedded environments) embedded environments)
Version 1.5 - 2005-01-01 Version 1.5 - 2005-01-01
- 64-bit compiler compatibility added - 64-bit compiler compatibility added
- Made variable wiping optional (define SHA1_WIPE_VARIABLES) - Made variable wiping optional (define SHA1_WIPE_VARIABLES)
- Removed unnecessary variable initializations - Removed unnecessary variable initializations
- ROL32 improvement for the Microsoft compiler (using _rotl) - ROL32 improvement for the Microsoft compiler (using _rotl)
======== Test Vectors (from FIPS PUB 180-1) ======== ======== Test Vectors (from FIPS PUB 180-1) ========
SHA1("abc") = SHA1("abc") =
A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") =
84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
SHA1(A million repetitions of "a") = SHA1(A million repetitions of "a") =
34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
*/ */
#include "SHA1.h" #include "SHA1.h"
#ifdef SHA1_UTILITY_FUNCTIONS #ifdef SHA1_UTILITY_FUNCTIONS
#define SHA1_MAX_FILE_BUFFER 8000 #define SHA1_MAX_FILE_BUFFER 8000
#endif #endif
// Rotate x bits to the left // Rotate x bits to the left
#ifndef ROL32 #ifndef ROL32
#ifdef _MSC_VER #ifdef _MSC_VER
#define ROL32(_val32, _nBits) _rotl(_val32, _nBits) #define ROL32(_val32, _nBits) _rotl(_val32, _nBits)
#else #else
#define ROL32(_val32, _nBits) (((_val32)<<(_nBits))|((_val32)>>(32-(_nBits)))) #define ROL32(_val32, _nBits) (((_val32)<<(_nBits))|((_val32)>>(32-(_nBits))))
#endif #endif
#endif #endif
#ifdef SHA1_LITTLE_ENDIAN #ifdef SHA1_LITTLE_ENDIAN
#define SHABLK0(i) (m_block->l[i] = \ #define SHABLK0(i) (m_block->l[i] = \
(ROL32(m_block->l[i],24) & 0xFF00FF00) | (ROL32(m_block->l[i],8) & 0x00FF00FF)) (ROL32(m_block->l[i],24) & 0xFF00FF00) | (ROL32(m_block->l[i],8) & 0x00FF00FF))
#else #else
#define SHABLK0(i) (m_block->l[i]) #define SHABLK0(i) (m_block->l[i])
#endif #endif
#define SHABLK(i) (m_block->l[i&15] = ROL32(m_block->l[(i+13)&15] ^ m_block->l[(i+8)&15] \ #define SHABLK(i) (m_block->l[i&15] = ROL32(m_block->l[(i+13)&15] ^ m_block->l[(i+8)&15] \
^ m_block->l[(i+2)&15] ^ m_block->l[i&15],1)) ^ m_block->l[(i+2)&15] ^ m_block->l[i&15],1))
// SHA-1 rounds // SHA-1 rounds
#define _R0(v,w,x,y,z,i) { z+=((w&(x^y))^y)+SHABLK0(i)+0x5A827999+ROL32(v,5); w=ROL32(w,30); } #define _R0(v,w,x,y,z,i) { z+=((w&(x^y))^y)+SHABLK0(i)+0x5A827999+ROL32(v,5); w=ROL32(w,30); }
#define _R1(v,w,x,y,z,i) { z+=((w&(x^y))^y)+SHABLK(i)+0x5A827999+ROL32(v,5); w=ROL32(w,30); } #define _R1(v,w,x,y,z,i) { z+=((w&(x^y))^y)+SHABLK(i)+0x5A827999+ROL32(v,5); w=ROL32(w,30); }
#define _R2(v,w,x,y,z,i) { z+=(w^x^y)+SHABLK(i)+0x6ED9EBA1+ROL32(v,5); w=ROL32(w,30); } #define _R2(v,w,x,y,z,i) { z+=(w^x^y)+SHABLK(i)+0x6ED9EBA1+ROL32(v,5); w=ROL32(w,30); }
#define _R3(v,w,x,y,z,i) { z+=(((w|x)&y)|(w&x))+SHABLK(i)+0x8F1BBCDC+ROL32(v,5); w=ROL32(w,30); } #define _R3(v,w,x,y,z,i) { z+=(((w|x)&y)|(w&x))+SHABLK(i)+0x8F1BBCDC+ROL32(v,5); w=ROL32(w,30); }
#define _R4(v,w,x,y,z,i) { z+=(w^x^y)+SHABLK(i)+0xCA62C1D6+ROL32(v,5); w=ROL32(w,30); } #define _R4(v,w,x,y,z,i) { z+=(w^x^y)+SHABLK(i)+0xCA62C1D6+ROL32(v,5); w=ROL32(w,30); }
CSHA1::CSHA1() CSHA1::CSHA1()
{ {
m_block = (SHA1_WORKSPACE_BLOCK *)m_workspace; m_block = (SHA1_WORKSPACE_BLOCK *)m_workspace;
Reset(); Reset();
} }
CSHA1::~CSHA1() CSHA1::~CSHA1()
{ {
Reset(); Reset();
} }
void CSHA1::Reset() void CSHA1::Reset()
{ {
// SHA1 initialization constants // SHA1 initialization constants
m_state[0] = 0x67452301; m_state[0] = 0x67452301;
m_state[1] = 0xEFCDAB89; m_state[1] = 0xEFCDAB89;
m_state[2] = 0x98BADCFE; m_state[2] = 0x98BADCFE;
m_state[3] = 0x10325476; m_state[3] = 0x10325476;
m_state[4] = 0xC3D2E1F0; m_state[4] = 0xC3D2E1F0;
m_count[0] = 0; m_count[0] = 0;
m_count[1] = 0; m_count[1] = 0;
} }
void CSHA1::Transform(UINT_32 *state, UINT_8 *buffer) void CSHA1::Transform(UINT_32 *state, UINT_8 *buffer)
{ {
// Copy state[] to working vars // Copy state[] to working vars
UINT_32 a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; UINT_32 a = state[0], b = state[1], c = state[2], d = state[3], e = state[4];
memcpy(m_block, buffer, 64); memcpy(m_block, buffer, 64);
// 4 rounds of 20 operations each. Loop unrolled. // 4 rounds of 20 operations each. Loop unrolled.
_R0(a,b,c,d,e, 0); _R0(e,a,b,c,d, 1); _R0(d,e,a,b,c, 2); _R0(c,d,e,a,b, 3); _R0(a,b,c,d,e, 0); _R0(e,a,b,c,d, 1); _R0(d,e,a,b,c, 2); _R0(c,d,e,a,b, 3);
_R0(b,c,d,e,a, 4); _R0(a,b,c,d,e, 5); _R0(e,a,b,c,d, 6); _R0(d,e,a,b,c, 7); _R0(b,c,d,e,a, 4); _R0(a,b,c,d,e, 5); _R0(e,a,b,c,d, 6); _R0(d,e,a,b,c, 7);
_R0(c,d,e,a,b, 8); _R0(b,c,d,e,a, 9); _R0(a,b,c,d,e,10); _R0(e,a,b,c,d,11); _R0(c,d,e,a,b, 8); _R0(b,c,d,e,a, 9); _R0(a,b,c,d,e,10); _R0(e,a,b,c,d,11);
_R0(d,e,a,b,c,12); _R0(c,d,e,a,b,13); _R0(b,c,d,e,a,14); _R0(a,b,c,d,e,15); _R0(d,e,a,b,c,12); _R0(c,d,e,a,b,13); _R0(b,c,d,e,a,14); _R0(a,b,c,d,e,15);
_R1(e,a,b,c,d,16); _R1(d,e,a,b,c,17); _R1(c,d,e,a,b,18); _R1(b,c,d,e,a,19); _R1(e,a,b,c,d,16); _R1(d,e,a,b,c,17); _R1(c,d,e,a,b,18); _R1(b,c,d,e,a,19);
_R2(a,b,c,d,e,20); _R2(e,a,b,c,d,21); _R2(d,e,a,b,c,22); _R2(c,d,e,a,b,23); _R2(a,b,c,d,e,20); _R2(e,a,b,c,d,21); _R2(d,e,a,b,c,22); _R2(c,d,e,a,b,23);
_R2(b,c,d,e,a,24); _R2(a,b,c,d,e,25); _R2(e,a,b,c,d,26); _R2(d,e,a,b,c,27); _R2(b,c,d,e,a,24); _R2(a,b,c,d,e,25); _R2(e,a,b,c,d,26); _R2(d,e,a,b,c,27);
_R2(c,d,e,a,b,28); _R2(b,c,d,e,a,29); _R2(a,b,c,d,e,30); _R2(e,a,b,c,d,31); _R2(c,d,e,a,b,28); _R2(b,c,d,e,a,29); _R2(a,b,c,d,e,30); _R2(e,a,b,c,d,31);
_R2(d,e,a,b,c,32); _R2(c,d,e,a,b,33); _R2(b,c,d,e,a,34); _R2(a,b,c,d,e,35); _R2(d,e,a,b,c,32); _R2(c,d,e,a,b,33); _R2(b,c,d,e,a,34); _R2(a,b,c,d,e,35);
_R2(e,a,b,c,d,36); _R2(d,e,a,b,c,37); _R2(c,d,e,a,b,38); _R2(b,c,d,e,a,39); _R2(e,a,b,c,d,36); _R2(d,e,a,b,c,37); _R2(c,d,e,a,b,38); _R2(b,c,d,e,a,39);
_R3(a,b,c,d,e,40); _R3(e,a,b,c,d,41); _R3(d,e,a,b,c,42); _R3(c,d,e,a,b,43); _R3(a,b,c,d,e,40); _R3(e,a,b,c,d,41); _R3(d,e,a,b,c,42); _R3(c,d,e,a,b,43);
_R3(b,c,d,e,a,44); _R3(a,b,c,d,e,45); _R3(e,a,b,c,d,46); _R3(d,e,a,b,c,47); _R3(b,c,d,e,a,44); _R3(a,b,c,d,e,45); _R3(e,a,b,c,d,46); _R3(d,e,a,b,c,47);
_R3(c,d,e,a,b,48); _R3(b,c,d,e,a,49); _R3(a,b,c,d,e,50); _R3(e,a,b,c,d,51); _R3(c,d,e,a,b,48); _R3(b,c,d,e,a,49); _R3(a,b,c,d,e,50); _R3(e,a,b,c,d,51);
_R3(d,e,a,b,c,52); _R3(c,d,e,a,b,53); _R3(b,c,d,e,a,54); _R3(a,b,c,d,e,55); _R3(d,e,a,b,c,52); _R3(c,d,e,a,b,53); _R3(b,c,d,e,a,54); _R3(a,b,c,d,e,55);
_R3(e,a,b,c,d,56); _R3(d,e,a,b,c,57); _R3(c,d,e,a,b,58); _R3(b,c,d,e,a,59); _R3(e,a,b,c,d,56); _R3(d,e,a,b,c,57); _R3(c,d,e,a,b,58); _R3(b,c,d,e,a,59);
_R4(a,b,c,d,e,60); _R4(e,a,b,c,d,61); _R4(d,e,a,b,c,62); _R4(c,d,e,a,b,63); _R4(a,b,c,d,e,60); _R4(e,a,b,c,d,61); _R4(d,e,a,b,c,62); _R4(c,d,e,a,b,63);
_R4(b,c,d,e,a,64); _R4(a,b,c,d,e,65); _R4(e,a,b,c,d,66); _R4(d,e,a,b,c,67); _R4(b,c,d,e,a,64); _R4(a,b,c,d,e,65); _R4(e,a,b,c,d,66); _R4(d,e,a,b,c,67);
_R4(c,d,e,a,b,68); _R4(b,c,d,e,a,69); _R4(a,b,c,d,e,70); _R4(e,a,b,c,d,71); _R4(c,d,e,a,b,68); _R4(b,c,d,e,a,69); _R4(a,b,c,d,e,70); _R4(e,a,b,c,d,71);
_R4(d,e,a,b,c,72); _R4(c,d,e,a,b,73); _R4(b,c,d,e,a,74); _R4(a,b,c,d,e,75); _R4(d,e,a,b,c,72); _R4(c,d,e,a,b,73); _R4(b,c,d,e,a,74); _R4(a,b,c,d,e,75);
_R4(e,a,b,c,d,76); _R4(d,e,a,b,c,77); _R4(c,d,e,a,b,78); _R4(b,c,d,e,a,79); _R4(e,a,b,c,d,76); _R4(d,e,a,b,c,77); _R4(c,d,e,a,b,78); _R4(b,c,d,e,a,79);
// Add the working vars back into state // Add the working vars back into state
state[0] += a; state[0] += a;
state[1] += b; state[1] += b;
state[2] += c; state[2] += c;
state[3] += d; state[3] += d;
state[4] += e; state[4] += e;
// Wipe variables // Wipe variables
#ifdef SHA1_WIPE_VARIABLES #ifdef SHA1_WIPE_VARIABLES
a = b = c = d = e = 0; a = b = c = d = e = 0;
#endif #endif
} }
// Use this function to hash in binary data and strings // Use this function to hash in binary data and strings
void CSHA1::Update(UINT_8 *data, UINT_32 len) void CSHA1::Update(UINT_8 *data, UINT_32 len)
{ {
UINT_32 i, j; UINT_32 i, j;
j = (m_count[0] >> 3) & 63; j = (m_count[0] >> 3) & 63;
if((m_count[0] += len << 3) < (len << 3)) m_count[1]++; if((m_count[0] += len << 3) < (len << 3)) m_count[1]++;
m_count[1] += (len >> 29); m_count[1] += (len >> 29);
if((j + len) > 63) if((j + len) > 63)
{ {
i = 64 - j; i = 64 - j;
memcpy(&m_buffer[j], data, i); memcpy(&m_buffer[j], data, i);
Transform(m_state, m_buffer); Transform(m_state, m_buffer);
for(; i + 63 < len; i += 64) Transform(m_state, &data[i]); for(; i + 63 < len; i += 64) Transform(m_state, &data[i]);
j = 0; j = 0;
} }
else i = 0; else i = 0;
memcpy(&m_buffer[j], &data[i], len - i); memcpy(&m_buffer[j], &data[i], len - i);
} }
#ifdef SHA1_UTILITY_FUNCTIONS #ifdef SHA1_UTILITY_FUNCTIONS
// Hash in file contents // Hash in file contents
bool CSHA1::HashFile(char *szFileName) bool CSHA1::HashFile(char *szFileName)
{ {
unsigned long ulFileSize, ulRest, ulBlocks; unsigned long ulFileSize, ulRest, ulBlocks;
unsigned long i; unsigned long i;
UINT_8 uData[SHA1_MAX_FILE_BUFFER]; UINT_8 uData[SHA1_MAX_FILE_BUFFER];
FILE *fIn; FILE *fIn;
if(szFileName == NULL) return false; if(szFileName == NULL) return false;
fIn = fopen(szFileName, "rb"); fIn = fopen(szFileName, "rb");
if(fIn == NULL) return false; if(fIn == NULL) return false;
fseek(fIn, 0, SEEK_END); fseek(fIn, 0, SEEK_END);
ulFileSize = (unsigned long)ftell(fIn); ulFileSize = (unsigned long)ftell(fIn);
fseek(fIn, 0, SEEK_SET); fseek(fIn, 0, SEEK_SET);
if(ulFileSize != 0) if(ulFileSize != 0)
{ {
ulBlocks = ulFileSize / SHA1_MAX_FILE_BUFFER; ulBlocks = ulFileSize / SHA1_MAX_FILE_BUFFER;
ulRest = ulFileSize % SHA1_MAX_FILE_BUFFER; ulRest = ulFileSize % SHA1_MAX_FILE_BUFFER;
} }
else else
{ {
ulBlocks = 0; ulBlocks = 0;
ulRest = 0; ulRest = 0;
} }
for(i = 0; i < ulBlocks; i++) for(i = 0; i < ulBlocks; i++)
{ {
fread(uData, 1, SHA1_MAX_FILE_BUFFER, fIn); fread(uData, 1, SHA1_MAX_FILE_BUFFER, fIn);
Update((UINT_8 *)uData, SHA1_MAX_FILE_BUFFER); Update((UINT_8 *)uData, SHA1_MAX_FILE_BUFFER);
} }
if(ulRest != 0) if(ulRest != 0)
{ {
fread(uData, 1, ulRest, fIn); fread(uData, 1, ulRest, fIn);
Update((UINT_8 *)uData, ulRest); Update((UINT_8 *)uData, ulRest);
} }
fclose(fIn); fIn = NULL; fclose(fIn); fIn = NULL;
return true; return true;
} }
#endif #endif
void CSHA1::Final() void CSHA1::Final()
{ {
UINT_32 i; UINT_32 i;
UINT_8 finalcount[8]; UINT_8 finalcount[8];
for(i = 0; i < 8; i++) for(i = 0; i < 8; i++)
finalcount[i] = (UINT_8)((m_count[((i >= 4) ? 0 : 1)] finalcount[i] = (UINT_8)((m_count[((i >= 4) ? 0 : 1)]
>> ((3 - (i & 3)) * 8) ) & 255); // Endian independent >> ((3 - (i & 3)) * 8) ) & 255); // Endian independent
Update((UINT_8 *)"\200", 1); Update((UINT_8 *)"\200", 1);
while ((m_count[0] & 504) != 448) while ((m_count[0] & 504) != 448)
Update((UINT_8 *)"\0", 1); Update((UINT_8 *)"\0", 1);
Update(finalcount, 8); // Cause a SHA1Transform() Update(finalcount, 8); // Cause a SHA1Transform()
for(i = 0; i < 20; i++) for(i = 0; i < 20; i++)
{ {
m_digest[i] = (UINT_8)((m_state[i >> 2] >> ((3 - (i & 3)) * 8) ) & 255); m_digest[i] = (UINT_8)((m_state[i >> 2] >> ((3 - (i & 3)) * 8) ) & 255);
} }
// Wipe variables for security reasons // Wipe variables for security reasons
#ifdef SHA1_WIPE_VARIABLES #ifdef SHA1_WIPE_VARIABLES
i = 0; i = 0;
memset(m_buffer, 0, 64); memset(m_buffer, 0, 64);
memset(m_state, 0, 20); memset(m_state, 0, 20);
memset(m_count, 0, 8); memset(m_count, 0, 8);
memset(finalcount, 0, 8); memset(finalcount, 0, 8);
Transform(m_state, m_buffer); Transform(m_state, m_buffer);
#endif #endif
} }
#ifdef SHA1_UTILITY_FUNCTIONS #ifdef SHA1_UTILITY_FUNCTIONS
// Get the final hash as a pre-formatted string // Get the final hash as a pre-formatted string
void CSHA1::ReportHash(char *szReport, unsigned char uReportType) void CSHA1::ReportHash(char *szReport, unsigned char uReportType)
{ {
unsigned char i; unsigned char i;
char szTemp[16]; char szTemp[16];
if(szReport == NULL) return; if(szReport == NULL) return;
if(uReportType == REPORT_HEX) if(uReportType == REPORT_HEX)
{ {
sprintf(szTemp, "%02X", m_digest[0]); sprintf(szTemp, "%02X", m_digest[0]);
strcat(szReport, szTemp); strcat(szReport, szTemp);
for(i = 1; i < 20; i++) for(i = 1; i < 20; i++)
{ {
sprintf(szTemp, " %02X", m_digest[i]); sprintf(szTemp, " %02X", m_digest[i]);
strcat(szReport, szTemp); strcat(szReport, szTemp);
} }
} }
else if(uReportType == REPORT_DIGIT) else if(uReportType == REPORT_DIGIT)
{ {
sprintf(szTemp, "%u", m_digest[0]); sprintf(szTemp, "%u", m_digest[0]);
strcat(szReport, szTemp); strcat(szReport, szTemp);
for(i = 1; i < 20; i++) for(i = 1; i < 20; i++)
{ {
sprintf(szTemp, " %u", m_digest[i]); sprintf(szTemp, " %u", m_digest[i]);
strcat(szReport, szTemp); strcat(szReport, szTemp);
} }
} }
else strcpy(szReport, "Error: Unknown report type!"); else strcpy(szReport, "Error: Unknown report type!");
} }
#endif #endif
// Get the raw message digest // Get the raw message digest
void CSHA1::GetHash(UINT_8 *puDest) void CSHA1::GetHash(UINT_8 *puDest)
{ {
memcpy(puDest, m_digest, 20); memcpy(puDest, m_digest, 20);
} }

View file

@ -1,148 +1,148 @@
/* /*
100% free public domain implementation of the SHA-1 algorithm 100% free public domain implementation of the SHA-1 algorithm
by Dominik Reichl <dominik.reichl@t-online.de> by Dominik Reichl <dominik.reichl@t-online.de>
Web: http://www.dominik-reichl.de/ Web: http://www.dominik-reichl.de/
Version 1.6 - 2005-02-07 (thanks to Howard Kapustein for patches) Version 1.6 - 2005-02-07 (thanks to Howard Kapustein for patches)
- You can set the endianness in your files, no need to modify the - You can set the endianness in your files, no need to modify the
header file of the CSHA1 class any more header file of the CSHA1 class any more
- Aligned data support - Aligned data support
- Made support/compilation of the utility functions (ReportHash - Made support/compilation of the utility functions (ReportHash
and HashFile) optional (useful, if bytes count, for example in and HashFile) optional (useful, if bytes count, for example in
embedded environments) embedded environments)
Version 1.5 - 2005-01-01 Version 1.5 - 2005-01-01
- 64-bit compiler compatibility added - 64-bit compiler compatibility added
- Made variable wiping optional (define SHA1_WIPE_VARIABLES) - Made variable wiping optional (define SHA1_WIPE_VARIABLES)
- Removed unnecessary variable initializations - Removed unnecessary variable initializations
- ROL32 improvement for the Microsoft compiler (using _rotl) - ROL32 improvement for the Microsoft compiler (using _rotl)
======== Test Vectors (from FIPS PUB 180-1) ======== ======== Test Vectors (from FIPS PUB 180-1) ========
SHA1("abc") = SHA1("abc") =
A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") =
84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
SHA1(A million repetitions of "a") = SHA1(A million repetitions of "a") =
34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
*/ */
#ifndef ___SHA1_HDR___ #ifndef ___SHA1_HDR___
#define ___SHA1_HDR___ #define ___SHA1_HDR___
#if !defined(SHA1_UTILITY_FUNCTIONS) && !defined(SHA1_NO_UTILITY_FUNCTIONS) #if !defined(SHA1_UTILITY_FUNCTIONS) && !defined(SHA1_NO_UTILITY_FUNCTIONS)
#define SHA1_UTILITY_FUNCTIONS #define SHA1_UTILITY_FUNCTIONS
#endif #endif
#include <memory.h> // Needed for memset and memcpy #include <memory.h> // Needed for memset and memcpy
#ifdef SHA1_UTILITY_FUNCTIONS #ifdef SHA1_UTILITY_FUNCTIONS
#include <stdio.h> // Needed for file access and sprintf #include <stdio.h> // Needed for file access and sprintf
#include <string.h> // Needed for strcat and strcpy #include <string.h> // Needed for strcat and strcpy
#endif #endif
#ifdef _MSC_VER #ifdef _MSC_VER
#include <stdlib.h> #include <stdlib.h>
#endif #endif
// You can define the endian mode in your files, without modifying the SHA1 // You can define the endian mode in your files, without modifying the SHA1
// source files. Just #define SHA1_LITTLE_ENDIAN or #define SHA1_BIG_ENDIAN // source files. Just #define SHA1_LITTLE_ENDIAN or #define SHA1_BIG_ENDIAN
// in your files, before including the SHA1.h header file. If you don't // in your files, before including the SHA1.h header file. If you don't
// define anything, the class defaults to little endian. // define anything, the class defaults to little endian.
#if !defined(SHA1_LITTLE_ENDIAN) && !defined(SHA1_BIG_ENDIAN) #if !defined(SHA1_LITTLE_ENDIAN) && !defined(SHA1_BIG_ENDIAN)
#define SHA1_LITTLE_ENDIAN #define SHA1_LITTLE_ENDIAN
#endif #endif
// Same here. If you want variable wiping, #define SHA1_WIPE_VARIABLES, if // Same here. If you want variable wiping, #define SHA1_WIPE_VARIABLES, if
// not, #define SHA1_NO_WIPE_VARIABLES. If you don't define anything, it // not, #define SHA1_NO_WIPE_VARIABLES. If you don't define anything, it
// defaults to wiping. // defaults to wiping.
#if !defined(SHA1_WIPE_VARIABLES) && !defined(SHA1_NO_WIPE_VARIABLES) #if !defined(SHA1_WIPE_VARIABLES) && !defined(SHA1_NO_WIPE_VARIABLES)
#define SHA1_WIPE_VARIABLES #define SHA1_WIPE_VARIABLES
#endif #endif
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Define 8- and 32-bit variables // Define 8- and 32-bit variables
#ifndef UINT_32 #ifndef UINT_32
#ifdef _MSC_VER #ifdef _MSC_VER
#define UINT_8 unsigned __int8 #define UINT_8 unsigned __int8
#define UINT_32 unsigned __int32 #define UINT_32 unsigned __int32
#else #else
#define UINT_8 unsigned char #define UINT_8 unsigned char
#if (ULONG_MAX == 0xFFFFFFFF) #if (ULONG_MAX == 0xFFFFFFFF)
#define UINT_32 unsigned long #define UINT_32 unsigned long
#else #else
#define UINT_32 unsigned int #define UINT_32 unsigned int
#endif #endif
#endif #endif
#endif #endif
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Declare SHA1 workspace // Declare SHA1 workspace
typedef union typedef union
{ {
UINT_8 c[64]; UINT_8 c[64];
UINT_32 l[16]; UINT_32 l[16];
} SHA1_WORKSPACE_BLOCK; } SHA1_WORKSPACE_BLOCK;
class CSHA1 class CSHA1
{ {
public: public:
#ifdef SHA1_UTILITY_FUNCTIONS #ifdef SHA1_UTILITY_FUNCTIONS
// Two different formats for ReportHash(...) // Two different formats for ReportHash(...)
enum enum
{ {
REPORT_HEX = 0, REPORT_HEX = 0,
REPORT_DIGIT = 1 REPORT_DIGIT = 1
}; };
#endif #endif
// Constructor and Destructor // Constructor and Destructor
CSHA1(); CSHA1();
~CSHA1(); ~CSHA1();
UINT_32 m_state[5]; UINT_32 m_state[5];
UINT_32 m_count[2]; UINT_32 m_count[2];
UINT_32 __reserved1[1]; UINT_32 __reserved1[1];
UINT_8 m_buffer[64]; UINT_8 m_buffer[64];
UINT_8 m_digest[20]; UINT_8 m_digest[20];
UINT_32 __reserved2[3]; UINT_32 __reserved2[3];
void Reset(); void Reset();
// Update the hash value // Update the hash value
void Update(UINT_8 *data, UINT_32 len); void Update(UINT_8 *data, UINT_32 len);
#ifdef SHA1_UTILITY_FUNCTIONS #ifdef SHA1_UTILITY_FUNCTIONS
bool HashFile(char *szFileName); bool HashFile(char *szFileName);
#endif #endif
// Finalize hash and report // Finalize hash and report
void Final(); void Final();
// Report functions: as pre-formatted and raw data // Report functions: as pre-formatted and raw data
#ifdef SHA1_UTILITY_FUNCTIONS #ifdef SHA1_UTILITY_FUNCTIONS
void ReportHash(char *szReport, unsigned char uReportType = REPORT_HEX); void ReportHash(char *szReport, unsigned char uReportType = REPORT_HEX);
#endif #endif
void GetHash(UINT_8 *puDest); void GetHash(UINT_8 *puDest);
private: private:
// Private SHA-1 transformation // Private SHA-1 transformation
void Transform(UINT_32 *state, UINT_8 *buffer); void Transform(UINT_32 *state, UINT_8 *buffer);
// Member variables // Member variables
UINT_8 m_workspace[64]; UINT_8 m_workspace[64];
SHA1_WORKSPACE_BLOCK *m_block; // SHA1 pointer to the byte array above SHA1_WORKSPACE_BLOCK *m_block; // SHA1 pointer to the byte array above
}; };
#endif #endif

View file

@ -1,123 +1,123 @@
/* /*
base64.cpp and base64.h base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages warranty. In no event will the author be held liable for any damages
arising from the use of this software. arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions: freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not 1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be in a product, an acknowledgment in the product documentation would be
appreciated but is not required. appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be 2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code. misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution. 3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/ */
#include "base64.h" #include "base64.h"
#include <iostream> #include <iostream>
static const std::string base64_chars = static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz" "abcdefghijklmnopqrstuvwxyz"
"0123456789+/"; "0123456789+/";
static inline bool is_base64(unsigned char c) { static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/')); return (isalnum(c) || (c == '+') || (c == '/'));
} }
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret; std::string ret;
int i = 0; int i = 0;
int j = 0; int j = 0;
unsigned char char_array_3[3]; unsigned char char_array_3[3];
unsigned char char_array_4[4]; unsigned char char_array_4[4];
while (in_len--) { while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++); char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) { if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f; char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++) for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]]; ret += base64_chars[char_array_4[i]];
i = 0; i = 0;
} }
} }
if (i) if (i)
{ {
for(j = i; j < 3; j++) for(j = i; j < 3; j++)
char_array_3[j] = '\0'; char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f; char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++) for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]]; ret += base64_chars[char_array_4[j]];
while((i++ < 3)) while((i++ < 3))
ret += '='; ret += '=';
} }
return ret; return ret;
} }
std::string base64_decode(std::string const& encoded_string) { std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size(); int in_len = encoded_string.size();
int i = 0; int i = 0;
int j = 0; int j = 0;
int in_ = 0; int in_ = 0;
unsigned char char_array_4[4], char_array_3[3]; unsigned char char_array_4[4], char_array_3[3];
std::string ret; std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++; char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) { if (i ==4) {
for (i = 0; i <4; i++) for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++) for (i = 0; (i < 3); i++)
ret += char_array_3[i]; ret += char_array_3[i];
i = 0; i = 0;
} }
} }
if (i) { if (i) {
for (j = i; j <4; j++) for (j = i; j <4; j++)
char_array_4[j] = 0; char_array_4[j] = 0;
for (j = 0; j <4; j++) for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
} }
return ret; return ret;
} }

View file

@ -1,4 +1,4 @@
#include <string> #include <string>
std::string base64_encode(unsigned char const* , unsigned int len); std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s); std::string base64_decode(std::string const& s);

File diff suppressed because it is too large Load diff

View file

@ -1,93 +1,93 @@
#ifndef __OAUTHLIB_H__ #ifndef __OAUTHLIB_H__
#define __OAUTHLIB_H__ #define __OAUTHLIB_H__
#include "time.h" #include "time.h"
#include <cstdlib> #include <cstdlib>
#include <sstream> #include <sstream>
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
#include <string> #include <string>
#include <list> #include <list>
#include <map> #include <map>
typedef enum _eOAuthHttpRequestType typedef enum _eOAuthHttpRequestType
{ {
eOAuthHttpInvalid = 0, eOAuthHttpInvalid = 0,
eOAuthHttpGet, eOAuthHttpGet,
eOAuthHttpPost, eOAuthHttpPost,
eOAuthHttpDelete eOAuthHttpDelete
} eOAuthHttpRequestType; } eOAuthHttpRequestType;
typedef std::list<std::string> oAuthKeyValueList; typedef std::list<std::string> oAuthKeyValueList;
typedef std::map<std::string, std::string> oAuthKeyValuePairs; typedef std::map<std::string, std::string> oAuthKeyValuePairs;
class oAuth class oAuth
{ {
public: public:
oAuth(); oAuth();
~oAuth(); ~oAuth();
/* OAuth public methods used by twitCurl */ /* OAuth public methods used by twitCurl */
void getConsumerKey( std::string& consumerKey /* out */ ); void getConsumerKey( std::string& consumerKey /* out */ );
void setConsumerKey( const std::string& consumerKey /* in */ ); void setConsumerKey( const std::string& consumerKey /* in */ );
void getConsumerSecret( std::string& consumerSecret /* out */ ); void getConsumerSecret( std::string& consumerSecret /* out */ );
void setConsumerSecret( const std::string& consumerSecret /* in */ ); void setConsumerSecret( const std::string& consumerSecret /* in */ );
void getOAuthTokenKey( std::string& oAuthTokenKey /* out */ ); void getOAuthTokenKey( std::string& oAuthTokenKey /* out */ );
void setOAuthTokenKey( const std::string& oAuthTokenKey /* in */ ); void setOAuthTokenKey( const std::string& oAuthTokenKey /* in */ );
void getOAuthTokenSecret( std::string& oAuthTokenSecret /* out */ ); void getOAuthTokenSecret( std::string& oAuthTokenSecret /* out */ );
void setOAuthTokenSecret( const std::string& oAuthTokenSecret /* in */ ); void setOAuthTokenSecret( const std::string& oAuthTokenSecret /* in */ );
void getOAuthScreenName( std::string& oAuthScreenName /* out */ ); void getOAuthScreenName( std::string& oAuthScreenName /* out */ );
void setOAuthScreenName( const std::string& oAuthScreenName /* in */ ); void setOAuthScreenName( const std::string& oAuthScreenName /* in */ );
void getOAuthPin( std::string& oAuthPin /* out */ ); void getOAuthPin( std::string& oAuthPin /* out */ );
void setOAuthPin( const std::string& oAuthPin /* in */ ); void setOAuthPin( const std::string& oAuthPin /* in */ );
bool getOAuthHeader( const eOAuthHttpRequestType eType, /* in */ bool getOAuthHeader( const eOAuthHttpRequestType eType, /* in */
const std::string& rawUrl, /* in */ const std::string& rawUrl, /* in */
const std::string& rawData, /* in */ const std::string& rawData, /* in */
std::string& oAuthHttpHeader, /* out */ std::string& oAuthHttpHeader, /* out */
const bool includeOAuthVerifierPin = false /* in */ ); const bool includeOAuthVerifierPin = false /* in */ );
bool extractOAuthTokenKeySecret( const std::string& requestTokenResponse /* in */ ); bool extractOAuthTokenKeySecret( const std::string& requestTokenResponse /* in */ );
oAuth clone(); oAuth clone();
private: private:
/* OAuth data */ /* OAuth data */
std::string m_consumerKey; std::string m_consumerKey;
std::string m_consumerSecret; std::string m_consumerSecret;
std::string m_oAuthTokenKey; std::string m_oAuthTokenKey;
std::string m_oAuthTokenSecret; std::string m_oAuthTokenSecret;
std::string m_oAuthPin; std::string m_oAuthPin;
std::string m_nonce; std::string m_nonce;
std::string m_timeStamp; std::string m_timeStamp;
std::string m_oAuthScreenName; std::string m_oAuthScreenName;
/* OAuth twitter related utility methods */ /* OAuth twitter related utility methods */
void buildOAuthRawDataKeyValPairs( const std::string& rawData, /* in */ void buildOAuthRawDataKeyValPairs( const std::string& rawData, /* in */
bool urlencodeData, /* in */ bool urlencodeData, /* in */
oAuthKeyValuePairs& rawDataKeyValuePairs /* out */ ); oAuthKeyValuePairs& rawDataKeyValuePairs /* out */ );
bool buildOAuthTokenKeyValuePairs( const bool includeOAuthVerifierPin, /* in */ bool buildOAuthTokenKeyValuePairs( const bool includeOAuthVerifierPin, /* in */
const std::string& oauthSignature, /* in */ const std::string& oauthSignature, /* in */
oAuthKeyValuePairs& keyValueMap /* out */, oAuthKeyValuePairs& keyValueMap /* out */,
const bool generateTimestamp /* in */ ); const bool generateTimestamp /* in */ );
bool getStringFromOAuthKeyValuePairs( const oAuthKeyValuePairs& rawParamMap, /* in */ bool getStringFromOAuthKeyValuePairs( const oAuthKeyValuePairs& rawParamMap, /* in */
std::string& rawParams, /* out */ std::string& rawParams, /* out */
const std::string& paramsSeperator /* in */ ); const std::string& paramsSeperator /* in */ );
bool getSignature( const eOAuthHttpRequestType eType, /* in */ bool getSignature( const eOAuthHttpRequestType eType, /* in */
const std::string& rawUrl, /* in */ const std::string& rawUrl, /* in */
const oAuthKeyValuePairs& rawKeyValuePairs, /* in */ const oAuthKeyValuePairs& rawKeyValuePairs, /* in */
std::string& oAuthSignature /* out */ ); std::string& oAuthSignature /* out */ );
void generateNonceTimeStamp(); void generateNonceTimeStamp();
}; };
#endif // __OAUTHLIB_H__ #endif // __OAUTHLIB_H__

File diff suppressed because it is too large Load diff

View file

@ -1,140 +1,140 @@
# Microsoft Developer Studio Project File - Name="twitcurl" - Package Owner=<4> # Microsoft Developer Studio Project File - Name="twitcurl" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00 # Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT ** # ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Static Library" 0x0104 # TARGTYPE "Win32 (x86) Static Library" 0x0104
CFG=twitcurl - Win32 Debug CFG=twitcurl - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run !MESSAGE use the Export Makefile command and run
!MESSAGE !MESSAGE
!MESSAGE NMAKE /f "twitcurl.mak". !MESSAGE NMAKE /f "twitcurl.mak".
!MESSAGE !MESSAGE
!MESSAGE You can specify a configuration when running NMAKE !MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE !MESSAGE
!MESSAGE NMAKE /f "twitcurl.mak" CFG="twitcurl - Win32 Debug" !MESSAGE NMAKE /f "twitcurl.mak" CFG="twitcurl - Win32 Debug"
!MESSAGE !MESSAGE
!MESSAGE Possible choices for configuration are: !MESSAGE Possible choices for configuration are:
!MESSAGE !MESSAGE
!MESSAGE "twitcurl - Win32 Release" (based on "Win32 (x86) Static Library") !MESSAGE "twitcurl - Win32 Release" (based on "Win32 (x86) Static Library")
!MESSAGE "twitcurl - Win32 Debug" (based on "Win32 (x86) Static Library") !MESSAGE "twitcurl - Win32 Debug" (based on "Win32 (x86) Static Library")
!MESSAGE !MESSAGE
# Begin Project # Begin Project
# PROP AllowPerConfigDependencies 0 # PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName "" # PROP Scc_ProjName ""
# PROP Scc_LocalPath "" # PROP Scc_LocalPath ""
CPP=cl.exe CPP=cl.exe
RSC=rc.exe RSC=rc.exe
!IF "$(CFG)" == "twitcurl - Win32 Release" !IF "$(CFG)" == "twitcurl - Win32 Release"
# PROP BASE Use_MFC 0 # PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0 # PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release" # PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release" # PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir "" # PROP BASE Target_Dir ""
# PROP Use_MFC 0 # PROP Use_MFC 0
# PROP Use_Debug_Libraries 0 # PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release" # PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release" # PROP Intermediate_Dir "Release"
# PROP Target_Dir "" # PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
# ADD CPP /nologo /W3 /GX /O2 /I "./curl" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c # ADD CPP /nologo /W3 /GX /O2 /I "./curl" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
# ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe BSC32=bscmake.exe
# ADD BASE BSC32 /nologo # ADD BASE BSC32 /nologo
# ADD BSC32 /nologo # ADD BSC32 /nologo
LIB32=link.exe -lib LIB32=link.exe -lib
# ADD BASE LIB32 /nologo # ADD BASE LIB32 /nologo
# ADD LIB32 /nologo # ADD LIB32 /nologo
!ELSEIF "$(CFG)" == "twitcurl - Win32 Debug" !ELSEIF "$(CFG)" == "twitcurl - Win32 Debug"
# PROP BASE Use_MFC 0 # PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1 # PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug" # PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug" # PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir "" # PROP BASE Target_Dir ""
# PROP Use_MFC 0 # PROP Use_MFC 0
# PROP Use_Debug_Libraries 1 # PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug" # PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug" # PROP Intermediate_Dir "Debug"
# PROP Target_Dir "" # PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "./curl" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c # ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "./curl" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
# ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe BSC32=bscmake.exe
# ADD BASE BSC32 /nologo # ADD BASE BSC32 /nologo
# ADD BSC32 /nologo # ADD BSC32 /nologo
LIB32=link.exe -lib LIB32=link.exe -lib
# ADD BASE LIB32 /nologo # ADD BASE LIB32 /nologo
# ADD LIB32 /nologo # ADD LIB32 /nologo
!ENDIF !ENDIF
# Begin Target # Begin Target
# Name "twitcurl - Win32 Release" # Name "twitcurl - Win32 Release"
# Name "twitcurl - Win32 Debug" # Name "twitcurl - Win32 Debug"
# Begin Group "Source Files" # Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File # Begin Source File
SOURCE=.\base64.cpp SOURCE=.\base64.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\HMAC_SHA1.cpp SOURCE=.\HMAC_SHA1.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\oauthlib.cpp SOURCE=.\oauthlib.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\SHA1.cpp SOURCE=.\SHA1.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\twitcurl.cpp SOURCE=.\twitcurl.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\urlencode.cpp SOURCE=.\urlencode.cpp
# End Source File # End Source File
# End Group # End Group
# Begin Group "Header Files" # Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl" # PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File # Begin Source File
SOURCE=.\base64.h SOURCE=.\base64.h
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\HMAC_SHA1.h SOURCE=.\HMAC_SHA1.h
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\oauthlib.h SOURCE=.\oauthlib.h
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\SHA1.h SOURCE=.\SHA1.h
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\twitcurl.h SOURCE=.\twitcurl.h
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\urlencode.h SOURCE=.\urlencode.h
# End Source File # End Source File
# End Group # End Group
# End Target # End Target
# End Project # End Project

View file

@ -1,29 +1,29 @@
Microsoft Developer Studio Workspace File, Format Version 6.00 Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! # WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
############################################################################### ###############################################################################
Project: "twitcurl"=.\twitcurl.dsp - Package Owner=<4> Project: "twitcurl"=.\twitcurl.dsp - Package Owner=<4>
Package=<5> Package=<5>
{{{ {{{
}}} }}}
Package=<4> Package=<4>
{{{ {{{
}}} }}}
############################################################################### ###############################################################################
Global: Global:
Package=<5> Package=<5>
{{{ {{{
}}} }}}
Package=<3> Package=<3>
{{{ {{{
}}} }}}
############################################################################### ###############################################################################

View file

@ -1,190 +1,190 @@
#ifndef _TWITCURL_H_ #ifndef _TWITCURL_H_
#define _TWITCURL_H_ #define _TWITCURL_H_
#include <string> #include <string>
#include <sstream> #include <sstream>
#include <cstring> #include <cstring>
#include <vector> #include <vector>
#include "oauthlib.h" #include "oauthlib.h"
#include "curl/curl.h" #include "curl/curl.h"
/* Few common types used by twitCurl */ /* Few common types used by twitCurl */
namespace twitCurlTypes namespace twitCurlTypes
{ {
typedef enum _eTwitCurlApiFormatType typedef enum _eTwitCurlApiFormatType
{ {
eTwitCurlApiFormatJson = 0, eTwitCurlApiFormatJson = 0,
eTwitCurlApiFormatXml, eTwitCurlApiFormatXml,
eTwitCurlApiFormatMax eTwitCurlApiFormatMax
} eTwitCurlApiFormatType; } eTwitCurlApiFormatType;
typedef enum _eTwitCurlProtocolType typedef enum _eTwitCurlProtocolType
{ {
eTwitCurlProtocolHttps = 0, eTwitCurlProtocolHttps = 0,
eTwitCurlProtocolHttp, eTwitCurlProtocolHttp,
eTwitCurlProtocolMax eTwitCurlProtocolMax
} eTwitCurlProtocolType; } eTwitCurlProtocolType;
}; };
/* twitCurl class */ /* twitCurl class */
class twitCurl class twitCurl
{ {
public: public:
twitCurl(); twitCurl();
~twitCurl(); ~twitCurl();
/* Twitter OAuth authorization methods */ /* Twitter OAuth authorization methods */
oAuth& getOAuth(); oAuth& getOAuth();
bool oAuthRequestToken( std::string& authorizeUrl /* out */ ); bool oAuthRequestToken( std::string& authorizeUrl /* out */ );
bool oAuthAccessToken(); bool oAuthAccessToken();
bool oAuthHandlePIN( const std::string& authorizeUrl /* in */ ); bool oAuthHandlePIN( const std::string& authorizeUrl /* in */ );
/* Twitter login APIs, set once and forget */ /* Twitter login APIs, set once and forget */
std::string& getTwitterUsername(); std::string& getTwitterUsername();
std::string& getTwitterPassword(); std::string& getTwitterPassword();
void setTwitterUsername( std::string& userName /* in */ ); void setTwitterUsername( std::string& userName /* in */ );
void setTwitterPassword( std::string& passWord /* in */ ); void setTwitterPassword( std::string& passWord /* in */ );
/* Twitter search APIs */ /* Twitter search APIs */
bool search( std::string& searchQuery /* in */, std::string resultCount = "" /* in */ ); bool search( std::string& searchQuery /* in */, std::string resultCount = "" /* in */ );
/* Twitter status APIs */ /* Twitter status APIs */
bool statusUpdate( std::string& newStatus /* in */, std::string inReplyToStatusId = "" /* in */ ); bool statusUpdate( std::string& newStatus /* in */, std::string inReplyToStatusId = "" /* in */ );
bool statusShowById( std::string& statusId /* in */ ); bool statusShowById( std::string& statusId /* in */ );
bool statusDestroyById( std::string& statusId /* in */ ); bool statusDestroyById( std::string& statusId /* in */ );
bool retweetById( std::string& statusId /* in */ ); bool retweetById( std::string& statusId /* in */ );
/* Twitter timeline APIs */ /* Twitter timeline APIs */
bool timelineHomeGet( std::string sinceId = "" /* in */ ); bool timelineHomeGet( std::string sinceId = "" /* in */ );
bool timelinePublicGet(); bool timelinePublicGet();
bool timelineFriendsGet(); bool timelineFriendsGet();
bool timelineUserGet( bool trimUser /* in */, bool includeRetweets /* in */, bool timelineUserGet( bool trimUser /* in */, bool includeRetweets /* in */,
unsigned int tweetCount /* in */, unsigned int tweetCount /* in */,
std::string userInfo = "" /* in */, std::string userInfo = "" /* in */,
bool isUserId = false /* in */ ); bool isUserId = false /* in */ );
bool featuredUsersGet(); bool featuredUsersGet();
bool mentionsGet( std::string sinceId = "" /* in */ ); bool mentionsGet( std::string sinceId = "" /* in */ );
/* Twitter user APIs */ /* Twitter user APIs */
bool userLookup( std::vector<std::string> &userInfo /* in */, bool isUserId = false /* in */ ); bool userLookup( std::vector<std::string> &userInfo /* in */, bool isUserId = false /* in */ );
bool userGet( std::string& userInfo /* in */, bool isUserId = false /* in */ ); bool userGet( std::string& userInfo /* in */, bool isUserId = false /* in */ );
bool friendsGet( std::string userInfo = "" /* in */, bool isUserId = false /* in */ ); bool friendsGet( std::string userInfo = "" /* in */, bool isUserId = false /* in */ );
bool followersGet( std::string userInfo = "" /* in */, bool isUserId = false /* in */ ); bool followersGet( std::string userInfo = "" /* in */, bool isUserId = false /* in */ );
/* Twitter direct message APIs */ /* Twitter direct message APIs */
bool directMessageGet( std::string sinceId = "" /* in */ ); bool directMessageGet( std::string sinceId = "" /* in */ );
bool directMessageSend( std::string& userInfo /* in */, std::string& dMsg /* in */, bool isUserId = false /* in */ ); bool directMessageSend( std::string& userInfo /* in */, std::string& dMsg /* in */, bool isUserId = false /* in */ );
bool directMessageGetSent(); bool directMessageGetSent();
bool directMessageDestroyById( std::string& dMsgId /* in */ ); bool directMessageDestroyById( std::string& dMsgId /* in */ );
/* Twitter friendships APIs */ /* Twitter friendships APIs */
bool friendshipCreate( std::string& userInfo /* in */, bool isUserId = false /* in */ ); bool friendshipCreate( std::string& userInfo /* in */, bool isUserId = false /* in */ );
bool friendshipDestroy( std::string& userInfo /* in */, bool isUserId = false /* in */ ); bool friendshipDestroy( std::string& userInfo /* in */, bool isUserId = false /* in */ );
bool friendshipShow( std::string& userInfo /* in */, bool isUserId = false /* in */ ); bool friendshipShow( std::string& userInfo /* in */, bool isUserId = false /* in */ );
/* Twitter social graphs APIs */ /* Twitter social graphs APIs */
bool friendsIdsGet( std::string& nextCursor /* in */, bool friendsIdsGet( std::string& nextCursor /* in */,
std::string& userInfo /* in */, bool isUserId = false /* in */ ); std::string& userInfo /* in */, bool isUserId = false /* in */ );
bool followersIdsGet( std::string& nextCursor /* in */, bool followersIdsGet( std::string& nextCursor /* in */,
std::string& userInfo /* in */, bool isUserId = false /* in */ ); std::string& userInfo /* in */, bool isUserId = false /* in */ );
/* Twitter account APIs */ /* Twitter account APIs */
bool accountRateLimitGet(); bool accountRateLimitGet();
bool accountVerifyCredGet(); bool accountVerifyCredGet();
/* Twitter favorites APIs */ /* Twitter favorites APIs */
bool favoriteGet(); bool favoriteGet();
bool favoriteCreate( std::string& statusId /* in */ ); bool favoriteCreate( std::string& statusId /* in */ );
bool favoriteDestroy( std::string& statusId /* in */ ); bool favoriteDestroy( std::string& statusId /* in */ );
/* Twitter block APIs */ /* Twitter block APIs */
bool blockCreate( std::string& userInfo /* in */ ); bool blockCreate( std::string& userInfo /* in */ );
bool blockDestroy( std::string& userInfo /* in */ ); bool blockDestroy( std::string& userInfo /* in */ );
bool blockListGet( std::string& nextCursor /* in */, bool blockListGet( std::string& nextCursor /* in */,
bool includeEntities /* in */, bool skipStatus /* in */ ); bool includeEntities /* in */, bool skipStatus /* in */ );
bool blockIdsGet( std::string& nextCursor /* in */, bool stringifyIds /* in */ ); bool blockIdsGet( std::string& nextCursor /* in */, bool stringifyIds /* in */ );
/* Twitter search APIs */ /* Twitter search APIs */
bool savedSearchGet(); bool savedSearchGet();
bool savedSearchCreate( std::string& query /* in */ ); bool savedSearchCreate( std::string& query /* in */ );
bool savedSearchShow( std::string& searchId /* in */ ); bool savedSearchShow( std::string& searchId /* in */ );
bool savedSearchDestroy( std::string& searchId /* in */ ); bool savedSearchDestroy( std::string& searchId /* in */ );
/* Twitter trends APIs (JSON) */ /* Twitter trends APIs (JSON) */
bool trendsGet(); bool trendsGet();
bool trendsDailyGet(); bool trendsDailyGet();
bool trendsWeeklyGet(); bool trendsWeeklyGet();
bool trendsCurrentGet(); bool trendsCurrentGet();
bool trendsAvailableGet(); bool trendsAvailableGet();
/* cURL APIs */ /* cURL APIs */
bool isCurlInit(); bool isCurlInit();
void getLastWebResponse( std::string& outWebResp /* out */ ); void getLastWebResponse( std::string& outWebResp /* out */ );
void getLastCurlError( std::string& outErrResp /* out */); void getLastCurlError( std::string& outErrResp /* out */);
/* Internal cURL related methods */ /* Internal cURL related methods */
int saveLastWebResponse( char*& data, size_t size ); int saveLastWebResponse( char*& data, size_t size );
/* cURL proxy APIs */ /* cURL proxy APIs */
std::string& getProxyServerIp(); std::string& getProxyServerIp();
std::string& getProxyServerPort(); std::string& getProxyServerPort();
std::string& getProxyUserName(); std::string& getProxyUserName();
std::string& getProxyPassword(); std::string& getProxyPassword();
void setProxyServerIp( std::string& proxyServerIp /* in */ ); void setProxyServerIp( std::string& proxyServerIp /* in */ );
void setProxyServerPort( std::string& proxyServerPort /* in */ ); void setProxyServerPort( std::string& proxyServerPort /* in */ );
void setProxyUserName( std::string& proxyUserName /* in */ ); void setProxyUserName( std::string& proxyUserName /* in */ );
void setProxyPassword( std::string& proxyPassword /* in */ ); void setProxyPassword( std::string& proxyPassword /* in */ );
/* Clones this object */ /* Clones this object */
twitCurl* clone(); twitCurl* clone();
private: private:
/* cURL data */ /* cURL data */
CURL* m_curlHandle; CURL* m_curlHandle;
char* m_errorBuffer; char* m_errorBuffer;
std::string m_callbackData; std::string m_callbackData;
/* cURL flags */ /* cURL flags */
bool m_curlProxyParamsSet; bool m_curlProxyParamsSet;
bool m_curlLoginParamsSet; bool m_curlLoginParamsSet;
bool m_curlCallbackParamsSet; bool m_curlCallbackParamsSet;
/* cURL proxy data */ /* cURL proxy data */
std::string m_proxyServerIp; std::string m_proxyServerIp;
std::string m_proxyServerPort; std::string m_proxyServerPort;
std::string m_proxyUserName; std::string m_proxyUserName;
std::string m_proxyPassword; std::string m_proxyPassword;
/* Twitter data */ /* Twitter data */
std::string m_twitterUsername; std::string m_twitterUsername;
std::string m_twitterPassword; std::string m_twitterPassword;
/* Twitter API type */ /* Twitter API type */
twitCurlTypes::eTwitCurlApiFormatType m_eApiFormatType; twitCurlTypes::eTwitCurlApiFormatType m_eApiFormatType;
twitCurlTypes::eTwitCurlProtocolType m_eProtocolType; twitCurlTypes::eTwitCurlProtocolType m_eProtocolType;
/* OAuth data */ /* OAuth data */
oAuth m_oAuth; oAuth m_oAuth;
/* Private methods */ /* Private methods */
void clearCurlCallbackBuffers(); void clearCurlCallbackBuffers();
void prepareCurlProxy(); void prepareCurlProxy();
void prepareCurlCallback(); void prepareCurlCallback();
void prepareCurlUserPass(); void prepareCurlUserPass();
void prepareStandardParams(); void prepareStandardParams();
bool performGet( const std::string& getUrl ); bool performGet( const std::string& getUrl );
bool performGetInternal( const std::string& getUrl, bool performGetInternal( const std::string& getUrl,
const std::string& oAuthHttpHeader ); const std::string& oAuthHttpHeader );
bool performDelete( const std::string& deleteUrl ); bool performDelete( const std::string& deleteUrl );
bool performPost( const std::string& postUrl, std::string dataStr = "" ); bool performPost( const std::string& postUrl, std::string dataStr = "" );
/* Internal cURL related methods */ /* Internal cURL related methods */
static int curlCallback( char* data, size_t size, size_t nmemb, twitCurl* pTwitCurlObj ); static int curlCallback( char* data, size_t size, size_t nmemb, twitCurl* pTwitCurlObj );
}; };
/* Private functions */ /* Private functions */
void utilMakeCurlParams( std::string& outStr, std::string& inParam1, std::string& inParam2 ); void utilMakeCurlParams( std::string& outStr, std::string& inParam1, std::string& inParam2 );
void utilMakeUrlForUser( std::string& outUrl, const std::string& baseUrl, std::string& userInfo, bool isUserId ); void utilMakeUrlForUser( std::string& outUrl, const std::string& baseUrl, std::string& userInfo, bool isUserId );
#endif // _TWITCURL_H_ #endif // _TWITCURL_H_

View file

@ -1,37 +1,37 @@
<html> <html>
<body> <body>
<pre> <pre>
<h1>Build Log</h1> <h1>Build Log</h1>
<h3> <h3>
--------------------Configuration: twitcurl - Win32 Release-------------------- --------------------Configuration: twitcurl - Win32 Release--------------------
</h3> </h3>
<h3>Command Lines</h3> <h3>Command Lines</h3>
Creating temporary file "C:\DOCUME~1\Mahesh\LOCALS~1\Temp\RSP239.tmp" with contents Creating temporary file "C:\DOCUME~1\Mahesh\LOCALS~1\Temp\RSP239.tmp" with contents
[ [
/nologo /ML /W3 /GX /O2 /I "./curl" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /Fp"Release/twitcurl.pch" /YX /Fo"Release/" /Fd"Release/" /FD /c /nologo /ML /W3 /GX /O2 /I "./curl" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /Fp"Release/twitcurl.pch" /YX /Fo"Release/" /Fd"Release/" /FD /c
"C:\Projects\twitcurl\base64.cpp" "C:\Projects\twitcurl\base64.cpp"
"C:\Projects\twitcurl\HMAC_SHA1.cpp" "C:\Projects\twitcurl\HMAC_SHA1.cpp"
"C:\Projects\twitcurl\oauthlib.cpp" "C:\Projects\twitcurl\oauthlib.cpp"
"C:\Projects\twitcurl\SHA1.cpp" "C:\Projects\twitcurl\SHA1.cpp"
"C:\Projects\twitcurl\twitcurl.cpp" "C:\Projects\twitcurl\twitcurl.cpp"
"C:\Projects\twitcurl\urlencode.cpp" "C:\Projects\twitcurl\urlencode.cpp"
] ]
Creating command line "cl.exe @C:\DOCUME~1\Mahesh\LOCALS~1\Temp\RSP239.tmp" Creating command line "cl.exe @C:\DOCUME~1\Mahesh\LOCALS~1\Temp\RSP239.tmp"
Creating command line "link.exe -lib /nologo /out:"Release\twitcurl.lib" .\Release\base64.obj .\Release\HMAC_SHA1.obj .\Release\oauthlib.obj .\Release\SHA1.obj .\Release\twitcurl.obj .\Release\urlencode.obj " Creating command line "link.exe -lib /nologo /out:"Release\twitcurl.lib" .\Release\base64.obj .\Release\HMAC_SHA1.obj .\Release\oauthlib.obj .\Release\SHA1.obj .\Release\twitcurl.obj .\Release\urlencode.obj "
<h3>Output Window</h3> <h3>Output Window</h3>
Compiling... Compiling...
base64.cpp base64.cpp
HMAC_SHA1.cpp HMAC_SHA1.cpp
oauthlib.cpp oauthlib.cpp
SHA1.cpp SHA1.cpp
twitcurl.cpp twitcurl.cpp
urlencode.cpp urlencode.cpp
Creating library... Creating library...
<h3>Results</h3> <h3>Results</h3>
twitcurl.lib - 0 error(s), 0 warning(s) twitcurl.lib - 0 error(s), 0 warning(s)
</pre> </pre>
</body> </body>
</html> </html>

View file

@ -1,20 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 10.00 Microsoft Visual Studio Solution File, Format Version 10.00
# Visual C++ Express 2008 # Visual C++ Express 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "twitcurl", "twitcurl.vcproj", "{00175D8C-EA44-48AE-AC59-B3B7BE04E65C}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "twitcurl", "twitcurl.vcproj", "{00175D8C-EA44-48AE-AC59-B3B7BE04E65C}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32 Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32 Release|Win32 = Release|Win32
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{00175D8C-EA44-48AE-AC59-B3B7BE04E65C}.Debug|Win32.ActiveCfg = Release|Win32 {00175D8C-EA44-48AE-AC59-B3B7BE04E65C}.Debug|Win32.ActiveCfg = Release|Win32
{00175D8C-EA44-48AE-AC59-B3B7BE04E65C}.Debug|Win32.Build.0 = Release|Win32 {00175D8C-EA44-48AE-AC59-B3B7BE04E65C}.Debug|Win32.Build.0 = Release|Win32
{00175D8C-EA44-48AE-AC59-B3B7BE04E65C}.Release|Win32.ActiveCfg = Release|Win32 {00175D8C-EA44-48AE-AC59-B3B7BE04E65C}.Release|Win32.ActiveCfg = Release|Win32
{00175D8C-EA44-48AE-AC59-B3B7BE04E65C}.Release|Win32.Build.0 = Release|Win32 {00175D8C-EA44-48AE-AC59-B3B7BE04E65C}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View file

@ -1,347 +1,347 @@
<?xml version="1.0" encoding="Windows-1252"?> <?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject <VisualStudioProject
ProjectType="Visual C++" ProjectType="Visual C++"
Version="9.00" Version="9.00"
Name="twitcurl" Name="twitcurl"
ProjectGUID="{00175D8C-EA44-48AE-AC59-B3B7BE04E65C}" ProjectGUID="{00175D8C-EA44-48AE-AC59-B3B7BE04E65C}"
TargetFrameworkVersion="0" TargetFrameworkVersion="0"
> >
<Platforms> <Platforms>
<Platform <Platform
Name="Win32" Name="Win32"
/> />
</Platforms> </Platforms>
<ToolFiles> <ToolFiles>
</ToolFiles> </ToolFiles>
<Configurations> <Configurations>
<Configuration <Configuration
Name="Debug|Win32" Name="Debug|Win32"
OutputDirectory=".\Debug" OutputDirectory=".\Debug"
IntermediateDirectory=".\Debug" IntermediateDirectory=".\Debug"
ConfigurationType="4" ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
UseOfMFC="0" UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false" ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2" CharacterSet="2"
> >
<Tool <Tool
Name="VCPreBuildEventTool" Name="VCPreBuildEventTool"
/> />
<Tool <Tool
Name="VCCustomBuildTool" Name="VCCustomBuildTool"
/> />
<Tool <Tool
Name="VCXMLDataGeneratorTool" Name="VCXMLDataGeneratorTool"
/> />
<Tool <Tool
Name="VCWebServiceProxyGeneratorTool" Name="VCWebServiceProxyGeneratorTool"
/> />
<Tool <Tool
Name="VCMIDLTool" Name="VCMIDLTool"
/> />
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
Optimization="0" Optimization="0"
AdditionalIncludeDirectories="./curl" AdditionalIncludeDirectories="./curl"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB" PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
MinimalRebuild="true" MinimalRebuild="true"
BasicRuntimeChecks="3" BasicRuntimeChecks="3"
RuntimeLibrary="1" RuntimeLibrary="1"
PrecompiledHeaderFile=".\Debug/twitcurl.pch" PrecompiledHeaderFile=".\Debug/twitcurl.pch"
AssemblerListingLocation=".\Debug/" AssemblerListingLocation=".\Debug/"
ObjectFile=".\Debug/" ObjectFile=".\Debug/"
ProgramDataBaseFileName=".\Debug/" ProgramDataBaseFileName=".\Debug/"
WarningLevel="3" WarningLevel="3"
SuppressStartupBanner="true" SuppressStartupBanner="true"
DebugInformationFormat="4" DebugInformationFormat="4"
/> />
<Tool <Tool
Name="VCManagedResourceCompilerTool" Name="VCManagedResourceCompilerTool"
/> />
<Tool <Tool
Name="VCResourceCompilerTool" Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG" PreprocessorDefinitions="_DEBUG"
Culture="1033" Culture="1033"
/> />
<Tool <Tool
Name="VCPreLinkEventTool" Name="VCPreLinkEventTool"
/> />
<Tool <Tool
Name="VCLibrarianTool" Name="VCLibrarianTool"
OutputFile=".\Debug\twitcurl.lib" OutputFile=".\Debug\twitcurl.lib"
SuppressStartupBanner="true" SuppressStartupBanner="true"
/> />
<Tool <Tool
Name="VCALinkTool" Name="VCALinkTool"
/> />
<Tool <Tool
Name="VCXDCMakeTool" Name="VCXDCMakeTool"
/> />
<Tool <Tool
Name="VCBscMakeTool" Name="VCBscMakeTool"
SuppressStartupBanner="true" SuppressStartupBanner="true"
OutputFile=".\Debug/twitcurl.bsc" OutputFile=".\Debug/twitcurl.bsc"
/> />
<Tool <Tool
Name="VCFxCopTool" Name="VCFxCopTool"
/> />
<Tool <Tool
Name="VCPostBuildEventTool" Name="VCPostBuildEventTool"
/> />
</Configuration> </Configuration>
<Configuration <Configuration
Name="Release|Win32" Name="Release|Win32"
OutputDirectory=".\Release" OutputDirectory=".\Release"
IntermediateDirectory=".\Release" IntermediateDirectory=".\Release"
ConfigurationType="4" ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
UseOfMFC="0" UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false" ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2" CharacterSet="2"
> >
<Tool <Tool
Name="VCPreBuildEventTool" Name="VCPreBuildEventTool"
/> />
<Tool <Tool
Name="VCCustomBuildTool" Name="VCCustomBuildTool"
/> />
<Tool <Tool
Name="VCXMLDataGeneratorTool" Name="VCXMLDataGeneratorTool"
/> />
<Tool <Tool
Name="VCWebServiceProxyGeneratorTool" Name="VCWebServiceProxyGeneratorTool"
/> />
<Tool <Tool
Name="VCMIDLTool" Name="VCMIDLTool"
/> />
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
Optimization="2" Optimization="2"
InlineFunctionExpansion="1" InlineFunctionExpansion="1"
AdditionalIncludeDirectories="./include" AdditionalIncludeDirectories="./include"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB;CURL_STATICLIB" PreprocessorDefinitions="WIN32;NDEBUG;_LIB;CURL_STATICLIB"
StringPooling="true" StringPooling="true"
RuntimeLibrary="2" RuntimeLibrary="2"
EnableFunctionLevelLinking="true" EnableFunctionLevelLinking="true"
PrecompiledHeaderFile=".\Release/twitcurl.pch" PrecompiledHeaderFile=".\Release/twitcurl.pch"
AssemblerListingLocation=".\Release/" AssemblerListingLocation=".\Release/"
ObjectFile=".\Release/" ObjectFile=".\Release/"
ProgramDataBaseFileName=".\Release/" ProgramDataBaseFileName=".\Release/"
WarningLevel="3" WarningLevel="3"
SuppressStartupBanner="true" SuppressStartupBanner="true"
/> />
<Tool <Tool
Name="VCManagedResourceCompilerTool" Name="VCManagedResourceCompilerTool"
/> />
<Tool <Tool
Name="VCResourceCompilerTool" Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG" PreprocessorDefinitions="NDEBUG"
Culture="1033" Culture="1033"
/> />
<Tool <Tool
Name="VCPreLinkEventTool" Name="VCPreLinkEventTool"
/> />
<Tool <Tool
Name="VCLibrarianTool" Name="VCLibrarianTool"
LinkLibraryDependencies="true" LinkLibraryDependencies="true"
AdditionalDependencies="libcurl.lib" AdditionalDependencies="libcurl.lib"
OutputFile=".\Release\twitcurl.lib" OutputFile=".\Release\twitcurl.lib"
AdditionalLibraryDirectories="./lib" AdditionalLibraryDirectories="./lib"
SuppressStartupBanner="true" SuppressStartupBanner="true"
/> />
<Tool <Tool
Name="VCALinkTool" Name="VCALinkTool"
/> />
<Tool <Tool
Name="VCXDCMakeTool" Name="VCXDCMakeTool"
/> />
<Tool <Tool
Name="VCBscMakeTool" Name="VCBscMakeTool"
SuppressStartupBanner="true" SuppressStartupBanner="true"
OutputFile=".\Release/twitcurl.bsc" OutputFile=".\Release/twitcurl.bsc"
/> />
<Tool <Tool
Name="VCFxCopTool" Name="VCFxCopTool"
/> />
<Tool <Tool
Name="VCPostBuildEventTool" Name="VCPostBuildEventTool"
/> />
</Configuration> </Configuration>
</Configurations> </Configurations>
<References> <References>
</References> </References>
<Files> <Files>
<Filter <Filter
Name="Source Files" Name="Source Files"
Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
> >
<File <File
RelativePath="base64.cpp" RelativePath="base64.cpp"
> >
<FileConfiguration <FileConfiguration
Name="Debug|Win32" Name="Debug|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
<FileConfiguration <FileConfiguration
Name="Release|Win32" Name="Release|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
</File> </File>
<File <File
RelativePath="HMAC_SHA1.cpp" RelativePath="HMAC_SHA1.cpp"
> >
<FileConfiguration <FileConfiguration
Name="Debug|Win32" Name="Debug|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
<FileConfiguration <FileConfiguration
Name="Release|Win32" Name="Release|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
</File> </File>
<File <File
RelativePath="oauthlib.cpp" RelativePath="oauthlib.cpp"
> >
<FileConfiguration <FileConfiguration
Name="Debug|Win32" Name="Debug|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
<FileConfiguration <FileConfiguration
Name="Release|Win32" Name="Release|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
</File> </File>
<File <File
RelativePath="SHA1.cpp" RelativePath="SHA1.cpp"
> >
<FileConfiguration <FileConfiguration
Name="Debug|Win32" Name="Debug|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
<FileConfiguration <FileConfiguration
Name="Release|Win32" Name="Release|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
</File> </File>
<File <File
RelativePath="twitcurl.cpp" RelativePath="twitcurl.cpp"
> >
<FileConfiguration <FileConfiguration
Name="Debug|Win32" Name="Debug|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
<FileConfiguration <FileConfiguration
Name="Release|Win32" Name="Release|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
</File> </File>
<File <File
RelativePath="urlencode.cpp" RelativePath="urlencode.cpp"
> >
<FileConfiguration <FileConfiguration
Name="Debug|Win32" Name="Debug|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
<FileConfiguration <FileConfiguration
Name="Release|Win32" Name="Release|Win32"
> >
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="" AdditionalIncludeDirectories=""
PreprocessorDefinitions="" PreprocessorDefinitions=""
/> />
</FileConfiguration> </FileConfiguration>
</File> </File>
</Filter> </Filter>
<Filter <Filter
Name="Header Files" Name="Header Files"
Filter="h;hpp;hxx;hm;inl" Filter="h;hpp;hxx;hm;inl"
> >
<File <File
RelativePath="base64.h" RelativePath="base64.h"
> >
</File> </File>
<File <File
RelativePath="HMAC_SHA1.h" RelativePath="HMAC_SHA1.h"
> >
</File> </File>
<File <File
RelativePath="oauthlib.h" RelativePath="oauthlib.h"
> >
</File> </File>
<File <File
RelativePath="SHA1.h" RelativePath="SHA1.h"
> >
</File> </File>
<File <File
RelativePath="twitcurl.h" RelativePath="twitcurl.h"
> >
</File> </File>
<File <File
RelativePath=".\twitcurlurls.h" RelativePath=".\twitcurlurls.h"
> >
</File> </File>
<File <File
RelativePath="urlencode.h" RelativePath="urlencode.h"
> >
</File> </File>
</Filter> </Filter>
</Files> </Files>
<Globals> <Globals>
</Globals> </Globals>
</VisualStudioProject> </VisualStudioProject>

View file

@ -1,156 +1,156 @@
#ifndef _TWITCURLURLS_H_ #ifndef _TWITCURLURLS_H_
#define _TWITCURLURLS_H_ #define _TWITCURLURLS_H_
#include <string> #include <string>
#include <cstring> #include <cstring>
/* Default values used in twitcurl */ /* Default values used in twitcurl */
namespace twitCurlDefaults namespace twitCurlDefaults
{ {
/* Constants */ /* Constants */
const int TWITCURL_DEFAULT_BUFFSIZE = 1024; const int TWITCURL_DEFAULT_BUFFSIZE = 1024;
const std::string TWITCURL_COLON = ":"; const std::string TWITCURL_COLON = ":";
const char TWITCURL_EOS = '\0'; const char TWITCURL_EOS = '\0';
const unsigned int MAX_TIMELINE_TWEET_COUNT = 200; const unsigned int MAX_TIMELINE_TWEET_COUNT = 200;
/* Miscellaneous data used to build twitter URLs*/ /* Miscellaneous data used to build twitter URLs*/
const std::string TWITCURL_STATUSSTRING = "status="; const std::string TWITCURL_STATUSSTRING = "status=";
const std::string TWITCURL_TEXTSTRING = "text="; const std::string TWITCURL_TEXTSTRING = "text=";
const std::string TWITCURL_QUERYSTRING = "query="; const std::string TWITCURL_QUERYSTRING = "query=";
const std::string TWITCURL_SEARCHQUERYSTRING = "q="; const std::string TWITCURL_SEARCHQUERYSTRING = "q=";
const std::string TWITCURL_SCREENNAME = "screen_name="; const std::string TWITCURL_SCREENNAME = "screen_name=";
const std::string TWITCURL_USERID = "user_id="; const std::string TWITCURL_USERID = "user_id=";
const std::string TWITCURL_EXTENSIONFORMATS[2] = { ".json", const std::string TWITCURL_EXTENSIONFORMATS[2] = { ".json",
".xml" ".xml"
}; };
const std::string TWITCURL_PROTOCOLS[2] = { "https://", const std::string TWITCURL_PROTOCOLS[2] = { "https://",
"http://" "http://"
}; };
const std::string TWITCURL_TARGETSCREENNAME = "target_screen_name="; const std::string TWITCURL_TARGETSCREENNAME = "target_screen_name=";
const std::string TWITCURL_TARGETUSERID = "target_id="; const std::string TWITCURL_TARGETUSERID = "target_id=";
const std::string TWITCURL_SINCEID = "since_id="; const std::string TWITCURL_SINCEID = "since_id=";
const std::string TWITCURL_TRIMUSER = "trim_user=true"; const std::string TWITCURL_TRIMUSER = "trim_user=true";
const std::string TWITCURL_INCRETWEETS = "include_rts=true"; const std::string TWITCURL_INCRETWEETS = "include_rts=true";
const std::string TWITCURL_COUNT = "count="; const std::string TWITCURL_COUNT = "count=";
const std::string TWITCURL_NEXT_CURSOR = "cursor="; const std::string TWITCURL_NEXT_CURSOR = "cursor=";
const std::string TWITCURL_SKIP_STATUS = "skip_status="; const std::string TWITCURL_SKIP_STATUS = "skip_status=";
const std::string TWITCURL_INCLUDE_ENTITIES = "include_entities="; const std::string TWITCURL_INCLUDE_ENTITIES = "include_entities=";
const std::string TWITCURL_STRINGIFY_IDS = "stringify_ids="; const std::string TWITCURL_STRINGIFY_IDS = "stringify_ids=";
const std::string TWITCURL_INREPLYTOSTATUSID = "in_reply_to_status_id="; const std::string TWITCURL_INREPLYTOSTATUSID = "in_reply_to_status_id=";
/* URL separators */ /* URL separators */
const std::string TWITCURL_URL_SEP_AMP = "&"; const std::string TWITCURL_URL_SEP_AMP = "&";
const std::string TWITCURL_URL_SEP_QUES = "?"; const std::string TWITCURL_URL_SEP_QUES = "?";
}; };
/* Default twitter URLs */ /* Default twitter URLs */
namespace twitterDefaults namespace twitterDefaults
{ {
/* Base URL */ /* Base URL */
const std::string TWITCURL_BASE_URL = "api.twitter.com/1.1/"; const std::string TWITCURL_BASE_URL = "api.twitter.com/1.1/";
/* Search URLs */ /* Search URLs */
const std::string TWITCURL_SEARCH_URL = TWITCURL_BASE_URL + "search/tweets"; const std::string TWITCURL_SEARCH_URL = TWITCURL_BASE_URL + "search/tweets";
/* Status URLs */ /* Status URLs */
const std::string TWITCURL_STATUSUPDATE_URL = TWITCURL_BASE_URL + "statuses/update"; const std::string TWITCURL_STATUSUPDATE_URL = TWITCURL_BASE_URL + "statuses/update";
const std::string TWITCURL_STATUSSHOW_URL = TWITCURL_BASE_URL + "statuses/show/"; const std::string TWITCURL_STATUSSHOW_URL = TWITCURL_BASE_URL + "statuses/show/";
const std::string TWITCURL_STATUDESTROY_URL = TWITCURL_BASE_URL + "statuses/destroy/"; const std::string TWITCURL_STATUDESTROY_URL = TWITCURL_BASE_URL + "statuses/destroy/";
const std::string TWITCURL_RETWEET_URL = TWITCURL_BASE_URL + "statuses/retweet/"; const std::string TWITCURL_RETWEET_URL = TWITCURL_BASE_URL + "statuses/retweet/";
/* Timeline URLs */ /* Timeline URLs */
const std::string TWITCURL_HOME_TIMELINE_URL = TWITCURL_BASE_URL + "statuses/home_timeline"; const std::string TWITCURL_HOME_TIMELINE_URL = TWITCURL_BASE_URL + "statuses/home_timeline";
const std::string TWITCURL_PUBLIC_TIMELINE_URL = TWITCURL_BASE_URL + "statuses/public_timeline"; const std::string TWITCURL_PUBLIC_TIMELINE_URL = TWITCURL_BASE_URL + "statuses/public_timeline";
const std::string TWITCURL_FEATURED_USERS_URL = TWITCURL_BASE_URL + "statuses/featured"; const std::string TWITCURL_FEATURED_USERS_URL = TWITCURL_BASE_URL + "statuses/featured";
const std::string TWITCURL_FRIENDS_TIMELINE_URL = TWITCURL_BASE_URL + "statuses/friends_timeline"; const std::string TWITCURL_FRIENDS_TIMELINE_URL = TWITCURL_BASE_URL + "statuses/friends_timeline";
const std::string TWITCURL_MENTIONS_URL = TWITCURL_BASE_URL + "statuses/mentions"; const std::string TWITCURL_MENTIONS_URL = TWITCURL_BASE_URL + "statuses/mentions";
const std::string TWITCURL_USERTIMELINE_URL = TWITCURL_BASE_URL + "statuses/user_timeline"; const std::string TWITCURL_USERTIMELINE_URL = TWITCURL_BASE_URL + "statuses/user_timeline";
/* Users URLs */ /* Users URLs */
const std::string TWITCURL_LOOKUPUSERS_URL = TWITCURL_BASE_URL + "users/lookup"; const std::string TWITCURL_LOOKUPUSERS_URL = TWITCURL_BASE_URL + "users/lookup";
const std::string TWITCURL_SHOWUSERS_URL = TWITCURL_BASE_URL + "users/show"; const std::string TWITCURL_SHOWUSERS_URL = TWITCURL_BASE_URL + "users/show";
const std::string TWITCURL_SHOWFRIENDS_URL = TWITCURL_BASE_URL + "statuses/friends"; const std::string TWITCURL_SHOWFRIENDS_URL = TWITCURL_BASE_URL + "statuses/friends";
const std::string TWITCURL_SHOWFOLLOWERS_URL = TWITCURL_BASE_URL + "statuses/followers"; const std::string TWITCURL_SHOWFOLLOWERS_URL = TWITCURL_BASE_URL + "statuses/followers";
/* Direct messages URLs */ /* Direct messages URLs */
const std::string TWITCURL_DIRECTMESSAGES_URL = TWITCURL_BASE_URL + "direct_messages"; const std::string TWITCURL_DIRECTMESSAGES_URL = TWITCURL_BASE_URL + "direct_messages";
const std::string TWITCURL_DIRECTMESSAGENEW_URL = TWITCURL_BASE_URL + "direct_messages/new"; const std::string TWITCURL_DIRECTMESSAGENEW_URL = TWITCURL_BASE_URL + "direct_messages/new";
const std::string TWITCURL_DIRECTMESSAGESSENT_URL = TWITCURL_BASE_URL + "direct_messages/sent"; const std::string TWITCURL_DIRECTMESSAGESSENT_URL = TWITCURL_BASE_URL + "direct_messages/sent";
const std::string TWITCURL_DIRECTMESSAGEDESTROY_URL = TWITCURL_BASE_URL + "direct_messages/destroy/"; const std::string TWITCURL_DIRECTMESSAGEDESTROY_URL = TWITCURL_BASE_URL + "direct_messages/destroy/";
/* Friendships URLs */ /* Friendships URLs */
const std::string TWITCURL_FRIENDSHIPSCREATE_URL = TWITCURL_BASE_URL + "friendships/create"; const std::string TWITCURL_FRIENDSHIPSCREATE_URL = TWITCURL_BASE_URL + "friendships/create";
const std::string TWITCURL_FRIENDSHIPSDESTROY_URL = TWITCURL_BASE_URL + "friendships/destroy"; const std::string TWITCURL_FRIENDSHIPSDESTROY_URL = TWITCURL_BASE_URL + "friendships/destroy";
const std::string TWITCURL_FRIENDSHIPSSHOW_URL = TWITCURL_BASE_URL + "friendships/show"; const std::string TWITCURL_FRIENDSHIPSSHOW_URL = TWITCURL_BASE_URL + "friendships/show";
/* Social graphs URLs */ /* Social graphs URLs */
const std::string TWITCURL_FRIENDSIDS_URL = TWITCURL_BASE_URL + "friends/ids"; const std::string TWITCURL_FRIENDSIDS_URL = TWITCURL_BASE_URL + "friends/ids";
const std::string TWITCURL_FOLLOWERSIDS_URL = TWITCURL_BASE_URL + "followers/ids"; const std::string TWITCURL_FOLLOWERSIDS_URL = TWITCURL_BASE_URL + "followers/ids";
/* Account URLs */ /* Account URLs */
const std::string TWITCURL_ACCOUNTRATELIMIT_URL = TWITCURL_BASE_URL + "account/rate_limit_status"; const std::string TWITCURL_ACCOUNTRATELIMIT_URL = TWITCURL_BASE_URL + "account/rate_limit_status";
const std::string TWITCURL_ACCOUNTVERIFYCRED_URL = TWITCURL_BASE_URL + "account/verify_credentials"; const std::string TWITCURL_ACCOUNTVERIFYCRED_URL = TWITCURL_BASE_URL + "account/verify_credentials";
/* Favorites URLs */ /* Favorites URLs */
const std::string TWITCURL_FAVORITESGET_URL = TWITCURL_BASE_URL + "favorites"; const std::string TWITCURL_FAVORITESGET_URL = TWITCURL_BASE_URL + "favorites";
const std::string TWITCURL_FAVORITECREATE_URL = TWITCURL_BASE_URL + "favorites/create/"; const std::string TWITCURL_FAVORITECREATE_URL = TWITCURL_BASE_URL + "favorites/create/";
const std::string TWITCURL_FAVORITEDESTROY_URL = TWITCURL_BASE_URL + "favorites/destroy/"; const std::string TWITCURL_FAVORITEDESTROY_URL = TWITCURL_BASE_URL + "favorites/destroy/";
/* Block URLs */ /* Block URLs */
const std::string TWITCURL_BLOCKSCREATE_URL = TWITCURL_BASE_URL + "blocks/create/"; const std::string TWITCURL_BLOCKSCREATE_URL = TWITCURL_BASE_URL + "blocks/create/";
const std::string TWITCURL_BLOCKSDESTROY_URL = TWITCURL_BASE_URL + "blocks/destroy/"; const std::string TWITCURL_BLOCKSDESTROY_URL = TWITCURL_BASE_URL + "blocks/destroy/";
const std::string TWITCURL_BLOCKSLIST_URL = TWITCURL_BASE_URL + "blocks/list"; const std::string TWITCURL_BLOCKSLIST_URL = TWITCURL_BASE_URL + "blocks/list";
const std::string TWITCURL_BLOCKSIDS_URL = TWITCURL_BASE_URL + "blocks/ids"; const std::string TWITCURL_BLOCKSIDS_URL = TWITCURL_BASE_URL + "blocks/ids";
/* Saved Search URLs */ /* Saved Search URLs */
const std::string TWITCURL_SAVEDSEARCHGET_URL = TWITCURL_BASE_URL + "saved_searches"; const std::string TWITCURL_SAVEDSEARCHGET_URL = TWITCURL_BASE_URL + "saved_searches";
const std::string TWITCURL_SAVEDSEARCHSHOW_URL = TWITCURL_BASE_URL + "saved_searches/show/"; const std::string TWITCURL_SAVEDSEARCHSHOW_URL = TWITCURL_BASE_URL + "saved_searches/show/";
const std::string TWITCURL_SAVEDSEARCHCREATE_URL = TWITCURL_BASE_URL + "saved_searches/create"; const std::string TWITCURL_SAVEDSEARCHCREATE_URL = TWITCURL_BASE_URL + "saved_searches/create";
const std::string TWITCURL_SAVEDSEARCHDESTROY_URL = TWITCURL_BASE_URL + "saved_searches/destroy/"; const std::string TWITCURL_SAVEDSEARCHDESTROY_URL = TWITCURL_BASE_URL + "saved_searches/destroy/";
/* Trends URLs */ /* Trends URLs */
const std::string TWITCURL_TRENDS_URL = TWITCURL_BASE_URL + "trends"; const std::string TWITCURL_TRENDS_URL = TWITCURL_BASE_URL + "trends";
const std::string TWITCURL_TRENDSDAILY_URL = TWITCURL_BASE_URL + "trends/daily"; const std::string TWITCURL_TRENDSDAILY_URL = TWITCURL_BASE_URL + "trends/daily";
const std::string TWITCURL_TRENDSCURRENT_URL = TWITCURL_BASE_URL + "trends/current"; const std::string TWITCURL_TRENDSCURRENT_URL = TWITCURL_BASE_URL + "trends/current";
const std::string TWITCURL_TRENDSWEEKLY_URL = TWITCURL_BASE_URL + "trends/weekly"; const std::string TWITCURL_TRENDSWEEKLY_URL = TWITCURL_BASE_URL + "trends/weekly";
const std::string TWITCURL_TRENDSAVAILABLE_URL = TWITCURL_BASE_URL + "trends/available"; const std::string TWITCURL_TRENDSAVAILABLE_URL = TWITCURL_BASE_URL + "trends/available";
}; };
namespace oAuthLibDefaults namespace oAuthLibDefaults
{ {
/* Constants */ /* Constants */
const int OAUTHLIB_BUFFSIZE = 1024; const int OAUTHLIB_BUFFSIZE = 1024;
const int OAUTHLIB_BUFFSIZE_LARGE = 1024; const int OAUTHLIB_BUFFSIZE_LARGE = 1024;
const std::string OAUTHLIB_CONSUMERKEY_KEY = "oauth_consumer_key"; const std::string OAUTHLIB_CONSUMERKEY_KEY = "oauth_consumer_key";
const std::string OAUTHLIB_CALLBACK_KEY = "oauth_callback"; const std::string OAUTHLIB_CALLBACK_KEY = "oauth_callback";
const std::string OAUTHLIB_VERSION_KEY = "oauth_version"; const std::string OAUTHLIB_VERSION_KEY = "oauth_version";
const std::string OAUTHLIB_SIGNATUREMETHOD_KEY = "oauth_signature_method"; const std::string OAUTHLIB_SIGNATUREMETHOD_KEY = "oauth_signature_method";
const std::string OAUTHLIB_SIGNATURE_KEY = "oauth_signature"; const std::string OAUTHLIB_SIGNATURE_KEY = "oauth_signature";
const std::string OAUTHLIB_TIMESTAMP_KEY = "oauth_timestamp"; const std::string OAUTHLIB_TIMESTAMP_KEY = "oauth_timestamp";
const std::string OAUTHLIB_NONCE_KEY = "oauth_nonce"; const std::string OAUTHLIB_NONCE_KEY = "oauth_nonce";
const std::string OAUTHLIB_TOKEN_KEY = "oauth_token"; const std::string OAUTHLIB_TOKEN_KEY = "oauth_token";
const std::string OAUTHLIB_TOKENSECRET_KEY = "oauth_token_secret"; const std::string OAUTHLIB_TOKENSECRET_KEY = "oauth_token_secret";
const std::string OAUTHLIB_VERIFIER_KEY = "oauth_verifier"; const std::string OAUTHLIB_VERIFIER_KEY = "oauth_verifier";
const std::string OAUTHLIB_SCREENNAME_KEY = "screen_name"; const std::string OAUTHLIB_SCREENNAME_KEY = "screen_name";
const std::string OAUTHLIB_AUTHENTICITY_TOKEN_KEY = "authenticity_token"; const std::string OAUTHLIB_AUTHENTICITY_TOKEN_KEY = "authenticity_token";
const std::string OAUTHLIB_SESSIONUSERNAME_KEY = "session[username_or_email]"; const std::string OAUTHLIB_SESSIONUSERNAME_KEY = "session[username_or_email]";
const std::string OAUTHLIB_SESSIONPASSWORD_KEY = "session[password]"; const std::string OAUTHLIB_SESSIONPASSWORD_KEY = "session[password]";
const std::string OAUTHLIB_AUTHENTICITY_TOKEN_TWITTER_RESP_KEY = "authenticity_token\" type=\"hidden\" value=\""; const std::string OAUTHLIB_AUTHENTICITY_TOKEN_TWITTER_RESP_KEY = "authenticity_token\" type=\"hidden\" value=\"";
const std::string OAUTHLIB_TOKEN_TWITTER_RESP_KEY = "oauth_token\" type=\"hidden\" value=\""; const std::string OAUTHLIB_TOKEN_TWITTER_RESP_KEY = "oauth_token\" type=\"hidden\" value=\"";
const std::string OAUTHLIB_PIN_TWITTER_RESP_KEY = "code-desc\"><code>"; const std::string OAUTHLIB_PIN_TWITTER_RESP_KEY = "code-desc\"><code>";
const std::string OAUTHLIB_TOKEN_END_TAG_TWITTER_RESP = "\" />"; const std::string OAUTHLIB_TOKEN_END_TAG_TWITTER_RESP = "\" />";
const std::string OAUTHLIB_PIN_END_TAG_TWITTER_RESP = "</code>"; const std::string OAUTHLIB_PIN_END_TAG_TWITTER_RESP = "</code>";
const std::string OAUTHLIB_AUTHHEADER_STRING = "Authorization: OAuth "; const std::string OAUTHLIB_AUTHHEADER_STRING = "Authorization: OAuth ";
}; };
namespace oAuthTwitterApiUrls namespace oAuthTwitterApiUrls
{ {
/* Twitter OAuth API URLs */ /* Twitter OAuth API URLs */
const std::string OAUTHLIB_TWITTER_REQUEST_TOKEN_URL = "api.twitter.com/oauth/request_token"; const std::string OAUTHLIB_TWITTER_REQUEST_TOKEN_URL = "api.twitter.com/oauth/request_token";
const std::string OAUTHLIB_TWITTER_AUTHORIZE_URL = "api.twitter.com/oauth/authorize?oauth_token="; const std::string OAUTHLIB_TWITTER_AUTHORIZE_URL = "api.twitter.com/oauth/authorize?oauth_token=";
const std::string OAUTHLIB_TWITTER_ACCESS_TOKEN_URL = "api.twitter.com/oauth/access_token"; const std::string OAUTHLIB_TWITTER_ACCESS_TOKEN_URL = "api.twitter.com/oauth/access_token";
}; };
#endif // _TWITCURLURLS_H_ #endif // _TWITCURLURLS_H_

View file

@ -1,40 +1,40 @@
#include "urlencode.h" #include "urlencode.h"
std::string char2hex( char dec ) std::string char2hex( char dec )
{ {
char dig1 = (dec&0xF0)>>4; char dig1 = (dec&0xF0)>>4;
char dig2 = (dec&0x0F); char dig2 = (dec&0x0F);
if ( 0<= dig1 && dig1<= 9) dig1+=48; //0,48 in ascii if ( 0<= dig1 && dig1<= 9) dig1+=48; //0,48 in ascii
if (10<= dig1 && dig1<=15) dig1+=65-10; //A,65 in ascii if (10<= dig1 && dig1<=15) dig1+=65-10; //A,65 in ascii
if ( 0<= dig2 && dig2<= 9) dig2+=48; if ( 0<= dig2 && dig2<= 9) dig2+=48;
if (10<= dig2 && dig2<=15) dig2+=65-10; if (10<= dig2 && dig2<=15) dig2+=65-10;
std::string r; std::string r;
r.append( &dig1, 1); r.append( &dig1, 1);
r.append( &dig2, 1); r.append( &dig2, 1);
return r; return r;
} }
std::string urlencode( const std::string &c ) std::string urlencode( const std::string &c )
{ {
std::string escaped; std::string escaped;
int max = c.length(); int max = c.length();
for(int i=0; i<max; i++) for(int i=0; i<max; i++)
{ {
if ( (48 <= c[i] && c[i] <= 57) ||//0-9 if ( (48 <= c[i] && c[i] <= 57) ||//0-9
(65 <= c[i] && c[i] <= 90) ||//ABC...XYZ (65 <= c[i] && c[i] <= 90) ||//ABC...XYZ
(97 <= c[i] && c[i] <= 122) || //abc...xyz (97 <= c[i] && c[i] <= 122) || //abc...xyz
(c[i]=='~' || c[i]=='-' || c[i]=='_' || c[i]=='.') (c[i]=='~' || c[i]=='-' || c[i]=='_' || c[i]=='.')
) )
{ {
escaped.append( &c[i], 1); escaped.append( &c[i], 1);
} }
else else
{ {
escaped.append("%"); escaped.append("%");
escaped.append( char2hex(c[i]) );//converts char 255 to string "FF" escaped.append( char2hex(c[i]) );//converts char 255 to string "FF"
} }
} }
return escaped; return escaped;
} }

View file

@ -1,10 +1,10 @@
#ifndef __URLENCODE_H__ #ifndef __URLENCODE_H__
#define __URLENCODE_H__ #define __URLENCODE_H__
#include <iostream> #include <iostream>
#include <string> #include <string>
std::string char2hex( char dec ); std::string char2hex( char dec );
std::string urlencode( const std::string &c ); std::string urlencode( const std::string &c );
#endif // __URLENCODE_H__ #endif // __URLENCODE_H__

View file

@ -1 +1 @@
ADD_SUBDIRECTORY(transport) ADD_SUBDIRECTORY(transport)

View file

@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SQLITE_SRC *.c *.h) FILE(GLOB SQLITE_SRC *.c *.h)
ADD_LIBRARY(sqlite3 STATIC ${HEADERS} ${SQLITE_SRC}) ADD_LIBRARY(sqlite3 STATIC ${HEADERS} ${SQLITE_SRC})
INSTALL(TARGETS sqlite3 LIBRARY DESTINATION lib ARCHIVE DESTINATION lib COMPONENT libraries) INSTALL(TARGETS sqlite3 LIBRARY DESTINATION lib ARCHIVE DESTINATION lib COMPONENT libraries)

View file

@ -1,38 +1,38 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SRC *.cpp *.h) FILE(GLOB SRC *.cpp *.h)
FILE(GLOB HEADERS ../include/transport/*.h) FILE(GLOB HEADERS ../include/transport/*.h)
set(EXTRA_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../../src/memoryusage.cpp) set(EXTRA_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../../src/memoryusage.cpp)
set(EXTRA_SOURCES ${EXTRA_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/../../src/logging.cpp) set(EXTRA_SOURCES ${EXTRA_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/../../src/logging.cpp)
set(EXTRA_SOURCES ${EXTRA_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/../../src/config.cpp) set(EXTRA_SOURCES ${EXTRA_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/../../src/config.cpp)
set(EXTRA_SOURCES ${EXTRA_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/../../src/util.cpp) set(EXTRA_SOURCES ${EXTRA_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/../../src/util.cpp)
set(EXTRA_SOURCES ${EXTRA_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.pb.cc) set(EXTRA_SOURCES ${EXTRA_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.pb.cc)
if (NOT WIN32) if (NOT WIN32)
ADD_LIBRARY(transport-plugin SHARED ${HEADERS} ${SRC} ${PROTOBUF_SRC} ${PROTOBUF_HDRS} ${EXTRA_SOURCES}) ADD_LIBRARY(transport-plugin SHARED ${HEADERS} ${SRC} ${PROTOBUF_SRC} ${PROTOBUF_HDRS} ${EXTRA_SOURCES})
else() else()
ADD_LIBRARY(transport-plugin STATIC ${HEADERS} ${SRC} ${EXTRA_SOURCES} ) ADD_LIBRARY(transport-plugin STATIC ${HEADERS} ${SRC} ${EXTRA_SOURCES} )
endif() endif()
ADD_DEPENDENCIES(transport-plugin pb) ADD_DEPENDENCIES(transport-plugin pb)
SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.pb.cc PROPERTIES GENERATED 1) SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.pb.cc PROPERTIES GENERATED 1)
if (CMAKE_COMPILER_IS_GNUCXX) if (CMAKE_COMPILER_IS_GNUCXX)
if (NOT WIN32) if (NOT WIN32)
ADD_DEFINITIONS(-fPIC) ADD_DEFINITIONS(-fPIC)
endif() endif()
endif() endif()
if (NOT WIN32) if (NOT WIN32)
TARGET_LINK_LIBRARIES(transport-plugin ${PROTOBUF_LIBRARY} ${LOG4CXX_LIBRARIES} ${Boost_LIBRARIES}) TARGET_LINK_LIBRARIES(transport-plugin ${PROTOBUF_LIBRARY} ${LOG4CXX_LIBRARIES} ${Boost_LIBRARIES})
else() else()
TARGET_LINK_LIBRARIES(transport-plugin ${PROTOBUF_LIBRARY} ${LOG4CXX_LIBRARIES} ${Boost_LIBRARIES} ws2_32.lib) TARGET_LINK_LIBRARIES(transport-plugin ${PROTOBUF_LIBRARY} ${LOG4CXX_LIBRARIES} ${Boost_LIBRARIES} ws2_32.lib)
endif() endif()
SET_TARGET_PROPERTIES(transport-plugin PROPERTIES SET_TARGET_PROPERTIES(transport-plugin PROPERTIES
VERSION ${TRANSPORT_VERSION} SOVERSION ${TRANSPORT_VERSION} VERSION ${TRANSPORT_VERSION} SOVERSION ${TRANSPORT_VERSION}
) )
INSTALL(TARGETS transport-plugin LIBRARY DESTINATION ${LIB_INSTALL_DIR} ARCHIVE DESTINATION ${LIB_INSTALL_DIR} COMPONENT libraries) INSTALL(TARGETS transport-plugin LIBRARY DESTINATION ${LIB_INSTALL_DIR} ARCHIVE DESTINATION ${LIB_INSTALL_DIR} COMPONENT libraries)
#CONFIGURE_FILE(transport.pc.in "${CMAKE_CURRENT_SOURCE_DIR}/transport.pc") #CONFIGURE_FILE(transport.pc.in "${CMAKE_CURRENT_SOURCE_DIR}/transport.pc")
#INSTALL(FILES "${CMAKE_CURRENT_SOURCE_DIR}/transport.pc" DESTINATION lib/pkgconfig) #INSTALL(FILES "${CMAKE_CURRENT_SOURCE_DIR}/transport.pc" DESTINATION lib/pkgconfig)

View file

@ -1,15 +1,15 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
if (PROTOBUF_FOUND) if (PROTOBUF_FOUND)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/protocol_pb2.py OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/protocol_pb2.py
COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} --python_out ${CMAKE_CURRENT_SOURCE_DIR} --proto_path ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/ ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.proto COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} --python_out ${CMAKE_CURRENT_SOURCE_DIR} --proto_path ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/ ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.proto
COMMENT "Running Python protocol buffer compiler on protocol.proto" COMMENT "Running Python protocol buffer compiler on protocol.proto"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.proto DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.proto
) )
ADD_CUSTOM_TARGET(pb-python ALL DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/protocol_pb2.py) ADD_CUSTOM_TARGET(pb-python ALL DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/protocol_pb2.py)
endif() endif()

View file

@ -1,48 +1,48 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SRC *.cpp) FILE(GLOB SRC *.cpp)
if (WIN32) if (WIN32)
FILE(GLOB WIN_SRC win32/*.cpp) FILE(GLOB WIN_SRC win32/*.cpp)
include_directories(win32) include_directories(win32)
include_directories("${CMAKE_SOURCE_DIR}/msvc-deps/sqlite3") include_directories("${CMAKE_SOURCE_DIR}/msvc-deps/sqlite3")
ADD_EXECUTABLE(spectrum2 ${SRC} ${WIN_SRC}) ADD_EXECUTABLE(spectrum2 ${SRC} ${WIN_SRC})
else() else()
ADD_EXECUTABLE(spectrum2 ${SRC}) ADD_EXECUTABLE(spectrum2 ${SRC})
endif() endif()
ADD_DEPENDENCIES(spectrum2 spectrum2_libpurple_backend) ADD_DEPENDENCIES(spectrum2 spectrum2_libpurple_backend)
ADD_DEPENDENCIES(spectrum2 spectrum2_libircclient-qt_backend) ADD_DEPENDENCIES(spectrum2 spectrum2_libircclient-qt_backend)
if (WIN32) if (WIN32)
target_link_libraries(spectrum2 transport sqlite3 ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES} ${PROTOBUF_LIBRARY}) target_link_libraries(spectrum2 transport sqlite3 ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES} ${PROTOBUF_LIBRARY})
else () else ()
target_link_libraries(spectrum2 transport ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES} ${PROTOBUF_LIBRARY}) target_link_libraries(spectrum2 transport ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES} ${PROTOBUF_LIBRARY})
endif() endif()
INSTALL(TARGETS spectrum2 RUNTIME DESTINATION bin) INSTALL(TARGETS spectrum2 RUNTIME DESTINATION bin)
INSTALL(FILES INSTALL(FILES
sample2_gateway.cfg sample2_gateway.cfg
RENAME spectrum.cfg.example RENAME spectrum.cfg.example
DESTINATION /etc/spectrum2/transports DESTINATION /etc/spectrum2/transports
) )
INSTALL(FILES INSTALL(FILES
sample2.cfg sample2.cfg
RENAME spectrum_server_mode.cfg.example RENAME spectrum_server_mode.cfg.example
DESTINATION /etc/spectrum2/transports DESTINATION /etc/spectrum2/transports
) )
INSTALL(FILES INSTALL(FILES
backend-logging.cfg backend-logging.cfg
DESTINATION /etc/spectrum2 DESTINATION /etc/spectrum2
) )
INSTALL(FILES INSTALL(FILES
logging.cfg logging.cfg
DESTINATION /etc/spectrum2 DESTINATION /etc/spectrum2
) )

View file

@ -1,19 +1,19 @@
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
FILE(GLOB SRC *.cpp *.c) FILE(GLOB SRC *.cpp *.c)
ADD_EXECUTABLE(spectrum2_manager ${SRC} ../../src/config.cpp ../../src/util.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.pb.cc) ADD_EXECUTABLE(spectrum2_manager ${SRC} ../../src/config.cpp ../../src/util.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.pb.cc)
ADD_DEPENDENCIES(spectrum2_manager pb) ADD_DEPENDENCIES(spectrum2_manager pb)
SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.pb.cc PROPERTIES GENERATED 1) SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.pb.cc PROPERTIES GENERATED 1)
target_link_libraries(spectrum2_manager ${SWIFTEN_LIBRARY} ${PROTOBUF_LIBRARIES}) target_link_libraries(spectrum2_manager ${SWIFTEN_LIBRARY} ${PROTOBUF_LIBRARIES})
if(APPLE) if(APPLE)
target_link_libraries(spectrum2_manager ${APPLE_FRAMEWORKS}) target_link_libraries(spectrum2_manager ${APPLE_FRAMEWORKS})
endif() endif()
INSTALL(TARGETS spectrum2_manager RUNTIME DESTINATION bin) INSTALL(TARGETS spectrum2_manager RUNTIME DESTINATION bin)
INSTALL(FILES INSTALL(FILES
spectrum_manager.cfg spectrum_manager.cfg
DESTINATION /etc/spectrum2 DESTINATION /etc/spectrum2
) )

View file

@ -1,200 +1,200 @@
#include "managerconfig.h" #include "managerconfig.h"
#include "methods.h" #include "methods.h"
#include "server.h" #include "server.h"
#include "transport/config.h" #include "transport/config.h"
#include "transport/protocol.pb.h" #include "transport/protocol.pb.h"
#include "Swiften/Swiften.h" #include "Swiften/Swiften.h"
#include "Swiften/EventLoop/SimpleEventLoop.h" #include "Swiften/EventLoop/SimpleEventLoop.h"
#include <boost/foreach.hpp> #include <boost/foreach.hpp>
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
#include <iterator> #include <iterator>
#include <algorithm> #include <algorithm>
#include <boost/filesystem.hpp> #include <boost/filesystem.hpp>
#include <cstdlib> #include <cstdlib>
#include "signal.h" #include "signal.h"
#include "sys/wait.h" #include "sys/wait.h"
using namespace Transport; using namespace Transport;
using namespace boost::filesystem; using namespace boost::filesystem;
using namespace boost; using namespace boost;
// static void ask_local_servers(ManagerConfig *config, Swift::BoostNetworkFactories &networkFactories, const std::string &message) { // static void ask_local_servers(ManagerConfig *config, Swift::BoostNetworkFactories &networkFactories, const std::string &message) {
// path p(CONFIG_STRING(config, "service.config_directory")); // path p(CONFIG_STRING(config, "service.config_directory"));
// //
// try { // try {
// if (!exists(p)) { // if (!exists(p)) {
// std::cerr << "Config directory " << CONFIG_STRING(config, "service.config_directory") << " does not exist\n"; // std::cerr << "Config directory " << CONFIG_STRING(config, "service.config_directory") << " does not exist\n";
// exit(6); // exit(6);
// } // }
// //
// if (!is_directory(p)) { // if (!is_directory(p)) {
// std::cerr << "Config directory " << CONFIG_STRING(config, "service.config_directory") << " does not exist\n"; // std::cerr << "Config directory " << CONFIG_STRING(config, "service.config_directory") << " does not exist\n";
// exit(7); // exit(7);
// } // }
// //
// directory_iterator end_itr; // directory_iterator end_itr;
// for (directory_iterator itr(p); itr != end_itr; ++itr) { // for (directory_iterator itr(p); itr != end_itr; ++itr) {
// if (is_regular(itr->path()) && extension(itr->path()) == ".cfg") { // if (is_regular(itr->path()) && extension(itr->path()) == ".cfg") {
// Config cfg; // Config cfg;
// if (cfg.load(itr->path().string()) == false) { // if (cfg.load(itr->path().string()) == false) {
// std::cerr << "Can't load config file " << itr->path().string() << ". Skipping...\n"; // std::cerr << "Can't load config file " << itr->path().string() << ". Skipping...\n";
// continue; // continue;
// } // }
// //
// if (CONFIG_VECTOR(&cfg, "service.admin_jid").empty() || CONFIG_STRING(&cfg, "service.admin_password").empty()) { // if (CONFIG_VECTOR(&cfg, "service.admin_jid").empty() || CONFIG_STRING(&cfg, "service.admin_password").empty()) {
// std::cerr << itr->path().string() << ": service.admin_jid or service.admin_password empty. This server can't be queried over XMPP.\n"; // std::cerr << itr->path().string() << ": service.admin_jid or service.admin_password empty. This server can't be queried over XMPP.\n";
// continue; // continue;
// } // }
// //
// finished++; // finished++;
// Swift::Client *client = new Swift::Client(CONFIG_VECTOR(&cfg, "service.admin_jid")[0], CONFIG_STRING(&cfg, "service.admin_password"), &networkFactories); // Swift::Client *client = new Swift::Client(CONFIG_VECTOR(&cfg, "service.admin_jid")[0], CONFIG_STRING(&cfg, "service.admin_password"), &networkFactories);
// client->setAlwaysTrustCertificates(); // client->setAlwaysTrustCertificates();
// client->onConnected.connect(boost::bind(&handleConnected, client, CONFIG_STRING(&cfg, "service.jid"))); // client->onConnected.connect(boost::bind(&handleConnected, client, CONFIG_STRING(&cfg, "service.jid")));
// client->onDisconnected.connect(bind(&handleDisconnected, client, _1, CONFIG_STRING(&cfg, "service.jid"))); // client->onDisconnected.connect(bind(&handleDisconnected, client, _1, CONFIG_STRING(&cfg, "service.jid")));
// client->onMessageReceived.connect(bind(&handleMessageReceived, client, _1, CONFIG_STRING(&cfg, "service.jid"))); // client->onMessageReceived.connect(bind(&handleMessageReceived, client, _1, CONFIG_STRING(&cfg, "service.jid")));
// Swift::ClientOptions opt; // Swift::ClientOptions opt;
// opt.allowPLAINWithoutTLS = true; // opt.allowPLAINWithoutTLS = true;
// client->connect(opt); // client->connect(opt);
// } // }
// } // }
// } // }
// catch (const filesystem_error& ex) { // catch (const filesystem_error& ex) {
// std::cerr << "boost filesystem error\n"; // std::cerr << "boost filesystem error\n";
// exit(5); // exit(5);
// } // }
// } // }
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
ManagerConfig config; ManagerConfig config;
std::string config_file; std::string config_file;
std::vector<std::string> command; std::vector<std::string> command;
boost::program_options::variables_map vm; boost::program_options::variables_map vm;
boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <COMMAND>\n" boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <COMMAND>\n"
" spectrum [OPTIONS] <instance_JID> <other>\nCommands:\n" " spectrum [OPTIONS] <instance_JID> <other>\nCommands:\n"
" start - start all local Spectrum2 instances\n" " start - start all local Spectrum2 instances\n"
" stop - stop all local Spectrum2 instances\n" " stop - stop all local Spectrum2 instances\n"
" restart - restart all local Spectrum2 instances\n" " restart - restart all local Spectrum2 instances\n"
" status - status of local Spectrum2 instances\n" " status - status of local Spectrum2 instances\n"
" <other> - send command to local Spectrum2 instance and print output\n" " <other> - send command to local Spectrum2 instance and print output\n"
"Allowed options"); "Allowed options");
desc.add_options() desc.add_options()
("help,h", "Show help output") ("help,h", "Show help output")
("config,c", boost::program_options::value<std::string>(&config_file)->default_value("/etc/spectrum2/spectrum_manager.cfg"), "Spectrum manager config file") ("config,c", boost::program_options::value<std::string>(&config_file)->default_value("/etc/spectrum2/spectrum_manager.cfg"), "Spectrum manager config file")
("command", boost::program_options::value<std::vector<std::string> >(&command), "Command") ("command", boost::program_options::value<std::vector<std::string> >(&command), "Command")
; ;
try try
{ {
boost::program_options::positional_options_description p; boost::program_options::positional_options_description p;
p.add("command", -1); p.add("command", -1);
boost::program_options::store(boost::program_options::command_line_parser(argc, argv). boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm); options(desc).positional(p).run(), vm);
boost::program_options::notify(vm); boost::program_options::notify(vm);
if(vm.count("help")) if(vm.count("help"))
{ {
std::cout << desc << "\n"; std::cout << desc << "\n";
return 1; return 1;
} }
} }
catch (std::runtime_error& e) catch (std::runtime_error& e)
{ {
std::cout << desc << "\n"; std::cout << desc << "\n";
return 2; return 2;
} }
catch (...) catch (...)
{ {
std::cout << desc << "\n"; std::cout << desc << "\n";
return 3; return 3;
} }
if (!config.load(config_file)) { if (!config.load(config_file)) {
std::cerr << "Can't load configuration file.\n"; std::cerr << "Can't load configuration file.\n";
return 4; return 4;
} }
if (command.empty()) { if (command.empty()) {
std::cout << desc << "\n"; std::cout << desc << "\n";
return 1; return 1;
} }
if (command[0] == "start") { if (command[0] == "start") {
return start_instances(&config); return start_instances(&config);
} }
else if (command[0] == "stop") { else if (command[0] == "stop") {
stop_instances(&config); stop_instances(&config);
} }
else if (command[0] == "status") { else if (command[0] == "status") {
return show_status(&config); return show_status(&config);
} }
else if (command[0] == "list") { else if (command[0] == "list") {
std::vector<std::string> list = show_list(&config); std::vector<std::string> list = show_list(&config);
} }
else if (command[0] == "restart") { else if (command[0] == "restart") {
return restart_instances(&config); return restart_instances(&config);
} }
else if (command[0] == "server") { else if (command[0] == "server") {
Server server(&config); Server server(&config);
if (server.start() == false) { if (server.start() == false) {
std::cerr << "Can't set up server handler.\n"; std::cerr << "Can't set up server handler.\n";
return 1; return 1;
} }
while (1) { sleep(10); } while (1) { sleep(10); }
} }
else { else {
if (command.size() < 2) { if (command.size() < 2) {
std::cout << desc << "\n"; std::cout << desc << "\n";
return 11; return 11;
} }
Swift::SimpleEventLoop eventLoop; Swift::SimpleEventLoop eventLoop;
Swift::BoostNetworkFactories networkFactories(&eventLoop); Swift::BoostNetworkFactories networkFactories(&eventLoop);
std::string jid = command[0]; std::string jid = command[0];
command.erase(command.begin()); command.erase(command.begin());
std::string cmd = boost::algorithm::join(command, " "); std::string cmd = boost::algorithm::join(command, " ");
if (cmd == "start") { if (cmd == "start") {
return start_instances(&config, jid); return start_instances(&config, jid);
} }
else if (cmd == "stop") { else if (cmd == "stop") {
stop_instances(&config, jid); stop_instances(&config, jid);
return 0; return 0;
} }
else if (cmd == "restart") { else if (cmd == "restart") {
return restart_instances(&config, jid); return restart_instances(&config, jid);
} }
ask_local_server(&config, networkFactories, jid, cmd); ask_local_server(&config, networkFactories, jid, cmd);
// std::string message = command; // std::string message = command;
// m = &message; // m = &message;
// ask_local_server(&config, networkFactories, message); // ask_local_server(&config, networkFactories, message);
eventLoop.runUntilEvents(); eventLoop.runUntilEvents();
struct timeval td_start,td_end; struct timeval td_start,td_end;
float elapsed = 0; float elapsed = 0;
gettimeofday(&td_start, NULL); gettimeofday(&td_start, NULL);
time_t started = time(NULL); time_t started = time(NULL);
while(get_response().empty()) { while(get_response().empty()) {
eventLoop.runUntilEvents(); eventLoop.runUntilEvents();
} }
if (!get_response().empty()) { if (!get_response().empty()) {
gettimeofday(&td_end, NULL); gettimeofday(&td_end, NULL);
elapsed = 1000000.0 * (td_end.tv_sec -td_start.tv_sec); \ elapsed = 1000000.0 * (td_end.tv_sec -td_start.tv_sec); \
elapsed += (td_end.tv_usec - td_start.tv_usec); \ elapsed += (td_end.tv_usec - td_start.tv_usec); \
elapsed = elapsed / 1000 / 1000; \ elapsed = elapsed / 1000 / 1000; \
// std::cout << "Response received after " << (elapsed) << " seconds\n"; // std::cout << "Response received after " << (elapsed) << " seconds\n";
} }
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,301 +1,301 @@
// Copyright (c) 2004-2012 Sergey Lyubka // Copyright (c) 2004-2012 Sergey Lyubka
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // furnished to do so, subject to the following conditions:
// //
// The above copyright notice and this permission notice shall be included in // The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software. // all copies or substantial portions of the Software.
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
#ifndef MONGOOSE_HEADER_INCLUDED #ifndef MONGOOSE_HEADER_INCLUDED
#define MONGOOSE_HEADER_INCLUDED #define MONGOOSE_HEADER_INCLUDED
#include <stdio.h> #include <stdio.h>
#include <stddef.h> #include <stddef.h>
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif // __cplusplus #endif // __cplusplus
struct mg_context; // Handle for the HTTP service itself struct mg_context; // Handle for the HTTP service itself
struct mg_connection; // Handle for the individual connection struct mg_connection; // Handle for the individual connection
// This structure contains information about the HTTP request. // This structure contains information about the HTTP request.
struct mg_request_info { struct mg_request_info {
void *user_data; // User-defined pointer passed to mg_start() void *user_data; // User-defined pointer passed to mg_start()
char *request_method; // "GET", "POST", etc char *request_method; // "GET", "POST", etc
char *uri; // URL-decoded URI char *uri; // URL-decoded URI
char *http_version; // E.g. "1.0", "1.1" char *http_version; // E.g. "1.0", "1.1"
char *query_string; // URL part after '?' (not including '?') or NULL char *query_string; // URL part after '?' (not including '?') or NULL
char *remote_user; // Authenticated user, or NULL if no auth used char *remote_user; // Authenticated user, or NULL if no auth used
char *log_message; // Mongoose error log message, MG_EVENT_LOG only char *log_message; // Mongoose error log message, MG_EVENT_LOG only
long remote_ip; // Client's IP address long remote_ip; // Client's IP address
int remote_port; // Client's port int remote_port; // Client's port
int status_code; // HTTP reply status code, e.g. 200 int status_code; // HTTP reply status code, e.g. 200
int is_ssl; // 1 if SSL-ed, 0 if not int is_ssl; // 1 if SSL-ed, 0 if not
int num_headers; // Number of headers int num_headers; // Number of headers
struct mg_header { struct mg_header {
char *name; // HTTP header name char *name; // HTTP header name
char *value; // HTTP header value char *value; // HTTP header value
} http_headers[64]; // Maximum 64 headers } http_headers[64]; // Maximum 64 headers
}; };
// Various events on which user-defined function is called by Mongoose. // Various events on which user-defined function is called by Mongoose.
enum mg_event { enum mg_event {
MG_NEW_REQUEST, // New HTTP request has arrived from the client MG_NEW_REQUEST, // New HTTP request has arrived from the client
MG_REQUEST_COMPLETE, // Mongoose has finished handling the request MG_REQUEST_COMPLETE, // Mongoose has finished handling the request
MG_HTTP_ERROR, // HTTP error must be returned to the client MG_HTTP_ERROR, // HTTP error must be returned to the client
MG_EVENT_LOG, // Mongoose logs an event, request_info.log_message MG_EVENT_LOG, // Mongoose logs an event, request_info.log_message
MG_INIT_SSL // Mongoose initializes SSL. Instead of mg_connection *, MG_INIT_SSL // Mongoose initializes SSL. Instead of mg_connection *,
// SSL context is passed to the callback function. // SSL context is passed to the callback function.
}; };
// Prototype for the user-defined function. Mongoose calls this function // Prototype for the user-defined function. Mongoose calls this function
// on every MG_* event. // on every MG_* event.
// //
// Parameters: // Parameters:
// event: which event has been triggered. // event: which event has been triggered.
// conn: opaque connection handler. Could be used to read, write data to the // conn: opaque connection handler. Could be used to read, write data to the
// client, etc. See functions below that have "mg_connection *" arg. // client, etc. See functions below that have "mg_connection *" arg.
// //
// Return: // Return:
// If handler returns non-NULL, that means that handler has processed the // If handler returns non-NULL, that means that handler has processed the
// request by sending appropriate HTTP reply to the client. Mongoose treats // request by sending appropriate HTTP reply to the client. Mongoose treats
// the request as served. // the request as served.
// If handler returns NULL, that means that handler has not processed // If handler returns NULL, that means that handler has not processed
// the request. Handler must not send any data to the client in this case. // the request. Handler must not send any data to the client in this case.
// Mongoose proceeds with request handling as if nothing happened. // Mongoose proceeds with request handling as if nothing happened.
typedef void * (*mg_callback_t)(enum mg_event event, typedef void * (*mg_callback_t)(enum mg_event event,
struct mg_connection *conn); struct mg_connection *conn);
// Start web server. // Start web server.
// //
// Parameters: // Parameters:
// callback: user defined event handling function or NULL. // callback: user defined event handling function or NULL.
// options: NULL terminated list of option_name, option_value pairs that // options: NULL terminated list of option_name, option_value pairs that
// specify Mongoose configuration parameters. // specify Mongoose configuration parameters.
// //
// Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom // Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
// processing is required for these, signal handlers must be set up // processing is required for these, signal handlers must be set up
// after calling mg_start(). // after calling mg_start().
// //
// //
// Example: // Example:
// const char *options[] = { // const char *options[] = {
// "document_root", "/var/www", // "document_root", "/var/www",
// "listening_ports", "80,443s", // "listening_ports", "80,443s",
// NULL // NULL
// }; // };
// struct mg_context *ctx = mg_start(&my_func, NULL, options); // struct mg_context *ctx = mg_start(&my_func, NULL, options);
// //
// Please refer to http://code.google.com/p/mongoose/wiki/MongooseManual // Please refer to http://code.google.com/p/mongoose/wiki/MongooseManual
// for the list of valid option and their possible values. // for the list of valid option and their possible values.
// //
// Return: // Return:
// web server context, or NULL on error. // web server context, or NULL on error.
struct mg_context *mg_start(mg_callback_t callback, void *user_data, struct mg_context *mg_start(mg_callback_t callback, void *user_data,
const char **options); const char **options);
// Stop the web server. // Stop the web server.
// //
// Must be called last, when an application wants to stop the web server and // Must be called last, when an application wants to stop the web server and
// release all associated resources. This function blocks until all Mongoose // release all associated resources. This function blocks until all Mongoose
// threads are stopped. Context pointer becomes invalid. // threads are stopped. Context pointer becomes invalid.
void mg_stop(struct mg_context *); void mg_stop(struct mg_context *);
// Get the value of particular configuration parameter. // Get the value of particular configuration parameter.
// The value returned is read-only. Mongoose does not allow changing // The value returned is read-only. Mongoose does not allow changing
// configuration at run time. // configuration at run time.
// If given parameter name is not valid, NULL is returned. For valid // If given parameter name is not valid, NULL is returned. For valid
// names, return value is guaranteed to be non-NULL. If parameter is not // names, return value is guaranteed to be non-NULL. If parameter is not
// set, zero-length string is returned. // set, zero-length string is returned.
const char *mg_get_option(const struct mg_context *ctx, const char *name); const char *mg_get_option(const struct mg_context *ctx, const char *name);
// Return array of strings that represent valid configuration options. // Return array of strings that represent valid configuration options.
// For each option, a short name, long name, and default value is returned. // For each option, a short name, long name, and default value is returned.
// Array is NULL terminated. // Array is NULL terminated.
const char **mg_get_valid_option_names(void); const char **mg_get_valid_option_names(void);
// Add, edit or delete the entry in the passwords file. // Add, edit or delete the entry in the passwords file.
// //
// This function allows an application to manipulate .htpasswd files on the // This function allows an application to manipulate .htpasswd files on the
// fly by adding, deleting and changing user records. This is one of the // fly by adding, deleting and changing user records. This is one of the
// several ways of implementing authentication on the server side. For another, // several ways of implementing authentication on the server side. For another,
// cookie-based way please refer to the examples/chat.c in the source tree. // cookie-based way please refer to the examples/chat.c in the source tree.
// //
// If password is not NULL, entry is added (or modified if already exists). // If password is not NULL, entry is added (or modified if already exists).
// If password is NULL, entry is deleted. // If password is NULL, entry is deleted.
// //
// Return: // Return:
// 1 on success, 0 on error. // 1 on success, 0 on error.
int mg_modify_passwords_file(const char *passwords_file_name, int mg_modify_passwords_file(const char *passwords_file_name,
const char *domain, const char *domain,
const char *user, const char *user,
const char *password); const char *password);
// Return mg_request_info structure associated with the request. // Return mg_request_info structure associated with the request.
// Always succeeds. // Always succeeds.
const struct mg_request_info *mg_get_request_info(const struct mg_connection *); const struct mg_request_info *mg_get_request_info(const struct mg_connection *);
// Send data to the client. // Send data to the client.
// Return: // Return:
// 0 when the connection has been closed // 0 when the connection has been closed
// -1 on error // -1 on error
// number of bytes written on success // number of bytes written on success
int mg_write(struct mg_connection *, const void *buf, size_t len); int mg_write(struct mg_connection *, const void *buf, size_t len);
// Send data to the browser using printf() semantics. // Send data to the browser using printf() semantics.
// //
// Works exactly like mg_write(), but allows to do message formatting. // Works exactly like mg_write(), but allows to do message formatting.
// Below are the macros for enabling compiler-specific checks for // Below are the macros for enabling compiler-specific checks for
// printf-like arguments. // printf-like arguments.
#undef PRINTF_FORMAT_STRING #undef PRINTF_FORMAT_STRING
#if _MSC_VER >= 1400 #if _MSC_VER >= 1400
#include <sal.h> #include <sal.h>
#if _MSC_VER > 1400 #if _MSC_VER > 1400
#define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s #define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
#else #else
#define PRINTF_FORMAT_STRING(s) __format_string s #define PRINTF_FORMAT_STRING(s) __format_string s
#endif #endif
#else #else
#define PRINTF_FORMAT_STRING(s) s #define PRINTF_FORMAT_STRING(s) s
#endif #endif
#ifdef __GNUC__ #ifdef __GNUC__
#define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y))) #define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
#else #else
#define PRINTF_ARGS(x, y) #define PRINTF_ARGS(x, y)
#endif #endif
int mg_printf(struct mg_connection *, int mg_printf(struct mg_connection *,
PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3); PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
// Send contents of the entire file together with HTTP headers. // Send contents of the entire file together with HTTP headers.
void mg_send_file(struct mg_connection *conn, const char *path); void mg_send_file(struct mg_connection *conn, const char *path);
// Read data from the remote end, return number of bytes read. // Read data from the remote end, return number of bytes read.
int mg_read(struct mg_connection *, void *buf, size_t len); int mg_read(struct mg_connection *, void *buf, size_t len);
// Get the value of particular HTTP header. // Get the value of particular HTTP header.
// //
// This is a helper function. It traverses request_info->http_headers array, // This is a helper function. It traverses request_info->http_headers array,
// and if the header is present in the array, returns its value. If it is // and if the header is present in the array, returns its value. If it is
// not present, NULL is returned. // not present, NULL is returned.
const char *mg_get_header(const struct mg_connection *, const char *name); const char *mg_get_header(const struct mg_connection *, const char *name);
// Get a value of particular form variable. // Get a value of particular form variable.
// //
// Parameters: // Parameters:
// data: pointer to form-uri-encoded buffer. This could be either POST data, // data: pointer to form-uri-encoded buffer. This could be either POST data,
// or request_info.query_string. // or request_info.query_string.
// data_len: length of the encoded data. // data_len: length of the encoded data.
// var_name: variable name to decode from the buffer // var_name: variable name to decode from the buffer
// buf: destination buffer for the decoded variable // buf: destination buffer for the decoded variable
// buf_len: length of the destination buffer // buf_len: length of the destination buffer
// //
// Return: // Return:
// On success, length of the decoded variable. // On success, length of the decoded variable.
// On error: // On error:
// -1 (variable not found, or destination buffer is too small). // -1 (variable not found, or destination buffer is too small).
// -2 (destination buffer is NULL or zero length). // -2 (destination buffer is NULL or zero length).
// //
// Destination buffer is guaranteed to be '\0' - terminated if it is not // Destination buffer is guaranteed to be '\0' - terminated if it is not
// NULL or zero length. In case of failure, dst[0] == '\0'. // NULL or zero length. In case of failure, dst[0] == '\0'.
int mg_get_var(const char *data, size_t data_len, int mg_get_var(const char *data, size_t data_len,
const char *var_name, char *buf, size_t buf_len); const char *var_name, char *buf, size_t buf_len);
// Fetch value of certain cookie variable into the destination buffer. // Fetch value of certain cookie variable into the destination buffer.
// //
// Destination buffer is guaranteed to be '\0' - terminated. In case of // Destination buffer is guaranteed to be '\0' - terminated. In case of
// failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same // failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
// parameter. This function returns only first occurrence. // parameter. This function returns only first occurrence.
// //
// Return: // Return:
// On success, value length. // On success, value length.
// On error, -1 (either "Cookie:" header is not present at all, or the // On error, -1 (either "Cookie:" header is not present at all, or the
// requested parameter is not found, or destination buffer is too small // requested parameter is not found, or destination buffer is too small
// to hold the value). // to hold the value).
int mg_get_cookie(const struct mg_connection *, int mg_get_cookie(const struct mg_connection *,
const char *cookie_name, char *buf, size_t buf_len); const char *cookie_name, char *buf, size_t buf_len);
// Connect to the remote web server. // Connect to the remote web server.
// Return: // Return:
// On success, valid pointer to the new connection // On success, valid pointer to the new connection
// On error, NULL // On error, NULL
struct mg_connection *mg_connect(struct mg_context *ctx, struct mg_connection *mg_connect(struct mg_context *ctx,
const char *host, int port, int use_ssl); const char *host, int port, int use_ssl);
// Close the connection opened by mg_connect(). // Close the connection opened by mg_connect().
void mg_close_connection(struct mg_connection *conn); void mg_close_connection(struct mg_connection *conn);
// Download given URL to a given file. // Download given URL to a given file.
// url: URL to download // url: URL to download
// path: file name where to save the data // path: file name where to save the data
// request_info: pointer to a structure that will hold parsed reply headers // request_info: pointer to a structure that will hold parsed reply headers
// buf, bul_len: a buffer for the reply headers // buf, bul_len: a buffer for the reply headers
// Return: // Return:
// On error, NULL // On error, NULL
// On success, opened file stream to the downloaded contents. The stream // On success, opened file stream to the downloaded contents. The stream
// is positioned to the end of the file. It is the user's responsibility // is positioned to the end of the file. It is the user's responsibility
// to fclose() the opened file stream. // to fclose() the opened file stream.
FILE *mg_fetch(struct mg_context *ctx, const char *url, const char *path, FILE *mg_fetch(struct mg_context *ctx, const char *url, const char *path,
char *buf, size_t buf_len, struct mg_request_info *request_info); char *buf, size_t buf_len, struct mg_request_info *request_info);
// Convenience function -- create detached thread. // Convenience function -- create detached thread.
// Return: 0 on success, non-0 on error. // Return: 0 on success, non-0 on error.
typedef void * (*mg_thread_func_t)(void *); typedef void * (*mg_thread_func_t)(void *);
int mg_start_thread(mg_thread_func_t f, void *p); int mg_start_thread(mg_thread_func_t f, void *p);
// Return builtin mime type for the given file name. // Return builtin mime type for the given file name.
// For unrecognized extensions, "text/plain" is returned. // For unrecognized extensions, "text/plain" is returned.
const char *mg_get_builtin_mime_type(const char *file_name); const char *mg_get_builtin_mime_type(const char *file_name);
// Return Mongoose version. // Return Mongoose version.
const char *mg_version(void); const char *mg_version(void);
// MD5 hash given strings. // MD5 hash given strings.
// Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of // Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
// ASCIIz strings. When function returns, buf will contain human-readable // ASCIIz strings. When function returns, buf will contain human-readable
// MD5 hash. Example: // MD5 hash. Example:
// char buf[33]; // char buf[33];
// mg_md5(buf, "aa", "bb", NULL); // mg_md5(buf, "aa", "bb", NULL);
void mg_md5(char buf[33], ...); void mg_md5(char buf[33], ...);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif // __cplusplus #endif // __cplusplus
#endif // MONGOOSE_HEADER_INCLUDED #endif // MONGOOSE_HEADER_INCLUDED