Merge remote branch 'upstream/master'

This commit is contained in:
Daniel Henninger 2012-09-14 11:25:47 -04:00
commit 3724ba2c0c
401 changed files with 257601 additions and 1672 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
*.pb.cc
*.pb.h
plugin/python/protocol_pb2.py

View file

@ -1,58 +1,167 @@
cmake_minimum_required(VERSION 2.6)
project(libtransport)
message(STATUS "Variables to override default places where to find libraries:")
message(STATUS "|- cppunit : -DCPPUNIT_INCLUDE_DIR, -DCPPUNIT_LIBRARY")
message(STATUS "|- swiften : -DSWIFTEN_INCLUDE_DIR, -DSWIFTEN_LIBRARY")
message(STATUS " |- zlib : -DZLIB_LIBRARY")
message(STATUS " |- expat : -DEXPAT_LIBRARY")
message(STATUS " |-libidn : -DLIBIDN_LIBRARY")
message(STATUS " |-libxml : -DLIBXML_LIBRARY")
message(STATUS "|- boost : -DBOOST_INCLUDEDIR, -DBOOST_LIBRARYDIR")
message(STATUS "|- protobuf: -DPROTOBUF_INCLUDE_DIR, -DPROTOBUF_LIBRARY")
message(STATUS " : -DPROTOBUF_PROTOC_EXECUTABLE")
message(STATUS "|- log4cxx : -DLOG4CXX_INCLUDE_DIR, -DLOG4CXX_LIBRARY")
message(STATUS "|- purple : -DPURPLE_INCLUDE_DIR, -DPURPLE_LIBRARY")
message(STATUS " : -DPURPLE_NOT_RUNTIME - enables compilation with libpurple.lib")
if(NOT LIB_INSTALL_DIR)
set(LIB_INSTALL_DIR "lib")
endif()
set(CMAKE_MODULE_PATH "cmake_modules")
# FIND CPPUNIT
set(cppunit_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(cppunit)
if(NOT CPPUNIT_FOUND AND CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARY)
set(CCPUNIT_LIBRARIES ${CPPUNIT_LIBRARY})
set(CPPUNIT_FOUND 1)
message(STATUS "Using cppunit: ${CPPUNIT_INCLUDE_DIR} ${CPPUNIT_LIBRARIES}")
else()
endif()
# FIND SQLITE3
if (NOT CMAKE_COMPILER_IS_GNUCXX)
ADD_SUBDIRECTORY(msvc-deps)
else()
if (WIN32)
ADD_SUBDIRECTORY(msvc-deps/sqlite3)
else()
set(sqlite3_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(sqlite3)
endif()
endif()
# FIND MYSQL
set(mysql_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(mysql)
# FIND LIBPURPLE
set(purple_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(purple)
set(glib_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(glib)
if (WIN32)
if (PURPLE_NOT_RUNTIME)
add_definitions(-DPURPLE_RUNTIME=0)
else(PURPLE_NOT_RUNTIME)
add_definitions(-DPURPLE_RUNTIME=1)
endif(PURPLE_NOT_RUNTIME)
else()
add_definitions(-DPURPLE_RUNTIME=0)
endif()
# FIND GLIB
# if (GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES)
# set(GLIB2_FOUND TRUE)
# else()
set(glib_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(glib)
# endif()
# FIND LIBXML2
# set(libxml2_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
# find_package(libxml2)
# FIND POPT
if (NOT WIN32)
set(popt_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(popt)
endif()
# FIND LIBEVENT
set(event_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(event)
# FIND SWIFTEN
set(Swiften_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(Swiften)
if(NOT SWIFTEN_FOUND)
if (ZLIB_LIBRARY)
set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} ${ZLIB_LIBRARY})
endif()
if (EXPAT_LIBRARY)
set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} ${EXPAT_LIBRARY})
endif()
if (LIBIDN_LIBRARY)
set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} ${LIBIDN_LIBRARY})
endif()
if (LIBXML_LIBRARY)
set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} ${LIBXML_LIBRARY})
endif()
set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} "Dnsapi")
set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} "Crypt32")
set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} "Secur32")
set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} "Iphlpapi")
set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} "Winscard")
message(STATUS "Using swiften: ${SWIFTEN_INCLUDE_DIR} ${SWIFTEN_LIBRARY}")
endif()
if (WIN32)
add_definitions(-DSWIFTEN_STATIC=1)
ADD_DEFINITIONS(-D_UNICODE)
ADD_DEFINITIONS(-DUNICODE)
endif()
if (CMAKE_COMPILER_IS_GNUCXX)
set(openssl_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(openssl)
endif()
# FIND BOOST
set(Boost_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
if (WIN32)
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
endif()
find_package(Boost COMPONENTS program_options date_time system filesystem regex signals REQUIRED)
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost COMPONENTS program_options date_time system filesystem regex thread signals REQUIRED)
else(WIN32)
find_package(Boost COMPONENTS program_options date_time system filesystem regex thread signals REQUIRED)
endif(WIN32)
message( STATUS "Found Boost: ${Boost_LIBRARIES}, ${Boost_INCLUDE_DIR}")
set(Protobuf_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(Protobuf REQUIRED)
find_package(Protobuf)
# FIND PROTOBUF
if (NOT PROTOBUF_FOUND AND PROTOBUF_INCLUDE_DIR AND PROTOBUF_LIBRARY)
set(PROTOBUF_FOUND 1)
set(PROTOBUF_INCLUDE_DIRS ${PROTOBUF_INCLUDE_DIR})
if (PROTOBUF_PROTOC_EXECUTABLE)
else()
set(PROTOBUF_PROTOC_EXECUTABLE protoc)
endif()
message(STATUS "Using protobuf: ${PROTOBUF_INCLUDE_DIRS} ${PROTOBUF_LIBRARY}")
endif()
set(Communi_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(Communi)
set(log4cxx_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(log4cxx)
if(LOG4CXX_INCLUDE_DIR AND LOG4CXX_LIBRARY)
set(LOG4CXX_LIBRARIES ${LOG4CXX_LIBRARY})
set(LOG4CXX_FOUND 1)
message(STATUS "Using log4cxx: ${CPPUNIT_INCLUDE_DIR} ${LOG4CXX_INCLUDE_DIR}")
else()
set(log4cxx_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(log4cxx)
endif()
set(event_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(event)
@ -60,8 +169,13 @@ find_package(event)
set(pqxx_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(pqxx)
if (NOT WIN32)
set(dbus_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(dbus)
endif()
set(yahoo2_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
find_package(yahoo2)
find_package(Doxygen)
@ -70,7 +184,7 @@ FIND_PACKAGE(Qt4 COMPONENTS QtCore QtNetwork)
# ADD_DEFINITIONS(${SWIFTEN_CFLAGS})
ADD_DEFINITIONS(-DSUPPORT_LEGACY_CAPS)
ADD_DEFINITIONS(-DBOOST_FILESYSTEM_VERSION=2)
# ADD_DEFINITIONS(-DBOOST_FILESYSTEM_VERSION=2)
message(" Supported features")
message("-----------------------")
@ -79,7 +193,10 @@ if (SPECTRUM_VERSION)
ADD_DEFINITIONS(-DSPECTRUM_VERSION="${SPECTRUM_VERSION}")
else (SPECTRUM_VERSION)
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)
execute_process(COMMAND git "--git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git" rev-parse --short HEAD
if (NOT GIT_EXECUTABLE)
set (GIT_EXECUTABLE git)
endif()
execute_process(COMMAND ${GIT_EXECUTABLE} "--git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git" rev-parse --short HEAD
OUTPUT_VARIABLE GIT_REVISION
OUTPUT_STRIP_TRAILING_WHITESPACE
)
@ -98,8 +215,14 @@ if (SQLITE3_FOUND)
include_directories(${SQLITE3_INCLUDE_DIR})
message("SQLite3 : yes")
else (SQLITE3_FOUND)
if (WIN32)
ADD_DEFINITIONS(-DWITH_SQLITE)
include_directories(msvc-deps/sqlite3)
message("SQLite3 : bundled")
else()
set(SQLITE3_LIBRARIES "")
message("SQLite3 : no")
endif()
endif (SQLITE3_FOUND)
if (MYSQL_FOUND)
@ -126,7 +249,7 @@ if (PROTOBUF_FOUND)
include_directories(${PROTOBUF_INCLUDE_DIRS})
message("Network plugins : yes")
if(PURPLE_LIBRARY AND PURPLE_INCLUDE_DIR)
if(PURPLE_FOUND)
message("Libpurple plugin : yes")
include_directories(${PURPLE_INCLUDE_DIR})
include_directories(${GLIB2_INCLUDE_DIR})
@ -152,15 +275,31 @@ if (PROTOBUF_FOUND)
message("IRC plugin : no (install libCommuni and libprotobuf-dev)")
endif()
if (NOT WIN32)
message("Frotz plugin : yes")
message("SMSTools3 plugin : yes")
if(${LIBDBUSGLIB_FOUND})
message("Skype plugin : yes")
include_directories(${LIBDBUSGLIB_INCLUDE_DIRS})
else()
message("Skype plugin : no (install dbus-glib-devel)")
endif()
else()
message("Frotz plugin : no")
message("SMSTools3 plugin : no")
message("Skype plugin : no")
endif()
# We have our own copy now...
# if(YAHOO2_FOUND)
message("Libyahoo2 plugin : yes")
# include_directories(${YAHOO2_INCLUDE_DIR})
# else()
# message("Libyahoo2 plugin : no (install libyahoo2-devel)")
# endif()
message("Swiften plugin : yes")
message("Twitter plugin : yes")
else()
message("Network plugins : no (install libprotobuf-dev)")
@ -168,6 +307,8 @@ else()
message("IRC plugin : no (install libircclient-qt and libprotobuf-dev)")
message("Frotz plugin : no (install libprotobuf-dev)")
message("SMSTools3 plugin : no (install libprotobuf-dev)")
message("Swiften plugin : no (install libprotobuf-dev)")
message("Twitter plugin : no (install libprotobuf-dev)")
endif()
if (LOG4CXX_FOUND)
@ -180,25 +321,17 @@ else()
endif()
if (WIN32)
ADD_DEFINITIONS(-DLOG4CXX_STATIC)
ADD_DEFINITIONS(-D_WIN32_WINNT=0x501)
ADD_DEFINITIONS(-DWIN32_LEAN_AND_MEAN)
ADD_DEFINITIONS(-DBOOST_USE_WINDOWS_H)
ADD_DEFINITIONS(-DBOOST_THREAD_USE_LIB)
endif()
if(CMAKE_BUILD_TYPE MATCHES Debug)
if (CMAKE_COMPILER_IS_GNUCXX)
ADD_DEFINITIONS(-O3)
ADD_DEFINITIONS(-O0)
ADD_DEFINITIONS(-ggdb)
ADD_DEFINITIONS(-Wall)
ADD_DEFINITIONS(-W)
ADD_DEFINITIONS(-Wcast-align)
ADD_DEFINITIONS(-Wextra -Wno-sign-compare -Wno-unused-parameter)
ADD_DEFINITIONS(-Winit-self)
ADD_DEFINITIONS(-Wmissing-declarations)
ADD_DEFINITIONS(-Wpointer-arith)
ADD_DEFINITIONS(-Wreorder)
ADD_DEFINITIONS(-Woverloaded-virtual)
ADD_DEFINITIONS(-Wsign-promo)
ADD_DEFINITIONS(-Wundef -Wunused)
endif()
ADD_DEFINITIONS(-DDEBUG)
message("Debug : yes")
@ -215,7 +348,10 @@ include_directories(include)
include_directories(${EVENT_INCLUDE_DIRS})
include_directories(${SWIFTEN_INCLUDE_DIR})
include_directories(${Boost_INCLUDE_DIRS})
if (CMAKE_COMPILER_IS_GNUCXX)
include_directories(${OPENSSL_INCLUDE_DIR})
endif()
ADD_SUBDIRECTORY(src)
ADD_SUBDIRECTORY(plugin)

View file

@ -13,13 +13,42 @@ Version 2.0.0-beta3 (2012-XX-XX):
* Added Munin plugin (Thanks to Askovpen).
* Added support for more admin_jid JIDs (Thanks to Askovpen).
* Fixed allowed_servers option.
* Show error in server-mode when server port is already used.
* Fixed bug when backend could freeze on exit.
* Options from config file can now be set also using command line like
--service.jid=domain.tld .
* Do not send password in IQ-get registration response.
* Added support for AdHoc commands.
* Do not store buddies with empty name in database.
* Improved MySQL storage backend performance.
* Do not handle error messages as normal ones.
* Added Munin script for Spectrum 2.
* Use utf-8 encoding as default for MySQL.
* Added a way to disable xhtml-im.
* Fix crash caused by two XMPP users using single PurpleAccount instance.
* Support for [registration] allowed_usernames.
* Fixed compilation with boost-1.50.
Spectrum2_manager:
* Rewritten to provide more features. Check the documentation.
Libpurple:
* prpl-gg: Fetch the contact list properly (#252).
* Added support for prpl-novell as it was in spectrum1.
Twitter:
* Added Twitter support using Twitter backend. Thanks to Sarang and
Google Summer of Code.
Skype:
* Log more errors.
Libyahoo2:
* Added new Yahoo backend based on libyahoo2.
Swiften:
* Added new XMPP backend based on Swiften library.
Backend API:
* Added Python NetworkPlugin class, so it is now easier to write backends
in Python (Thanks to Sarang).

66
README.win32 Normal file
View file

@ -0,0 +1,66 @@
Prerequisites
=============
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)
3. CMake 2.8 or newer (http://www.cmake.org/cmake/resources/software.html)
Libraries
=========
3. Swiften library and Python for run scons (http://swift.im/git/swift)
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)
Environment
===========
To create spectrum build environment do:
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%.
Assuming you have git, python and cmake in %PATH%,
launch "Visual Studio 2010 command prompt" or
"Visual Studio 2010(x64) command prompt", depends on your target (Windows x86 or Windows x86_64).
1. unpack and build boost libraries:
bootstrap.bat
b2.exe --without-mpi --without-python
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:
git clone git://swift.im/swift
cd swift
echo boost_includedir="c:/env-msvc-x64/include/boost-1_49" > 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 C:\env-msvc-x64
TODO: fix in upstream
You may need manually copy compiled 3rdParty libs to C:\env-msvc-x64\lib\3rdParty\Expat,
C:\env-msvc-x64\lib\3rdParty\LibIDN, C:\env-msvc-x64\lib\3rdParty\Zlib
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
Move protoc.exe to C:\env-msvc-x64\bin\ and libprotobuf.lib to C:\env-msvc-x64\lib
4. Install gtkmm
Download installer from https://live.gnome.org/gtkmm/MSWindows and install gtkmm into C:\env-msvc-x64\
5. Install libpurple headers
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)
Compile it as:
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=Release -DCMAKE_INSTALL_PREFIX=C:\env-msvc-x64 -DGIT_EXECUTABLE="c:\Program Files (x86)\git\bin\git.exe"
nmake
TODO: libpurple_backend compilation

View file

@ -1,5 +1,5 @@
if (PROTOBUF_FOUND)
if ( PURPLE_LIBRARY AND PURPLE_INCLUDE_DIR )
if (PURPLE_FOUND)
ADD_SUBDIRECTORY(libpurple)
endif()
@ -7,12 +7,18 @@ if (PROTOBUF_FOUND)
ADD_SUBDIRECTORY(libcommuni)
endif()
ADD_SUBDIRECTORY(smstools3)
ADD_SUBDIRECTORY(swiften)
ADD_SUBDIRECTORY(template)
if (NOT WIN32)
ADD_SUBDIRECTORY(smstools3)
ADD_SUBDIRECTORY(frotz)
# if(YAHOO2_FOUND)
ADD_SUBDIRECTORY(libyahoo2)
# endif()
ADD_SUBDIRECTORY(twitter)
if (${LIBDBUSGLIB_FOUND})
ADD_SUBDIRECTORY(skype)
endif()

View file

@ -235,7 +235,11 @@ class FrotzNetworkPlugin : public NetworkPlugin {
directory_iterator end_itr;
for (directory_iterator itr(p); itr != end_itr; ++itr) {
if (extension(itr->path()) == ".z5") {
#if BOOST_FILESYSTEM_VERSION == 3
games.push_back(itr->path().filename().string());
#else
games.push_back(itr->path().leaf());
#endif
}
}
return games;
@ -335,54 +339,19 @@ int main (int argc, char* argv[]) {
return -1;
}
boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <config_file.cfg>\nAllowed options");
desc.add_options()
("host,h", value<std::string>(&host), "host")
("port,p", value<int>(&port), "port")
;
try
{
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
}
catch (std::runtime_error& e)
{
std::cout << desc << "\n";
exit(1);
}
catch (...)
{
std::cout << desc << "\n";
exit(1);
}
if (argc < 5) {
return 1;
}
// QStringList channels;
// for (int i = 3; i < argc; ++i)
// {
// channels.append(argv[i]);
// }
//
// MyIrcSession session;
// session.setNick(argv[2]);
// session.setAutoJoinChannels(channels);
// session.connectToServer(argv[1], 6667);
Config config;
if (!config.load(argv[5])) {
std::cerr << "Can't open " << argv[1] << " configuration file.\n";
std::string error;
Config *cfg = Config::createFromArgs(argc, argv, error, host, port);
if (cfg == NULL) {
std::cerr << error;
return 1;
}
Swift::SimpleEventLoop eventLoop;
loop_ = &eventLoop;
np = new FrotzNetworkPlugin(&config, &eventLoop, host, port);
np = new FrotzNetworkPlugin(cfg, &eventLoop, host, port);
loop_->run();
delete cfg;
return 0;
}

View file

@ -27,62 +27,24 @@ int main (int argc, char* argv[]) {
std::string host;
int port;
boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <config_file.cfg>\nAllowed options");
desc.add_options()
("host,h", value<std::string>(&host), "host")
("port,p", value<int>(&port), "port")
;
try
{
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
}
catch (std::runtime_error& e)
{
std::cout << desc << "\n";
exit(1);
}
catch (...)
{
std::cout << desc << "\n";
exit(1);
}
if (argc < 5) {
qDebug("Usage: %s <config>", argv[0]);
std::string error;
Config *cfg = Config::createFromArgs(argc, argv, error, host, port);
if (cfg == NULL) {
std::cerr << error;
return 1;
}
// QStringList channels;
// for (int i = 3; i < argc; ++i)
// {
// channels.append(argv[i]);
// }
//
// MyIrcSession session;
// session.setNick(argv[2]);
// session.setAutoJoinChannels(channels);
// session.connectToServer(argv[1], 6667);
Config config;
if (!config.load(argv[5])) {
std::cerr << "Can't open " << argv[1] << " configuration file.\n";
return 1;
}
QCoreApplication app(argc, argv);
Logging::initBackendLogging(&config);
Logging::initBackendLogging(cfg);
Swift::QtEventLoop eventLoop;
if (config.getUnregistered().find("service.irc_server") == config.getUnregistered().end()) {
np = new IRCNetworkPlugin(&config, &eventLoop, host, port);
if (!CONFIG_HAS_KEY(cfg, "service.irc_server")) {
np = new IRCNetworkPlugin(cfg, &eventLoop, host, port);
}
else {
np = new SingleIRCNetworkPlugin(&config, &eventLoop, host, port);
np = new SingleIRCNetworkPlugin(cfg, &eventLoop, host, port);
}
return app.exec();

View file

@ -142,6 +142,13 @@ void MyIrcSession::on_topicChanged(IrcMessage *message) {
void MyIrcSession::on_messageReceived(IrcMessage *message) {
IrcPrivateMessage *m = (IrcPrivateMessage *) message;
if (m->isRequest()) {
QString request = m->message().split(" ", QString::SkipEmptyParts).value(0).toUpper();
if (request == "PING" || request == "TIME" || request == "VERSION") {
LOG4CXX_INFO(logger, user << ": " << TO_UTF8(request) << " received and has been answered");
return;
}
}
std::string target = TO_UTF8(m->target());
LOG4CXX_INFO(logger, user << ": Message from " << target);

View file

@ -10,13 +10,19 @@ DEFINE_LOGGER(logger, "SingleIRCNetworkPlugin");
SingleIRCNetworkPlugin::SingleIRCNetworkPlugin(Config *config, Swift::QtEventLoop *loop, const std::string &host, int port) {
this->config = config;
m_server = config->getUnregistered().find("service.irc_server")->second;
if (CONFIG_HAS_KEY(config, "service.irc_server")) {
m_server = CONFIG_STRING(config, "service.irc_server");
}
else {
LOG4CXX_ERROR(logger, "No [service] irc_server defined, exiting...");
exit(-1);
}
m_socket = new QTcpSocket();
m_socket->connectToHost(FROM_UTF8(host), port);
connect(m_socket, SIGNAL(readyRead()), this, SLOT(readData()));
if (config->getUnregistered().find("service.irc_identify") != config->getUnregistered().end()) {
m_identify = config->getUnregistered().find("service.irc_identify")->second;
if (CONFIG_HAS_KEY(config, "service.irc_identify")) {
m_identify = CONFIG_STRING(config, "service.irc_identify");
}
else {
m_identify = "NickServ identify $name $password";
@ -52,6 +58,7 @@ void SingleIRCNetworkPlugin::handleLoginRequest(const std::string &user, const s
session->setRealName(FROM_UTF8(legacyName));
session->setHost(FROM_UTF8(m_server));
session->setPort(6667);
session->setEncoding( "utf-8" );
if (!password.empty()) {
std::string identify = m_identify;

View file

@ -3,10 +3,14 @@ FILE(GLOB SRC *.cpp)
ADD_EXECUTABLE(spectrum2_libpurple_backend ${SRC})
if(NOT WIN32)
target_link_libraries(spectrum2_libpurple_backend ${PURPLE_LIBRARY} ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport-plugin pthread)
if(CMAKE_COMPILER_IS_GNUCXX)
if (NOT WIN32)
target_link_libraries(spectrum2_libpurple_backend ${PURPLE_LIBRARY} ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport-plugin pthread)
else()
target_link_libraries(spectrum2_libpurple_backend ${PURPLE_LIBRARY} ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport-plugin)
endif()
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} ${LIBXML2_LIBRARIES} ${EVENT_LIBRARIES} transport-plugin ${PROTOBUF_LIBRARY})
endif()
INSTALL(TARGETS spectrum2_libpurple_backend RUNTIME DESTINATION bin)

View file

@ -132,7 +132,7 @@ def output():
header = open("purple_defs.h", "w")
print >> header, "#pragma once"
print >> header, "#ifdef WIN32"
print >> header, "#if PURPLE_RUNTIME"
print >> header, """
#include <Windows.h>
@ -186,7 +186,7 @@ def output():
cpp = open("purple_defs.cpp", "w")
print >> cpp, "#include \"purple_defs.h\""
print >> cpp, ""
print >> cpp, "#ifdef WIN32"
print >> cpp, "#if PURPLE_RUNTIME"
print >> cpp, "static HMODULE f_hPurple = NULL;"
for d in definitions:
#purple_util_set_user_wrapped_fnc purple_util_set_user_wrapped = NULL;
@ -195,8 +195,8 @@ def output():
print >> cpp, "#endif"
print >> cpp, "bool resolvePurpleFunctions() {"
print >> cpp, "#ifdef WIN32"
print >> cpp, "\tf_hPurple = LoadLibrary(\"libpurple.dll\");"
print >> cpp, "#if PURPLE_RUNTIME"
print >> cpp, "\tf_hPurple = LoadLibrary(L\"libpurple.dll\");"
print >> cpp, "\tif (!f_hPurple)"
print >> cpp, "\t\t\treturn false;"
for d in definitions:

View file

@ -98,7 +98,7 @@ static guint input_add(gint fd,
}
#ifdef WIN32
channel = wpurple_g_io_channel_win32_new_socket(fd);
channel = wpurple_g_io_channel_win32_new_socket_wrapped(fd);
#else
channel = g_io_channel_unix_new(fd);
#endif

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,704 @@
#include "purple_defs.h"
bool resolvePurpleFunctions() {
#include "utils.h"
#if PURPLE_RUNTIME
using std::string;
using std::wstring;
static HMODULE f_hPurple = NULL;
purple_debug_set_ui_ops_wrapped_fnc purple_debug_set_ui_ops_wrapped = NULL;
purple_debug_set_verbose_wrapped_fnc purple_debug_set_verbose_wrapped = NULL;
purple_request_set_ui_ops_wrapped_fnc purple_request_set_ui_ops_wrapped = NULL;
purple_imgstore_get_data_wrapped_fnc purple_imgstore_get_data_wrapped = NULL;
purple_imgstore_get_size_wrapped_fnc purple_imgstore_get_size_wrapped = NULL;
purple_imgstore_unref_wrapped_fnc purple_imgstore_unref_wrapped = NULL;
purple_markup_escape_text_wrapped_fnc purple_markup_escape_text_wrapped = NULL;
purple_markup_strip_html_wrapped_fnc purple_markup_strip_html_wrapped = NULL;
purple_normalize_wrapped_fnc purple_normalize_wrapped = NULL;
purple_strdup_withhtml_wrapped_fnc purple_strdup_withhtml_wrapped = NULL;
purple_markup_html_to_xhtml_wrapped_fnc purple_markup_html_to_xhtml_wrapped = NULL;
purple_utf8_try_convert_wrapped_fnc purple_utf8_try_convert_wrapped = NULL;
purple_util_set_user_dir_wrapped_fnc purple_util_set_user_dir_wrapped = NULL;
purple_blist_node_get_type_wrapped_fnc purple_blist_node_get_type_wrapped = NULL;
purple_buddy_get_alias_wrapped_fnc purple_buddy_get_alias_wrapped = NULL;
purple_buddy_get_server_alias_wrapped_fnc purple_buddy_get_server_alias_wrapped = NULL;
purple_find_buddy_wrapped_fnc purple_find_buddy_wrapped = NULL;
purple_buddy_get_group_wrapped_fnc purple_buddy_get_group_wrapped = NULL;
purple_blist_remove_buddy_wrapped_fnc purple_blist_remove_buddy_wrapped = NULL;
purple_blist_alias_buddy_wrapped_fnc purple_blist_alias_buddy_wrapped = NULL;
purple_blist_server_alias_buddy_wrapped_fnc purple_blist_server_alias_buddy_wrapped = NULL;
purple_find_group_wrapped_fnc purple_find_group_wrapped = NULL;
purple_group_new_wrapped_fnc purple_group_new_wrapped = NULL;
purple_blist_add_contact_wrapped_fnc purple_blist_add_contact_wrapped = NULL;
purple_buddy_get_contact_wrapped_fnc purple_buddy_get_contact_wrapped = NULL;
purple_buddy_new_wrapped_fnc purple_buddy_new_wrapped = NULL;
purple_blist_add_buddy_wrapped_fnc purple_blist_add_buddy_wrapped = NULL;
purple_blist_find_chat_wrapped_fnc purple_blist_find_chat_wrapped = NULL;
purple_chat_get_components_wrapped_fnc purple_chat_get_components_wrapped = NULL;
purple_buddy_get_presence_wrapped_fnc purple_buddy_get_presence_wrapped = NULL;
purple_buddy_get_account_wrapped_fnc purple_buddy_get_account_wrapped = NULL;
purple_buddy_get_name_wrapped_fnc purple_buddy_get_name_wrapped = NULL;
purple_find_buddies_wrapped_fnc purple_find_buddies_wrapped = NULL;
purple_group_get_name_wrapped_fnc purple_group_get_name_wrapped = NULL;
purple_blist_set_ui_ops_wrapped_fnc purple_blist_set_ui_ops_wrapped = NULL;
purple_set_blist_wrapped_fnc purple_set_blist_wrapped = NULL;
purple_blist_new_wrapped_fnc purple_blist_new_wrapped = NULL;
purple_blist_load_wrapped_fnc purple_blist_load_wrapped = NULL;
purple_blist_get_handle_wrapped_fnc purple_blist_get_handle_wrapped = NULL;
purple_xfer_ui_ready_wrapped_fnc purple_xfer_ui_ready_wrapped = NULL;
purple_xfer_request_accepted_wrapped_fnc purple_xfer_request_accepted_wrapped = NULL;
purple_xfer_request_denied_wrapped_fnc purple_xfer_request_denied_wrapped = NULL;
purple_certificate_add_ca_search_path_wrapped_fnc purple_certificate_add_ca_search_path_wrapped = NULL;
purple_xfer_get_account_wrapped_fnc purple_xfer_get_account_wrapped = NULL;
purple_xfer_get_filename_wrapped_fnc purple_xfer_get_filename_wrapped = NULL;
purple_xfer_get_size_wrapped_fnc purple_xfer_get_size_wrapped = NULL;
purple_xfer_unref_wrapped_fnc purple_xfer_unref_wrapped = NULL;
purple_xfer_ref_wrapped_fnc purple_xfer_ref_wrapped = NULL;
purple_xfers_set_ui_ops_wrapped_fnc purple_xfers_set_ui_ops_wrapped = NULL;
purple_xfers_get_handle_wrapped_fnc purple_xfers_get_handle_wrapped = NULL;
purple_signal_connect_wrapped_fnc purple_signal_connect_wrapped = NULL;
purple_prefs_load_wrapped_fnc purple_prefs_load_wrapped = NULL;
purple_prefs_set_bool_wrapped_fnc purple_prefs_set_bool_wrapped = NULL;
purple_prefs_set_string_wrapped_fnc purple_prefs_set_string_wrapped = NULL;
purple_notify_user_info_new_wrapped_fnc purple_notify_user_info_new_wrapped = NULL;
purple_notify_user_info_destroy_wrapped_fnc purple_notify_user_info_destroy_wrapped = NULL;
purple_notify_user_info_get_entries_wrapped_fnc purple_notify_user_info_get_entries_wrapped = NULL;
purple_notify_user_info_entry_get_label_wrapped_fnc purple_notify_user_info_entry_get_label_wrapped = NULL;
purple_notify_user_info_entry_get_value_wrapped_fnc purple_notify_user_info_entry_get_value_wrapped = NULL;
purple_notify_set_ui_ops_wrapped_fnc purple_notify_set_ui_ops_wrapped = NULL;
purple_buddy_icons_set_account_icon_wrapped_fnc purple_buddy_icons_set_account_icon_wrapped = NULL;
purple_buddy_icons_find_wrapped_fnc purple_buddy_icons_find_wrapped = NULL;
purple_buddy_icon_get_full_path_wrapped_fnc purple_buddy_icon_get_full_path_wrapped = NULL;
purple_buddy_icon_unref_wrapped_fnc purple_buddy_icon_unref_wrapped = NULL;
purple_buddy_icons_find_account_icon_wrapped_fnc purple_buddy_icons_find_account_icon_wrapped = NULL;
purple_buddy_icon_get_data_wrapped_fnc purple_buddy_icon_get_data_wrapped = NULL;
purple_account_set_bool_wrapped_fnc purple_account_set_bool_wrapped = NULL;
purple_account_get_protocol_id_wrapped_fnc purple_account_get_protocol_id_wrapped = NULL;
purple_account_set_int_wrapped_fnc purple_account_set_int_wrapped = NULL;
purple_account_set_string_wrapped_fnc purple_account_set_string_wrapped = NULL;
purple_account_get_username_wrapped_fnc purple_account_get_username_wrapped = NULL;
purple_account_set_username_wrapped_fnc purple_account_set_username_wrapped = NULL;
purple_accounts_find_wrapped_fnc purple_accounts_find_wrapped = NULL;
purple_account_new_wrapped_fnc purple_account_new_wrapped = NULL;
purple_accounts_add_wrapped_fnc purple_accounts_add_wrapped = NULL;
purple_account_set_password_wrapped_fnc purple_account_set_password_wrapped = NULL;
purple_account_set_enabled_wrapped_fnc purple_account_set_enabled_wrapped = NULL;
purple_account_set_privacy_type_wrapped_fnc purple_account_set_privacy_type_wrapped = NULL;
purple_account_get_status_type_with_primitive_wrapped_fnc purple_account_get_status_type_with_primitive_wrapped = NULL;
purple_account_set_status_wrapped_fnc purple_account_set_status_wrapped = NULL;
purple_account_get_int_wrapped_fnc purple_account_get_int_wrapped = NULL;
purple_account_disconnect_wrapped_fnc purple_account_disconnect_wrapped = NULL;
purple_accounts_delete_wrapped_fnc purple_accounts_delete_wrapped = NULL;
purple_account_get_connection_wrapped_fnc purple_account_get_connection_wrapped = NULL;
purple_account_set_alias_wrapped_fnc purple_account_set_alias_wrapped = NULL;
purple_account_set_public_alias_wrapped_fnc purple_account_set_public_alias_wrapped = NULL;
purple_account_remove_buddy_wrapped_fnc purple_account_remove_buddy_wrapped = NULL;
purple_account_add_buddy_wrapped_fnc purple_account_add_buddy_wrapped = NULL;
purple_account_get_name_for_display_wrapped_fnc purple_account_get_name_for_display_wrapped = NULL;
purple_accounts_set_ui_ops_wrapped_fnc purple_accounts_set_ui_ops_wrapped = NULL;
purple_status_type_get_id_wrapped_fnc purple_status_type_get_id_wrapped = NULL;
purple_presence_get_active_status_wrapped_fnc purple_presence_get_active_status_wrapped = NULL;
purple_status_type_get_primitive_wrapped_fnc purple_status_type_get_primitive_wrapped = NULL;
purple_status_get_type_wrapped_fnc purple_status_get_type_wrapped = NULL;
purple_status_get_attr_string_wrapped_fnc purple_status_get_attr_string_wrapped = NULL;
serv_get_info_wrapped_fnc serv_get_info_wrapped = NULL;
serv_alias_buddy_wrapped_fnc serv_alias_buddy_wrapped = NULL;
serv_send_typing_wrapped_fnc serv_send_typing_wrapped = NULL;
serv_join_chat_wrapped_fnc serv_join_chat_wrapped = NULL;
purple_dnsquery_set_ui_ops_wrapped_fnc purple_dnsquery_set_ui_ops_wrapped = NULL;
purple_conversation_get_im_data_wrapped_fnc purple_conversation_get_im_data_wrapped = NULL;
purple_conversation_get_chat_data_wrapped_fnc purple_conversation_get_chat_data_wrapped = NULL;
purple_find_conversation_with_account_wrapped_fnc purple_find_conversation_with_account_wrapped = NULL;
purple_conversation_new_wrapped_fnc purple_conversation_new_wrapped = NULL;
purple_conversation_get_type_wrapped_fnc purple_conversation_get_type_wrapped = NULL;
purple_conv_im_send_wrapped_fnc purple_conv_im_send_wrapped = NULL;
purple_conv_chat_send_wrapped_fnc purple_conv_chat_send_wrapped = NULL;
purple_conversation_destroy_wrapped_fnc purple_conversation_destroy_wrapped = NULL;
purple_conversation_get_account_wrapped_fnc purple_conversation_get_account_wrapped = NULL;
purple_conversation_get_name_wrapped_fnc purple_conversation_get_name_wrapped = NULL;
purple_conversations_set_ui_ops_wrapped_fnc purple_conversations_set_ui_ops_wrapped = NULL;
purple_conversations_get_handle_wrapped_fnc purple_conversations_get_handle_wrapped = NULL;
purple_plugin_action_free_wrapped_fnc purple_plugin_action_free_wrapped = NULL;
purple_plugins_add_search_path_wrapped_fnc purple_plugins_add_search_path_wrapped = NULL;
purple_connection_get_state_wrapped_fnc purple_connection_get_state_wrapped = NULL;
purple_connection_get_account_wrapped_fnc purple_connection_get_account_wrapped = NULL;
purple_connection_get_display_name_wrapped_fnc purple_connection_get_display_name_wrapped = NULL;
purple_connections_set_ui_ops_wrapped_fnc purple_connections_set_ui_ops_wrapped = NULL;
purple_connections_get_handle_wrapped_fnc purple_connections_get_handle_wrapped = NULL;
purple_core_set_ui_ops_wrapped_fnc purple_core_set_ui_ops_wrapped = NULL;
purple_core_init_wrapped_fnc purple_core_init_wrapped = NULL;
purple_input_add_wrapped_fnc purple_input_add_wrapped = NULL;
purple_timeout_add_wrapped_fnc purple_timeout_add_wrapped = NULL;
purple_timeout_add_seconds_wrapped_fnc purple_timeout_add_seconds_wrapped = NULL;
purple_timeout_remove_wrapped_fnc purple_timeout_remove_wrapped = NULL;
purple_eventloop_set_ui_ops_wrapped_fnc purple_eventloop_set_ui_ops_wrapped = NULL;
purple_input_remove_wrapped_fnc purple_input_remove_wrapped = NULL;
purple_privacy_deny_wrapped_fnc purple_privacy_deny_wrapped = NULL;
purple_privacy_allow_wrapped_fnc purple_privacy_allow_wrapped = NULL;
purple_privacy_check_wrapped_fnc purple_privacy_check_wrapped = NULL;
purple_find_prpl_wrapped_fnc purple_find_prpl_wrapped = NULL;
purple_prpl_send_attention_wrapped_fnc purple_prpl_send_attention_wrapped = NULL;
purple_account_option_get_type_wrapped_fnc purple_account_option_get_type_wrapped = NULL;
purple_account_option_get_setting_wrapped_fnc purple_account_option_get_setting_wrapped = NULL;
wpurple_g_io_channel_win32_new_socket_wrapped_fnc wpurple_g_io_channel_win32_new_socket_wrapped = NULL;
#endif
bool resolvePurpleFunctions(const std::string& libPurpleDllPath) {
#if PURPLE_RUNTIME
std::wstring dllPath;
if (!libPurpleDllPath.empty())
{
dllPath = utf8ToUtf16(libPurpleDllPath);
}
else
{
// No path was specified, so try loading libpurple from the current working directory
dllPath = L"libpurple.dll";
}
f_hPurple = LoadLibrary(dllPath.c_str());
if (!f_hPurple)
return false;
purple_debug_set_ui_ops_wrapped = (purple_debug_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_debug_set_ui_ops");
if (!purple_debug_set_ui_ops_wrapped)
return false;
purple_debug_set_verbose_wrapped = (purple_debug_set_verbose_wrapped_fnc)GetProcAddress(f_hPurple, "purple_debug_set_verbose");
if (!purple_debug_set_verbose_wrapped)
return false;
purple_request_set_ui_ops_wrapped = (purple_request_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_request_set_ui_ops");
if (!purple_request_set_ui_ops_wrapped)
return false;
purple_imgstore_get_data_wrapped = (purple_imgstore_get_data_wrapped_fnc)GetProcAddress(f_hPurple, "purple_imgstore_get_data");
if (!purple_imgstore_get_data_wrapped)
return false;
purple_imgstore_get_size_wrapped = (purple_imgstore_get_size_wrapped_fnc)GetProcAddress(f_hPurple, "purple_imgstore_get_size");
if (!purple_imgstore_get_size_wrapped)
return false;
purple_imgstore_unref_wrapped = (purple_imgstore_unref_wrapped_fnc)GetProcAddress(f_hPurple, "purple_imgstore_unref");
if (!purple_imgstore_unref_wrapped)
return false;
purple_markup_escape_text_wrapped = (purple_markup_escape_text_wrapped_fnc)GetProcAddress(f_hPurple, "purple_markup_escape_text");
if (!purple_markup_escape_text_wrapped)
return false;
purple_markup_strip_html_wrapped = (purple_markup_strip_html_wrapped_fnc)GetProcAddress(f_hPurple, "purple_markup_strip_html");
if (!purple_markup_strip_html_wrapped)
return false;
purple_normalize_wrapped = (purple_normalize_wrapped_fnc)GetProcAddress(f_hPurple, "purple_normalize");
if (!purple_normalize_wrapped)
return false;
purple_strdup_withhtml_wrapped = (purple_strdup_withhtml_wrapped_fnc)GetProcAddress(f_hPurple, "purple_strdup_withhtml");
if (!purple_strdup_withhtml_wrapped)
return false;
purple_markup_html_to_xhtml_wrapped = (purple_markup_html_to_xhtml_wrapped_fnc)GetProcAddress(f_hPurple, "purple_markup_html_to_xhtml");
if (!purple_markup_html_to_xhtml_wrapped)
return false;
purple_utf8_try_convert_wrapped = (purple_utf8_try_convert_wrapped_fnc)GetProcAddress(f_hPurple, "purple_utf8_try_convert");
if (!purple_utf8_try_convert_wrapped)
return false;
purple_util_set_user_dir_wrapped = (purple_util_set_user_dir_wrapped_fnc)GetProcAddress(f_hPurple, "purple_util_set_user_dir");
if (!purple_util_set_user_dir_wrapped)
return false;
purple_certificate_add_ca_search_path_wrapped = (purple_util_set_user_dir_wrapped_fnc)GetProcAddress(f_hPurple, "purple_certificate_add_ca_search_path");
if (!purple_certificate_add_ca_search_path_wrapped)
return false;
purple_blist_node_get_type_wrapped = (purple_blist_node_get_type_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_node_get_type");
if (!purple_blist_node_get_type_wrapped)
return false;
purple_buddy_get_alias_wrapped = (purple_buddy_get_alias_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_get_alias");
if (!purple_buddy_get_alias_wrapped)
return false;
purple_buddy_get_server_alias_wrapped = (purple_buddy_get_server_alias_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_get_server_alias");
if (!purple_buddy_get_server_alias_wrapped)
return false;
purple_find_buddy_wrapped = (purple_find_buddy_wrapped_fnc)GetProcAddress(f_hPurple, "purple_find_buddy");
if (!purple_find_buddy_wrapped)
return false;
purple_buddy_get_group_wrapped = (purple_buddy_get_group_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_get_group");
if (!purple_buddy_get_group_wrapped)
return false;
purple_blist_remove_buddy_wrapped = (purple_blist_remove_buddy_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_remove_buddy");
if (!purple_blist_remove_buddy_wrapped)
return false;
purple_blist_alias_buddy_wrapped = (purple_blist_alias_buddy_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_alias_buddy");
if (!purple_blist_alias_buddy_wrapped)
return false;
purple_blist_server_alias_buddy_wrapped = (purple_blist_server_alias_buddy_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_server_alias_buddy");
if (!purple_blist_server_alias_buddy_wrapped)
return false;
purple_find_group_wrapped = (purple_find_group_wrapped_fnc)GetProcAddress(f_hPurple, "purple_find_group");
if (!purple_find_group_wrapped)
return false;
purple_group_new_wrapped = (purple_group_new_wrapped_fnc)GetProcAddress(f_hPurple, "purple_group_new");
if (!purple_group_new_wrapped)
return false;
purple_blist_add_contact_wrapped = (purple_blist_add_contact_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_add_contact");
if (!purple_blist_add_contact_wrapped)
return false;
purple_buddy_get_contact_wrapped = (purple_buddy_get_contact_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_get_contact");
if (!purple_buddy_get_contact_wrapped)
return false;
purple_buddy_new_wrapped = (purple_buddy_new_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_new");
if (!purple_buddy_new_wrapped)
return false;
purple_blist_add_buddy_wrapped = (purple_blist_add_buddy_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_add_buddy");
if (!purple_blist_add_buddy_wrapped)
return false;
purple_blist_find_chat_wrapped = (purple_blist_find_chat_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_find_chat");
if (!purple_blist_find_chat_wrapped)
return false;
purple_chat_get_components_wrapped = (purple_chat_get_components_wrapped_fnc)GetProcAddress(f_hPurple, "purple_chat_get_components");
if (!purple_chat_get_components_wrapped)
return false;
purple_buddy_get_presence_wrapped = (purple_buddy_get_presence_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_get_presence");
if (!purple_buddy_get_presence_wrapped)
return false;
purple_buddy_get_account_wrapped = (purple_buddy_get_account_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_get_account");
if (!purple_buddy_get_account_wrapped)
return false;
purple_buddy_get_name_wrapped = (purple_buddy_get_name_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_get_name");
if (!purple_buddy_get_name_wrapped)
return false;
purple_find_buddies_wrapped = (purple_find_buddies_wrapped_fnc)GetProcAddress(f_hPurple, "purple_find_buddies");
if (!purple_find_buddies_wrapped)
return false;
purple_group_get_name_wrapped = (purple_group_get_name_wrapped_fnc)GetProcAddress(f_hPurple, "purple_group_get_name");
if (!purple_group_get_name_wrapped)
return false;
purple_blist_set_ui_ops_wrapped = (purple_blist_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_set_ui_ops");
if (!purple_blist_set_ui_ops_wrapped)
return false;
purple_set_blist_wrapped = (purple_set_blist_wrapped_fnc)GetProcAddress(f_hPurple, "purple_set_blist");
if (!purple_set_blist_wrapped)
return false;
purple_blist_new_wrapped = (purple_blist_new_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_new");
if (!purple_blist_new_wrapped)
return false;
purple_blist_load_wrapped = (purple_blist_load_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_load");
if (!purple_blist_load_wrapped)
return false;
purple_blist_get_handle_wrapped = (purple_blist_get_handle_wrapped_fnc)GetProcAddress(f_hPurple, "purple_blist_get_handle");
if (!purple_blist_get_handle_wrapped)
return false;
purple_xfer_ui_ready_wrapped = (purple_xfer_ui_ready_wrapped_fnc)GetProcAddress(f_hPurple, "purple_xfer_ui_ready");
if (!purple_xfer_ui_ready_wrapped)
return false;
purple_xfer_request_accepted_wrapped = (purple_xfer_request_accepted_wrapped_fnc)GetProcAddress(f_hPurple, "purple_xfer_request_accepted");
if (!purple_xfer_request_accepted_wrapped)
return false;
purple_xfer_request_denied_wrapped = (purple_xfer_request_denied_wrapped_fnc)GetProcAddress(f_hPurple, "purple_xfer_request_denied");
if (!purple_xfer_request_denied_wrapped)
return false;
purple_xfer_get_account_wrapped = (purple_xfer_get_account_wrapped_fnc)GetProcAddress(f_hPurple, "purple_xfer_get_account");
if (!purple_xfer_get_account_wrapped)
return false;
purple_xfer_get_filename_wrapped = (purple_xfer_get_filename_wrapped_fnc)GetProcAddress(f_hPurple, "purple_xfer_get_filename");
if (!purple_xfer_get_filename_wrapped)
return false;
purple_xfer_get_size_wrapped = (purple_xfer_get_size_wrapped_fnc)GetProcAddress(f_hPurple, "purple_xfer_get_size");
if (!purple_xfer_get_size_wrapped)
return false;
purple_xfer_unref_wrapped = (purple_xfer_unref_wrapped_fnc)GetProcAddress(f_hPurple, "purple_xfer_unref");
if (!purple_xfer_unref_wrapped)
return false;
purple_xfer_ref_wrapped = (purple_xfer_ref_wrapped_fnc)GetProcAddress(f_hPurple, "purple_xfer_ref");
if (!purple_xfer_ref_wrapped)
return false;
purple_xfers_set_ui_ops_wrapped = (purple_xfers_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_xfers_set_ui_ops");
if (!purple_xfers_set_ui_ops_wrapped)
return false;
purple_xfers_get_handle_wrapped = (purple_xfers_get_handle_wrapped_fnc)GetProcAddress(f_hPurple, "purple_xfers_get_handle");
if (!purple_xfers_get_handle_wrapped)
return false;
purple_signal_connect_wrapped = (purple_signal_connect_wrapped_fnc)GetProcAddress(f_hPurple, "purple_signal_connect");
if (!purple_signal_connect_wrapped)
return false;
purple_prefs_load_wrapped = (purple_prefs_load_wrapped_fnc)GetProcAddress(f_hPurple, "purple_prefs_load");
if (!purple_prefs_load_wrapped)
return false;
purple_prefs_set_bool_wrapped = (purple_prefs_set_bool_wrapped_fnc)GetProcAddress(f_hPurple, "purple_prefs_set_bool");
if (!purple_prefs_set_bool_wrapped)
return false;
purple_prefs_set_string_wrapped = (purple_prefs_set_string_wrapped_fnc)GetProcAddress(f_hPurple, "purple_prefs_set_string");
if (!purple_prefs_set_string_wrapped)
return false;
purple_notify_user_info_new_wrapped = (purple_notify_user_info_new_wrapped_fnc)GetProcAddress(f_hPurple, "purple_notify_user_info_new");
if (!purple_notify_user_info_new_wrapped)
return false;
purple_notify_user_info_destroy_wrapped = (purple_notify_user_info_destroy_wrapped_fnc)GetProcAddress(f_hPurple, "purple_notify_user_info_destroy");
if (!purple_notify_user_info_destroy_wrapped)
return false;
purple_notify_user_info_get_entries_wrapped = (purple_notify_user_info_get_entries_wrapped_fnc)GetProcAddress(f_hPurple, "purple_notify_user_info_get_entries");
if (!purple_notify_user_info_get_entries_wrapped)
return false;
purple_notify_user_info_entry_get_label_wrapped = (purple_notify_user_info_entry_get_label_wrapped_fnc)GetProcAddress(f_hPurple, "purple_notify_user_info_entry_get_label");
if (!purple_notify_user_info_entry_get_label_wrapped)
return false;
purple_notify_user_info_entry_get_value_wrapped = (purple_notify_user_info_entry_get_value_wrapped_fnc)GetProcAddress(f_hPurple, "purple_notify_user_info_entry_get_value");
if (!purple_notify_user_info_entry_get_value_wrapped)
return false;
purple_notify_set_ui_ops_wrapped = (purple_notify_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_notify_set_ui_ops");
if (!purple_notify_set_ui_ops_wrapped)
return false;
purple_buddy_icons_set_account_icon_wrapped = (purple_buddy_icons_set_account_icon_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_icons_set_account_icon");
if (!purple_buddy_icons_set_account_icon_wrapped)
return false;
purple_buddy_icons_find_wrapped = (purple_buddy_icons_find_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_icons_find");
if (!purple_buddy_icons_find_wrapped)
return false;
purple_buddy_icon_get_full_path_wrapped = (purple_buddy_icon_get_full_path_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_icon_get_full_path");
if (!purple_buddy_icon_get_full_path_wrapped)
return false;
purple_buddy_icon_unref_wrapped = (purple_buddy_icon_unref_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_icon_unref");
if (!purple_buddy_icon_unref_wrapped)
return false;
purple_buddy_icons_find_account_icon_wrapped = (purple_buddy_icons_find_account_icon_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_icons_find_account_icon");
if (!purple_buddy_icons_find_account_icon_wrapped)
return false;
purple_buddy_icon_get_data_wrapped = (purple_buddy_icon_get_data_wrapped_fnc)GetProcAddress(f_hPurple, "purple_buddy_icon_get_data");
if (!purple_buddy_icon_get_data_wrapped)
return false;
purple_account_set_bool_wrapped = (purple_account_set_bool_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_set_bool");
if (!purple_account_set_bool_wrapped)
return false;
purple_account_get_protocol_id_wrapped = (purple_account_get_protocol_id_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_get_protocol_id");
if (!purple_account_get_protocol_id_wrapped)
return false;
purple_account_set_int_wrapped = (purple_account_set_int_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_set_int");
if (!purple_account_set_int_wrapped)
return false;
purple_account_set_string_wrapped = (purple_account_set_string_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_set_string");
if (!purple_account_set_string_wrapped)
return false;
purple_account_get_username_wrapped = (purple_account_get_username_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_get_username");
if (!purple_account_get_username_wrapped)
return false;
purple_account_set_username_wrapped = (purple_account_set_username_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_set_username");
if (!purple_account_set_username_wrapped)
return false;
purple_accounts_find_wrapped = (purple_accounts_find_wrapped_fnc)GetProcAddress(f_hPurple, "purple_accounts_find");
if (!purple_accounts_find_wrapped)
return false;
purple_account_new_wrapped = (purple_account_new_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_new");
if (!purple_account_new_wrapped)
return false;
purple_accounts_add_wrapped = (purple_accounts_add_wrapped_fnc)GetProcAddress(f_hPurple, "purple_accounts_add");
if (!purple_accounts_add_wrapped)
return false;
purple_account_set_password_wrapped = (purple_account_set_password_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_set_password");
if (!purple_account_set_password_wrapped)
return false;
purple_account_set_enabled_wrapped = (purple_account_set_enabled_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_set_enabled");
if (!purple_account_set_enabled_wrapped)
return false;
purple_account_set_privacy_type_wrapped = (purple_account_set_privacy_type_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_set_privacy_type");
if (!purple_account_set_privacy_type_wrapped)
return false;
purple_account_get_status_type_with_primitive_wrapped = (purple_account_get_status_type_with_primitive_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_get_status_type_with_primitive");
if (!purple_account_get_status_type_with_primitive_wrapped)
return false;
purple_account_set_status_wrapped = (purple_account_set_status_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_set_status");
if (!purple_account_set_status_wrapped)
return false;
purple_account_get_int_wrapped = (purple_account_get_int_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_get_int");
if (!purple_account_get_int_wrapped)
return false;
purple_account_disconnect_wrapped = (purple_account_disconnect_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_disconnect");
if (!purple_account_disconnect_wrapped)
return false;
purple_accounts_delete_wrapped = (purple_accounts_delete_wrapped_fnc)GetProcAddress(f_hPurple, "purple_accounts_delete");
if (!purple_accounts_delete_wrapped)
return false;
purple_account_get_connection_wrapped = (purple_account_get_connection_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_get_connection");
if (!purple_account_get_connection_wrapped)
return false;
purple_account_set_alias_wrapped = (purple_account_set_alias_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_set_alias");
if (!purple_account_set_alias_wrapped)
return false;
purple_account_set_public_alias_wrapped = (purple_account_set_public_alias_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_set_public_alias");
if (!purple_account_set_public_alias_wrapped)
return false;
purple_account_remove_buddy_wrapped = (purple_account_remove_buddy_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_remove_buddy");
if (!purple_account_remove_buddy_wrapped)
return false;
purple_account_add_buddy_wrapped = (purple_account_add_buddy_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_add_buddy");
if (!purple_account_add_buddy_wrapped)
return false;
purple_account_get_name_for_display_wrapped = (purple_account_get_name_for_display_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_get_name_for_display");
if (!purple_account_get_name_for_display_wrapped)
return false;
purple_accounts_set_ui_ops_wrapped = (purple_accounts_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_accounts_set_ui_ops");
if (!purple_accounts_set_ui_ops_wrapped)
return false;
purple_status_type_get_id_wrapped = (purple_status_type_get_id_wrapped_fnc)GetProcAddress(f_hPurple, "purple_status_type_get_id");
if (!purple_status_type_get_id_wrapped)
return false;
purple_presence_get_active_status_wrapped = (purple_presence_get_active_status_wrapped_fnc)GetProcAddress(f_hPurple, "purple_presence_get_active_status");
if (!purple_presence_get_active_status_wrapped)
return false;
purple_status_type_get_primitive_wrapped = (purple_status_type_get_primitive_wrapped_fnc)GetProcAddress(f_hPurple, "purple_status_type_get_primitive");
if (!purple_status_type_get_primitive_wrapped)
return false;
purple_status_get_type_wrapped = (purple_status_get_type_wrapped_fnc)GetProcAddress(f_hPurple, "purple_status_get_type");
if (!purple_status_get_type_wrapped)
return false;
purple_status_get_attr_string_wrapped = (purple_status_get_attr_string_wrapped_fnc)GetProcAddress(f_hPurple, "purple_status_get_attr_string");
if (!purple_status_get_attr_string_wrapped)
return false;
serv_get_info_wrapped = (serv_get_info_wrapped_fnc)GetProcAddress(f_hPurple, "serv_get_info");
if (!serv_get_info_wrapped)
return false;
serv_alias_buddy_wrapped = (serv_alias_buddy_wrapped_fnc)GetProcAddress(f_hPurple, "serv_alias_buddy");
if (!serv_alias_buddy_wrapped)
return false;
serv_send_typing_wrapped = (serv_send_typing_wrapped_fnc)GetProcAddress(f_hPurple, "serv_send_typing");
if (!serv_send_typing_wrapped)
return false;
serv_join_chat_wrapped = (serv_join_chat_wrapped_fnc)GetProcAddress(f_hPurple, "serv_join_chat");
if (!serv_join_chat_wrapped)
return false;
purple_dnsquery_set_ui_ops_wrapped = (purple_dnsquery_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_dnsquery_set_ui_ops");
if (!purple_dnsquery_set_ui_ops_wrapped)
return false;
purple_conversation_get_im_data_wrapped = (purple_conversation_get_im_data_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conversation_get_im_data");
if (!purple_conversation_get_im_data_wrapped)
return false;
purple_conversation_get_chat_data_wrapped = (purple_conversation_get_chat_data_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conversation_get_chat_data");
if (!purple_conversation_get_chat_data_wrapped)
return false;
purple_find_conversation_with_account_wrapped = (purple_find_conversation_with_account_wrapped_fnc)GetProcAddress(f_hPurple, "purple_find_conversation_with_account");
if (!purple_find_conversation_with_account_wrapped)
return false;
purple_conversation_new_wrapped = (purple_conversation_new_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conversation_new");
if (!purple_conversation_new_wrapped)
return false;
purple_conversation_get_type_wrapped = (purple_conversation_get_type_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conversation_get_type");
if (!purple_conversation_get_type_wrapped)
return false;
purple_conv_im_send_wrapped = (purple_conv_im_send_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conv_im_send");
if (!purple_conv_im_send_wrapped)
return false;
purple_conv_chat_send_wrapped = (purple_conv_chat_send_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conv_chat_send");
if (!purple_conv_chat_send_wrapped)
return false;
purple_conversation_destroy_wrapped = (purple_conversation_destroy_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conversation_destroy");
if (!purple_conversation_destroy_wrapped)
return false;
purple_conversation_get_account_wrapped = (purple_conversation_get_account_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conversation_get_account");
if (!purple_conversation_get_account_wrapped)
return false;
purple_conversation_get_name_wrapped = (purple_conversation_get_name_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conversation_get_name");
if (!purple_conversation_get_name_wrapped)
return false;
purple_conversations_set_ui_ops_wrapped = (purple_conversations_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conversations_set_ui_ops");
if (!purple_conversations_set_ui_ops_wrapped)
return false;
purple_conversations_get_handle_wrapped = (purple_conversations_get_handle_wrapped_fnc)GetProcAddress(f_hPurple, "purple_conversations_get_handle");
if (!purple_conversations_get_handle_wrapped)
return false;
purple_plugin_action_free_wrapped = (purple_plugin_action_free_wrapped_fnc)GetProcAddress(f_hPurple, "purple_plugin_action_free");
if (!purple_plugin_action_free_wrapped)
return false;
purple_plugins_add_search_path_wrapped = (purple_plugins_add_search_path_wrapped_fnc)GetProcAddress(f_hPurple, "purple_plugins_add_search_path");
if (!purple_plugins_add_search_path_wrapped)
return false;
purple_connection_get_state_wrapped = (purple_connection_get_state_wrapped_fnc)GetProcAddress(f_hPurple, "purple_connection_get_state");
if (!purple_connection_get_state_wrapped)
return false;
purple_connection_get_account_wrapped = (purple_connection_get_account_wrapped_fnc)GetProcAddress(f_hPurple, "purple_connection_get_account");
if (!purple_connection_get_account_wrapped)
return false;
purple_connection_get_display_name_wrapped = (purple_connection_get_display_name_wrapped_fnc)GetProcAddress(f_hPurple, "purple_connection_get_display_name");
if (!purple_connection_get_display_name_wrapped)
return false;
purple_connections_set_ui_ops_wrapped = (purple_connections_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_connections_set_ui_ops");
if (!purple_connections_set_ui_ops_wrapped)
return false;
purple_connections_get_handle_wrapped = (purple_connections_get_handle_wrapped_fnc)GetProcAddress(f_hPurple, "purple_connections_get_handle");
if (!purple_connections_get_handle_wrapped)
return false;
purple_core_set_ui_ops_wrapped = (purple_core_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_core_set_ui_ops");
if (!purple_core_set_ui_ops_wrapped)
return false;
purple_core_init_wrapped = (purple_core_init_wrapped_fnc)GetProcAddress(f_hPurple, "purple_core_init");
if (!purple_core_init_wrapped)
return false;
purple_input_add_wrapped = (purple_input_add_wrapped_fnc)GetProcAddress(f_hPurple, "purple_input_add");
if (!purple_input_add_wrapped)
return false;
purple_timeout_add_wrapped = (purple_timeout_add_wrapped_fnc)GetProcAddress(f_hPurple, "purple_timeout_add");
if (!purple_timeout_add_wrapped)
return false;
purple_timeout_add_seconds_wrapped = (purple_timeout_add_seconds_wrapped_fnc)GetProcAddress(f_hPurple, "purple_timeout_add_seconds");
if (!purple_timeout_add_seconds_wrapped)
return false;
purple_timeout_remove_wrapped = (purple_timeout_remove_wrapped_fnc)GetProcAddress(f_hPurple, "purple_timeout_remove");
if (!purple_timeout_remove_wrapped)
return false;
purple_eventloop_set_ui_ops_wrapped = (purple_eventloop_set_ui_ops_wrapped_fnc)GetProcAddress(f_hPurple, "purple_eventloop_set_ui_ops");
if (!purple_eventloop_set_ui_ops_wrapped)
return false;
purple_input_remove_wrapped = (purple_input_remove_wrapped_fnc)GetProcAddress(f_hPurple, "purple_input_remove");
if (!purple_input_remove_wrapped)
return false;
purple_privacy_deny_wrapped = (purple_privacy_deny_wrapped_fnc)GetProcAddress(f_hPurple, "purple_privacy_deny");
if (!purple_privacy_deny_wrapped)
return false;
purple_privacy_allow_wrapped = (purple_privacy_allow_wrapped_fnc)GetProcAddress(f_hPurple, "purple_privacy_allow");
if (!purple_privacy_allow_wrapped)
return false;
purple_privacy_check_wrapped = (purple_privacy_check_wrapped_fnc)GetProcAddress(f_hPurple, "purple_privacy_check");
if (!purple_privacy_check_wrapped)
return false;
purple_find_prpl_wrapped = (purple_find_prpl_wrapped_fnc)GetProcAddress(f_hPurple, "purple_find_prpl");
if (!purple_find_prpl_wrapped)
return false;
purple_prpl_send_attention_wrapped = (purple_prpl_send_attention_wrapped_fnc)GetProcAddress(f_hPurple, "purple_prpl_send_attention");
if (!purple_prpl_send_attention_wrapped)
return false;
purple_account_option_get_type_wrapped = (purple_account_option_get_type_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_option_get_type");
if (!purple_account_option_get_type_wrapped)
return false;
purple_account_option_get_setting_wrapped = (purple_account_option_get_setting_wrapped_fnc)GetProcAddress(f_hPurple, "purple_account_option_get_setting");
if (!purple_account_option_get_setting_wrapped)
return false;
wpurple_g_io_channel_win32_new_socket_wrapped = (wpurple_g_io_channel_win32_new_socket_wrapped_fnc)GetProcAddress(f_hPurple, "wpurple_g_io_channel_win32_new_socket");
if (!wpurple_g_io_channel_win32_new_socket_wrapped)
return false;
#endif
return true;
}

View file

@ -1,3 +1,576 @@
#pragma once
#include <string>
#if PURPLE_RUNTIME
#include <Windows.h>
#include <purple.h>
#define PURPLE_BLIST_NODE_IS_CHAT_WRAPPED(n) (purple_blist_node_get_type_wrapped(n) == PURPLE_BLIST_CHAT_NODE)
#define PURPLE_BLIST_NODE_IS_BUDDY_WRAPPED(n) (purple_blist_node_get_type_wrapped(n) == PURPLE_BLIST_BUDDY_NODE)
#define PURPLE_BLIST_NODE_IS_CONTACT_WRAPPED(n) (purple_blist_node_get_type_wrapped(n) == PURPLE_BLIST_CONTACT_NODE)
#define PURPLE_BLIST_NODE_IS_GROUP_WRAPPED(n) (purple_blist_node_get_type_wrapped(n) == PURPLE_BLIST_GROUP_NODE)
#define PURPLE_CONV_IM_WRAPPED(c) (purple_conversation_get_im_data_wrapped(c))
#define PURPLE_CONV_CHAT_WRAPPED(c) (purple_conversation_get_chat_data_wrapped(c))
#define PURPLE_CONNECTION_IS_CONNECTED_WRAPPED(gc) (purple_connection_get_state_wrapped(gc) == PURPLE_CONNECTED)
typedef void (_cdecl * purple_debug_set_ui_ops_wrapped_fnc)(PurpleDebugUiOps *ops);
extern purple_debug_set_ui_ops_wrapped_fnc purple_debug_set_ui_ops_wrapped;
typedef void (_cdecl * purple_debug_set_verbose_wrapped_fnc)(gboolean verbose);
extern purple_debug_set_verbose_wrapped_fnc purple_debug_set_verbose_wrapped;
typedef void (_cdecl * purple_request_set_ui_ops_wrapped_fnc)(PurpleRequestUiOps *ops);
extern purple_request_set_ui_ops_wrapped_fnc purple_request_set_ui_ops_wrapped;
typedef gconstpointer (_cdecl * purple_imgstore_get_data_wrapped_fnc)(PurpleStoredImage *img);
extern purple_imgstore_get_data_wrapped_fnc purple_imgstore_get_data_wrapped;
typedef size_t (_cdecl * purple_imgstore_get_size_wrapped_fnc)(PurpleStoredImage *img);
extern purple_imgstore_get_size_wrapped_fnc purple_imgstore_get_size_wrapped;
typedef PurpleStoredImage * (_cdecl * purple_imgstore_unref_wrapped_fnc)(PurpleStoredImage *img);
extern purple_imgstore_unref_wrapped_fnc purple_imgstore_unref_wrapped;
typedef gchar * (_cdecl * purple_markup_escape_text_wrapped_fnc)(const gchar *text, gssize length);
extern purple_markup_escape_text_wrapped_fnc purple_markup_escape_text_wrapped;
typedef char * (_cdecl * purple_markup_strip_html_wrapped_fnc)(const char *str);
extern purple_markup_strip_html_wrapped_fnc purple_markup_strip_html_wrapped;
typedef const char * (_cdecl * purple_normalize_wrapped_fnc)(const PurpleAccount *account, const char *str);
extern purple_normalize_wrapped_fnc purple_normalize_wrapped;
typedef gchar * (_cdecl * purple_strdup_withhtml_wrapped_fnc)(const gchar *src);
extern purple_strdup_withhtml_wrapped_fnc purple_strdup_withhtml_wrapped;
typedef void (_cdecl * purple_markup_html_to_xhtml_wrapped_fnc)(const char *html, char **dest_xhtml, char **dest_plain);
extern purple_markup_html_to_xhtml_wrapped_fnc purple_markup_html_to_xhtml_wrapped;
typedef gchar * (_cdecl * purple_utf8_try_convert_wrapped_fnc)(const char *str);
extern purple_utf8_try_convert_wrapped_fnc purple_utf8_try_convert_wrapped;
typedef void (_cdecl * purple_util_set_user_dir_wrapped_fnc)(const char *dir);
extern purple_util_set_user_dir_wrapped_fnc purple_util_set_user_dir_wrapped;
typedef PurpleBlistNodeType (_cdecl * purple_blist_node_get_type_wrapped_fnc)(PurpleBlistNode *node);
extern purple_blist_node_get_type_wrapped_fnc purple_blist_node_get_type_wrapped;
typedef const char * (_cdecl * purple_buddy_get_alias_wrapped_fnc)(PurpleBuddy *buddy);
extern purple_buddy_get_alias_wrapped_fnc purple_buddy_get_alias_wrapped;
typedef const char * (_cdecl * purple_buddy_get_server_alias_wrapped_fnc)(PurpleBuddy *buddy);
extern purple_buddy_get_server_alias_wrapped_fnc purple_buddy_get_server_alias_wrapped;
typedef PurpleBuddy * (_cdecl * purple_find_buddy_wrapped_fnc)(PurpleAccount *account, const char *name);
extern purple_find_buddy_wrapped_fnc purple_find_buddy_wrapped;
typedef PurpleGroup * (_cdecl * purple_buddy_get_group_wrapped_fnc)(PurpleBuddy *buddy);
extern purple_buddy_get_group_wrapped_fnc purple_buddy_get_group_wrapped;
typedef void (_cdecl * purple_blist_remove_buddy_wrapped_fnc)(PurpleBuddy *buddy);
extern purple_blist_remove_buddy_wrapped_fnc purple_blist_remove_buddy_wrapped;
typedef void (_cdecl * purple_blist_alias_buddy_wrapped_fnc)(PurpleBuddy *buddy, const char *alias);
extern purple_blist_alias_buddy_wrapped_fnc purple_blist_alias_buddy_wrapped;
typedef void (_cdecl * purple_blist_server_alias_buddy_wrapped_fnc)(PurpleBuddy *buddy, const char *alias);
extern purple_blist_server_alias_buddy_wrapped_fnc purple_blist_server_alias_buddy_wrapped;
typedef PurpleGroup * (_cdecl * purple_find_group_wrapped_fnc)(const char *name);
extern purple_find_group_wrapped_fnc purple_find_group_wrapped;
typedef PurpleGroup * (_cdecl * purple_group_new_wrapped_fnc)(const char *name);
extern purple_group_new_wrapped_fnc purple_group_new_wrapped;
typedef void (_cdecl * purple_blist_add_contact_wrapped_fnc)(PurpleContact *contact, PurpleGroup *group, PurpleBlistNode *node);
extern purple_blist_add_contact_wrapped_fnc purple_blist_add_contact_wrapped;
typedef PurpleContact * (_cdecl * purple_buddy_get_contact_wrapped_fnc)(PurpleBuddy *buddy);
extern purple_buddy_get_contact_wrapped_fnc purple_buddy_get_contact_wrapped;
typedef PurpleBuddy * (_cdecl * purple_buddy_new_wrapped_fnc)(PurpleAccount *account, const char *name, const char *alias);
extern purple_buddy_new_wrapped_fnc purple_buddy_new_wrapped;
typedef void (_cdecl * purple_blist_add_buddy_wrapped_fnc)(PurpleBuddy *buddy, PurpleContact *contact, PurpleGroup *group, PurpleBlistNode *node);
extern purple_blist_add_buddy_wrapped_fnc purple_blist_add_buddy_wrapped;
typedef PurpleChat * (_cdecl * purple_blist_find_chat_wrapped_fnc)(PurpleAccount *account, const char *name);
extern purple_blist_find_chat_wrapped_fnc purple_blist_find_chat_wrapped;
typedef GHashTable * (_cdecl * purple_chat_get_components_wrapped_fnc)(PurpleChat *chat);
extern purple_chat_get_components_wrapped_fnc purple_chat_get_components_wrapped;
typedef PurplePresence * (_cdecl * purple_buddy_get_presence_wrapped_fnc)(const PurpleBuddy *buddy);
extern purple_buddy_get_presence_wrapped_fnc purple_buddy_get_presence_wrapped;
typedef PurpleAccount * (_cdecl * purple_buddy_get_account_wrapped_fnc)(const PurpleBuddy *buddy);
extern purple_buddy_get_account_wrapped_fnc purple_buddy_get_account_wrapped;
typedef const char * (_cdecl * purple_buddy_get_name_wrapped_fnc)(const PurpleBuddy *buddy);
extern purple_buddy_get_name_wrapped_fnc purple_buddy_get_name_wrapped;
typedef GSList * (_cdecl * purple_find_buddies_wrapped_fnc)(PurpleAccount *account, const char *name);
extern purple_find_buddies_wrapped_fnc purple_find_buddies_wrapped;
typedef const char * (_cdecl * purple_group_get_name_wrapped_fnc)(PurpleGroup *group);
extern purple_group_get_name_wrapped_fnc purple_group_get_name_wrapped;
typedef void (_cdecl * purple_blist_set_ui_ops_wrapped_fnc)(PurpleBlistUiOps *ops);
extern purple_blist_set_ui_ops_wrapped_fnc purple_blist_set_ui_ops_wrapped;
typedef void (_cdecl * purple_set_blist_wrapped_fnc)(PurpleBuddyList *blist);
extern purple_set_blist_wrapped_fnc purple_set_blist_wrapped;
typedef PurpleBuddyList * (_cdecl * purple_blist_new_wrapped_fnc)(void);
extern purple_blist_new_wrapped_fnc purple_blist_new_wrapped;
typedef void (_cdecl * purple_blist_load_wrapped_fnc)(void);
extern purple_blist_load_wrapped_fnc purple_blist_load_wrapped;
typedef void * (_cdecl * purple_blist_get_handle_wrapped_fnc)(void);
extern purple_blist_get_handle_wrapped_fnc purple_blist_get_handle_wrapped;
typedef void (_cdecl * purple_xfer_ui_ready_wrapped_fnc)(PurpleXfer *xfer);
extern purple_xfer_ui_ready_wrapped_fnc purple_xfer_ui_ready_wrapped;
typedef void (_cdecl * purple_xfer_request_accepted_wrapped_fnc)(PurpleXfer *xfer, const char *filename);
extern purple_xfer_request_accepted_wrapped_fnc purple_xfer_request_accepted_wrapped;
typedef void (_cdecl * purple_xfer_request_denied_wrapped_fnc)(PurpleXfer *xfer);
extern purple_xfer_request_denied_wrapped_fnc purple_xfer_request_denied_wrapped;
typedef PurpleAccount * (_cdecl * purple_xfer_get_account_wrapped_fnc)(const PurpleXfer *xfer);
extern purple_xfer_get_account_wrapped_fnc purple_xfer_get_account_wrapped;
typedef const char * (_cdecl * purple_xfer_get_filename_wrapped_fnc)(const PurpleXfer *xfer);
extern purple_xfer_get_filename_wrapped_fnc purple_xfer_get_filename_wrapped;
typedef size_t (_cdecl * purple_xfer_get_size_wrapped_fnc)(const PurpleXfer *xfer);
extern purple_xfer_get_size_wrapped_fnc purple_xfer_get_size_wrapped;
typedef void (_cdecl * purple_xfer_unref_wrapped_fnc)(PurpleXfer *xfer);
extern purple_xfer_unref_wrapped_fnc purple_xfer_unref_wrapped;
typedef void (_cdecl * purple_xfer_ref_wrapped_fnc)(PurpleXfer *xfer);
extern purple_xfer_ref_wrapped_fnc purple_xfer_ref_wrapped;
typedef void (_cdecl * purple_xfers_set_ui_ops_wrapped_fnc)(PurpleXferUiOps *ops);
extern purple_xfers_set_ui_ops_wrapped_fnc purple_xfers_set_ui_ops_wrapped;
typedef void * (_cdecl * purple_xfers_get_handle_wrapped_fnc)(void);
extern purple_xfers_get_handle_wrapped_fnc purple_xfers_get_handle_wrapped;
typedef gulong (_cdecl * purple_signal_connect_wrapped_fnc)(void *instance, const char *signal, void *handle, PurpleCallback func, void *data);
extern purple_signal_connect_wrapped_fnc purple_signal_connect_wrapped;
typedef gboolean (_cdecl * purple_prefs_load_wrapped_fnc)(void);
extern purple_prefs_load_wrapped_fnc purple_prefs_load_wrapped;
typedef void (_cdecl * purple_prefs_set_bool_wrapped_fnc)(const char *name, gboolean value);
extern purple_prefs_set_bool_wrapped_fnc purple_prefs_set_bool_wrapped;
typedef void (_cdecl * purple_prefs_set_string_wrapped_fnc)(const char *name, const char *value);
extern purple_prefs_set_string_wrapped_fnc purple_prefs_set_string_wrapped;
typedef PurpleNotifyUserInfo * (_cdecl * purple_notify_user_info_new_wrapped_fnc)(void);
extern purple_notify_user_info_new_wrapped_fnc purple_notify_user_info_new_wrapped;
typedef void (_cdecl * purple_notify_user_info_destroy_wrapped_fnc)(PurpleNotifyUserInfo *user_info);
extern purple_notify_user_info_destroy_wrapped_fnc purple_notify_user_info_destroy_wrapped;
typedef GList * (_cdecl * purple_notify_user_info_get_entries_wrapped_fnc)(PurpleNotifyUserInfo *user_info);
extern purple_notify_user_info_get_entries_wrapped_fnc purple_notify_user_info_get_entries_wrapped;
typedef const gchar * (_cdecl * purple_notify_user_info_entry_get_label_wrapped_fnc)(PurpleNotifyUserInfoEntry *user_info_entry);
extern purple_notify_user_info_entry_get_label_wrapped_fnc purple_notify_user_info_entry_get_label_wrapped;
typedef const gchar * (_cdecl * purple_notify_user_info_entry_get_value_wrapped_fnc)(PurpleNotifyUserInfoEntry *user_info_entry);
extern purple_notify_user_info_entry_get_value_wrapped_fnc purple_notify_user_info_entry_get_value_wrapped;
typedef void (_cdecl * purple_notify_set_ui_ops_wrapped_fnc)(PurpleNotifyUiOps *ops);
extern purple_notify_set_ui_ops_wrapped_fnc purple_notify_set_ui_ops_wrapped;
typedef PurpleStoredImage * (_cdecl * purple_buddy_icons_set_account_icon_wrapped_fnc)(PurpleAccount *account, guchar *icon_data, size_t icon_len);
extern purple_buddy_icons_set_account_icon_wrapped_fnc purple_buddy_icons_set_account_icon_wrapped;
typedef PurpleBuddyIcon * (_cdecl * purple_buddy_icons_find_wrapped_fnc)(PurpleAccount *account, const char *username);
extern purple_buddy_icons_find_wrapped_fnc purple_buddy_icons_find_wrapped;
typedef char * (_cdecl * purple_buddy_icon_get_full_path_wrapped_fnc)(PurpleBuddyIcon *icon);
extern purple_buddy_icon_get_full_path_wrapped_fnc purple_buddy_icon_get_full_path_wrapped;
typedef PurpleBuddyIcon * (_cdecl * purple_buddy_icon_unref_wrapped_fnc)(PurpleBuddyIcon *icon);
extern purple_buddy_icon_unref_wrapped_fnc purple_buddy_icon_unref_wrapped;
typedef PurpleStoredImage * (_cdecl * purple_buddy_icons_find_account_icon_wrapped_fnc)(PurpleAccount *account);
extern purple_buddy_icons_find_account_icon_wrapped_fnc purple_buddy_icons_find_account_icon_wrapped;
typedef gconstpointer (_cdecl * purple_buddy_icon_get_data_wrapped_fnc)(const PurpleBuddyIcon *icon, size_t *len);
extern purple_buddy_icon_get_data_wrapped_fnc purple_buddy_icon_get_data_wrapped;
typedef void (_cdecl * purple_account_set_bool_wrapped_fnc)(PurpleAccount *account, const char *name, gboolean value);
extern purple_account_set_bool_wrapped_fnc purple_account_set_bool_wrapped;
typedef const char * (_cdecl * purple_account_get_protocol_id_wrapped_fnc)(const PurpleAccount *account);
extern purple_account_get_protocol_id_wrapped_fnc purple_account_get_protocol_id_wrapped;
typedef void (_cdecl * purple_account_set_int_wrapped_fnc)(PurpleAccount *account, const char *name, int value);
extern purple_account_set_int_wrapped_fnc purple_account_set_int_wrapped;
typedef void (_cdecl * purple_account_set_string_wrapped_fnc)(PurpleAccount *account, const char *name, const char *value);
extern purple_account_set_string_wrapped_fnc purple_account_set_string_wrapped;
typedef const char * (_cdecl * purple_account_get_username_wrapped_fnc)(const PurpleAccount *account);
extern purple_account_get_username_wrapped_fnc purple_account_get_username_wrapped;
typedef void (_cdecl * purple_account_set_username_wrapped_fnc)(PurpleAccount *account, const char *username);
extern purple_account_set_username_wrapped_fnc purple_account_set_username_wrapped;
typedef PurpleAccount * (_cdecl * purple_accounts_find_wrapped_fnc)(const char *name, const char *protocol);
extern purple_accounts_find_wrapped_fnc purple_accounts_find_wrapped;
typedef PurpleAccount * (_cdecl * purple_account_new_wrapped_fnc)(const char *username, const char *protocol_id);
extern purple_account_new_wrapped_fnc purple_account_new_wrapped;
typedef void (_cdecl * purple_accounts_add_wrapped_fnc)(PurpleAccount *account);
extern purple_accounts_add_wrapped_fnc purple_accounts_add_wrapped;
typedef void (_cdecl * purple_account_set_password_wrapped_fnc)(PurpleAccount *account, const char *password);
extern purple_account_set_password_wrapped_fnc purple_account_set_password_wrapped;
typedef void (_cdecl * purple_account_set_enabled_wrapped_fnc)(PurpleAccount *account, const char *ui, gboolean value);
extern purple_account_set_enabled_wrapped_fnc purple_account_set_enabled_wrapped;
typedef void (_cdecl * purple_account_set_privacy_type_wrapped_fnc)(PurpleAccount *account, PurplePrivacyType privacy_type);
extern purple_account_set_privacy_type_wrapped_fnc purple_account_set_privacy_type_wrapped;
typedef PurpleStatusType * (_cdecl * purple_account_get_status_type_with_primitive_wrapped_fnc)( const PurpleAccount *account, PurpleStatusPrimitive primitive);
extern purple_account_get_status_type_with_primitive_wrapped_fnc purple_account_get_status_type_with_primitive_wrapped;
typedef void (_cdecl * purple_account_set_status_wrapped_fnc)(PurpleAccount *account, const char *status_id, gboolean active, ...);
extern purple_account_set_status_wrapped_fnc purple_account_set_status_wrapped;
typedef int (_cdecl * purple_account_get_int_wrapped_fnc)(const PurpleAccount *account, const char *name, int default_value);
extern purple_account_get_int_wrapped_fnc purple_account_get_int_wrapped;
typedef void (_cdecl * purple_account_disconnect_wrapped_fnc)(PurpleAccount *account);
extern purple_account_disconnect_wrapped_fnc purple_account_disconnect_wrapped;
typedef void (_cdecl * purple_accounts_delete_wrapped_fnc)(PurpleAccount *account);
extern purple_accounts_delete_wrapped_fnc purple_accounts_delete_wrapped;
typedef PurpleConnection * (_cdecl * purple_account_get_connection_wrapped_fnc)(const PurpleAccount *account);
extern purple_account_get_connection_wrapped_fnc purple_account_get_connection_wrapped;
typedef void (_cdecl * purple_account_set_alias_wrapped_fnc)(PurpleAccount *account, const char *alias);
extern purple_account_set_alias_wrapped_fnc purple_account_set_alias_wrapped;
typedef void (_cdecl * purple_account_set_public_alias_wrapped_fnc)(PurpleAccount *account, const char *alias, PurpleSetPublicAliasSuccessCallback success_cb, PurpleSetPublicAliasFailureCallback failure_cb);
extern purple_account_set_public_alias_wrapped_fnc purple_account_set_public_alias_wrapped;
typedef void (_cdecl * purple_account_remove_buddy_wrapped_fnc)(PurpleAccount *account, PurpleBuddy *buddy, PurpleGroup *group);
extern purple_account_remove_buddy_wrapped_fnc purple_account_remove_buddy_wrapped;
typedef void (_cdecl * purple_account_add_buddy_wrapped_fnc)(PurpleAccount *account, PurpleBuddy *buddy);
extern purple_account_add_buddy_wrapped_fnc purple_account_add_buddy_wrapped;
typedef const gchar * (_cdecl * purple_account_get_name_for_display_wrapped_fnc)(const PurpleAccount *account);
extern purple_account_get_name_for_display_wrapped_fnc purple_account_get_name_for_display_wrapped;
typedef void (_cdecl * purple_accounts_set_ui_ops_wrapped_fnc)(PurpleAccountUiOps *ops);
extern purple_accounts_set_ui_ops_wrapped_fnc purple_accounts_set_ui_ops_wrapped;
typedef const char * (_cdecl * purple_status_type_get_id_wrapped_fnc)(const PurpleStatusType *status_type);
extern purple_status_type_get_id_wrapped_fnc purple_status_type_get_id_wrapped;
typedef PurpleStatus * (_cdecl * purple_presence_get_active_status_wrapped_fnc)(const PurplePresence *presence);
extern purple_presence_get_active_status_wrapped_fnc purple_presence_get_active_status_wrapped;
typedef PurpleStatusPrimitive (_cdecl * purple_status_type_get_primitive_wrapped_fnc)( const PurpleStatusType *status_type);
extern purple_status_type_get_primitive_wrapped_fnc purple_status_type_get_primitive_wrapped;
typedef PurpleStatusType * (_cdecl * purple_status_get_type_wrapped_fnc)(const PurpleStatus *status);
extern purple_status_get_type_wrapped_fnc purple_status_get_type_wrapped;
typedef const char * (_cdecl * purple_status_get_attr_string_wrapped_fnc)(const PurpleStatus *status, const char *id);
extern purple_status_get_attr_string_wrapped_fnc purple_status_get_attr_string_wrapped;
typedef void (_cdecl * serv_get_info_wrapped_fnc)(PurpleConnection *, const char *);
extern serv_get_info_wrapped_fnc serv_get_info_wrapped;
typedef void (_cdecl * serv_alias_buddy_wrapped_fnc)(PurpleBuddy *);
extern serv_alias_buddy_wrapped_fnc serv_alias_buddy_wrapped;
typedef unsigned int (_cdecl * serv_send_typing_wrapped_fnc)(PurpleConnection *gc, const char *name, PurpleTypingState state);
extern serv_send_typing_wrapped_fnc serv_send_typing_wrapped;
typedef void (_cdecl * serv_join_chat_wrapped_fnc)(PurpleConnection *, GHashTable *data);
extern serv_join_chat_wrapped_fnc serv_join_chat_wrapped;
typedef void (_cdecl * purple_dnsquery_set_ui_ops_wrapped_fnc)(PurpleDnsQueryUiOps *ops);
extern purple_dnsquery_set_ui_ops_wrapped_fnc purple_dnsquery_set_ui_ops_wrapped;
typedef PurpleConvIm * (_cdecl * purple_conversation_get_im_data_wrapped_fnc)(const PurpleConversation *conv);
extern purple_conversation_get_im_data_wrapped_fnc purple_conversation_get_im_data_wrapped;
typedef PurpleConvChat * (_cdecl * purple_conversation_get_chat_data_wrapped_fnc)(const PurpleConversation *conv);
extern purple_conversation_get_chat_data_wrapped_fnc purple_conversation_get_chat_data_wrapped;
typedef PurpleConversation * (_cdecl * purple_find_conversation_with_account_wrapped_fnc)( PurpleConversationType type, const char *name, const PurpleAccount *account);
extern purple_find_conversation_with_account_wrapped_fnc purple_find_conversation_with_account_wrapped;
typedef PurpleConversation * (_cdecl * purple_conversation_new_wrapped_fnc)(PurpleConversationType type, PurpleAccount *account, const char *name);
extern purple_conversation_new_wrapped_fnc purple_conversation_new_wrapped;
typedef PurpleConversationType (_cdecl * purple_conversation_get_type_wrapped_fnc)(const PurpleConversation *conv);
extern purple_conversation_get_type_wrapped_fnc purple_conversation_get_type_wrapped;
typedef void (_cdecl * purple_conv_im_send_wrapped_fnc)(PurpleConvIm *im, const char *message);
extern purple_conv_im_send_wrapped_fnc purple_conv_im_send_wrapped;
typedef void (_cdecl * purple_conv_chat_send_wrapped_fnc)(PurpleConvChat *chat, const char *message);
extern purple_conv_chat_send_wrapped_fnc purple_conv_chat_send_wrapped;
typedef void (_cdecl * purple_conversation_destroy_wrapped_fnc)(PurpleConversation *conv);
extern purple_conversation_destroy_wrapped_fnc purple_conversation_destroy_wrapped;
typedef PurpleAccount * (_cdecl * purple_conversation_get_account_wrapped_fnc)(const PurpleConversation *conv);
extern purple_conversation_get_account_wrapped_fnc purple_conversation_get_account_wrapped;
typedef const char * (_cdecl * purple_conversation_get_name_wrapped_fnc)(const PurpleConversation *conv);
extern purple_conversation_get_name_wrapped_fnc purple_conversation_get_name_wrapped;
typedef void (_cdecl * purple_conversations_set_ui_ops_wrapped_fnc)(PurpleConversationUiOps *ops);
extern purple_conversations_set_ui_ops_wrapped_fnc purple_conversations_set_ui_ops_wrapped;
typedef void * (_cdecl * purple_conversations_get_handle_wrapped_fnc)(void);
extern purple_conversations_get_handle_wrapped_fnc purple_conversations_get_handle_wrapped;
typedef void (_cdecl * purple_plugin_action_free_wrapped_fnc)(PurplePluginAction *action);
extern purple_plugin_action_free_wrapped_fnc purple_plugin_action_free_wrapped;
typedef void (_cdecl * purple_plugins_add_search_path_wrapped_fnc)(const char *path);
extern purple_plugins_add_search_path_wrapped_fnc purple_plugins_add_search_path_wrapped;
typedef void (_cdecl * purple_certificate_add_ca_search_path_wrapped_fnc)(const char *path);
extern purple_certificate_add_ca_search_path_wrapped_fnc purple_certificate_add_ca_search_path_wrapped;
typedef PurpleConnectionState (_cdecl * purple_connection_get_state_wrapped_fnc)(const PurpleConnection *gc);
extern purple_connection_get_state_wrapped_fnc purple_connection_get_state_wrapped;
typedef PurpleAccount * (_cdecl * purple_connection_get_account_wrapped_fnc)(const PurpleConnection *gc);
extern purple_connection_get_account_wrapped_fnc purple_connection_get_account_wrapped;
typedef const char * (_cdecl * purple_connection_get_display_name_wrapped_fnc)(const PurpleConnection *gc);
extern purple_connection_get_display_name_wrapped_fnc purple_connection_get_display_name_wrapped;
typedef void (_cdecl * purple_connections_set_ui_ops_wrapped_fnc)(PurpleConnectionUiOps *ops);
extern purple_connections_set_ui_ops_wrapped_fnc purple_connections_set_ui_ops_wrapped;
typedef void * (_cdecl * purple_connections_get_handle_wrapped_fnc)(void);
extern purple_connections_get_handle_wrapped_fnc purple_connections_get_handle_wrapped;
typedef void (_cdecl * purple_core_set_ui_ops_wrapped_fnc)(PurpleCoreUiOps *ops);
extern purple_core_set_ui_ops_wrapped_fnc purple_core_set_ui_ops_wrapped;
typedef gboolean (_cdecl * purple_core_init_wrapped_fnc)(const char *ui);
extern purple_core_init_wrapped_fnc purple_core_init_wrapped;
typedef guint (_cdecl * purple_input_add_wrapped_fnc)(int fd, PurpleInputCondition cond, PurpleInputFunction func, gpointer user_data);
extern purple_input_add_wrapped_fnc purple_input_add_wrapped;
typedef guint (_cdecl * purple_timeout_add_wrapped_fnc)(guint interval, GSourceFunc function, gpointer data);
extern purple_timeout_add_wrapped_fnc purple_timeout_add_wrapped;
typedef guint (_cdecl * purple_timeout_add_seconds_wrapped_fnc)(guint interval, GSourceFunc function, gpointer data);
extern purple_timeout_add_seconds_wrapped_fnc purple_timeout_add_seconds_wrapped;
typedef gboolean (_cdecl * purple_timeout_remove_wrapped_fnc)(guint handle);
extern purple_timeout_remove_wrapped_fnc purple_timeout_remove_wrapped;
typedef void (_cdecl * purple_eventloop_set_ui_ops_wrapped_fnc)(PurpleEventLoopUiOps *ops);
extern purple_eventloop_set_ui_ops_wrapped_fnc purple_eventloop_set_ui_ops_wrapped;
typedef gboolean (_cdecl * purple_input_remove_wrapped_fnc)(guint handle);
extern purple_input_remove_wrapped_fnc purple_input_remove_wrapped;
typedef void (_cdecl * purple_privacy_deny_wrapped_fnc)(PurpleAccount *account, const char *who, gboolean local, gboolean restore);
extern purple_privacy_deny_wrapped_fnc purple_privacy_deny_wrapped;
typedef void (_cdecl * purple_privacy_allow_wrapped_fnc)(PurpleAccount *account, const char *who, gboolean local, gboolean restore);
extern purple_privacy_allow_wrapped_fnc purple_privacy_allow_wrapped;
typedef gboolean (_cdecl * purple_privacy_check_wrapped_fnc)(PurpleAccount *account, const char *who);
extern purple_privacy_check_wrapped_fnc purple_privacy_check_wrapped;
typedef PurplePlugin * (_cdecl * purple_find_prpl_wrapped_fnc)(const char *id);
extern purple_find_prpl_wrapped_fnc purple_find_prpl_wrapped;
typedef void (_cdecl * purple_prpl_send_attention_wrapped_fnc)(PurpleConnection *gc, const char *who, guint type_code);
extern purple_prpl_send_attention_wrapped_fnc purple_prpl_send_attention_wrapped;
typedef PurplePrefType (_cdecl * purple_account_option_get_type_wrapped_fnc)(const PurpleAccountOption *option);
extern purple_account_option_get_type_wrapped_fnc purple_account_option_get_type_wrapped;
typedef const char * (_cdecl * purple_account_option_get_setting_wrapped_fnc)(const PurpleAccountOption *option);
extern purple_account_option_get_setting_wrapped_fnc purple_account_option_get_setting_wrapped;
typedef GIOChannel * (_cdecl * wpurple_g_io_channel_win32_new_socket_wrapped_fnc)(int socket);
extern wpurple_g_io_channel_win32_new_socket_wrapped_fnc wpurple_g_io_channel_win32_new_socket_wrapped;
#else
#define PURPLE_BLIST_NODE_IS_CHAT_WRAPPED PURPLE_BLIST_NODE_IS_CHAT
#define PURPLE_BLIST_NODE_IS_BUDDY_WRAPPED PURPLE_BLIST_NODE_IS_BUDDY
#define PURPLE_BLIST_NODE_IS_CONTACT_WRAPPED PURPLE_BLIST_NODE_IS_CONTACT
#define PURPLE_BLIST_NODE_IS_GROUP_WRAPPED PURPLE_BLIST_NODE_IS_GROUP
#define PURPLE_CONV_IM_WRAPPED PURPLE_CONV_IM
#define PURPLE_CONV_CHAT_WRAPPED PURPLE_CONV_CHAT
#define PURPLE_CONNECTION_IS_CONNECTED_WRAPPED PURPLE_CONNECTION_IS_CONNECTED
#define purple_debug_set_ui_ops_wrapped purple_debug_set_ui_ops
#define purple_debug_set_verbose_wrapped purple_debug_set_verbose
#define purple_request_set_ui_ops_wrapped purple_request_set_ui_ops
#define purple_imgstore_get_data_wrapped purple_imgstore_get_data
#define purple_imgstore_get_size_wrapped purple_imgstore_get_size
#define purple_imgstore_unref_wrapped purple_imgstore_unref
#define purple_markup_escape_text_wrapped purple_markup_escape_text
#define purple_markup_strip_html_wrapped purple_markup_strip_html
#define purple_normalize_wrapped purple_normalize
#define purple_strdup_withhtml_wrapped purple_strdup_withhtml
#define purple_markup_html_to_xhtml_wrapped purple_markup_html_to_xhtml
#define purple_utf8_try_convert_wrapped purple_utf8_try_convert
#define purple_util_set_user_dir_wrapped purple_util_set_user_dir
#define purple_blist_node_get_type_wrapped purple_blist_node_get_type
#define purple_buddy_get_alias_wrapped purple_buddy_get_alias
#define purple_buddy_get_server_alias_wrapped purple_buddy_get_server_alias
#define purple_find_buddy_wrapped purple_find_buddy
#define purple_buddy_get_group_wrapped purple_buddy_get_group
#define purple_blist_remove_buddy_wrapped purple_blist_remove_buddy
#define purple_blist_alias_buddy_wrapped purple_blist_alias_buddy
#define purple_blist_server_alias_buddy_wrapped purple_blist_server_alias_buddy
#define purple_find_group_wrapped purple_find_group
#define purple_group_new_wrapped purple_group_new
#define purple_blist_add_contact_wrapped purple_blist_add_contact
#define purple_buddy_get_contact_wrapped purple_buddy_get_contact
#define purple_buddy_new_wrapped purple_buddy_new
#define purple_blist_add_buddy_wrapped purple_blist_add_buddy
#define purple_blist_find_chat_wrapped purple_blist_find_chat
#define purple_chat_get_components_wrapped purple_chat_get_components
#define purple_buddy_get_presence_wrapped purple_buddy_get_presence
#define purple_buddy_get_account_wrapped purple_buddy_get_account
#define purple_buddy_get_name_wrapped purple_buddy_get_name
#define purple_find_buddies_wrapped purple_find_buddies
#define purple_group_get_name_wrapped purple_group_get_name
#define purple_blist_set_ui_ops_wrapped purple_blist_set_ui_ops
#define purple_set_blist_wrapped purple_set_blist
#define purple_blist_new_wrapped purple_blist_new
#define purple_blist_load_wrapped purple_blist_load
#define purple_blist_get_handle_wrapped purple_blist_get_handle
#define purple_xfer_ui_ready_wrapped purple_xfer_ui_ready
#define purple_xfer_request_accepted_wrapped purple_xfer_request_accepted
#define purple_xfer_request_denied_wrapped purple_xfer_request_denied
#define purple_xfer_get_account_wrapped purple_xfer_get_account
#define purple_xfer_get_filename_wrapped purple_xfer_get_filename
#define purple_xfer_get_size_wrapped purple_xfer_get_size
#define purple_xfer_unref_wrapped purple_xfer_unref
#define purple_xfer_ref_wrapped purple_xfer_ref
#define purple_xfers_set_ui_ops_wrapped purple_xfers_set_ui_ops
#define purple_xfers_get_handle_wrapped purple_xfers_get_handle
#define purple_signal_connect_wrapped purple_signal_connect
#define purple_prefs_load_wrapped purple_prefs_load
#define purple_prefs_set_bool_wrapped purple_prefs_set_bool
#define purple_prefs_set_string_wrapped purple_prefs_set_string
#define purple_notify_user_info_new_wrapped purple_notify_user_info_new
#define purple_notify_user_info_destroy_wrapped purple_notify_user_info_destroy
#define purple_notify_user_info_get_entries_wrapped purple_notify_user_info_get_entries
#define purple_notify_user_info_entry_get_label_wrapped purple_notify_user_info_entry_get_label
#define purple_notify_user_info_entry_get_value_wrapped purple_notify_user_info_entry_get_value
#define purple_notify_set_ui_ops_wrapped purple_notify_set_ui_ops
#define purple_buddy_icons_set_account_icon_wrapped purple_buddy_icons_set_account_icon
#define purple_buddy_icons_find_wrapped purple_buddy_icons_find
#define purple_buddy_icon_get_full_path_wrapped purple_buddy_icon_get_full_path
#define purple_buddy_icon_unref_wrapped purple_buddy_icon_unref
#define purple_buddy_icons_find_account_icon_wrapped purple_buddy_icons_find_account_icon
#define purple_buddy_icon_get_data_wrapped purple_buddy_icon_get_data
#define purple_account_set_bool_wrapped purple_account_set_bool
#define purple_account_get_protocol_id_wrapped purple_account_get_protocol_id
#define purple_account_set_int_wrapped purple_account_set_int
#define purple_account_set_string_wrapped purple_account_set_string
#define purple_account_get_username_wrapped purple_account_get_username
#define purple_account_set_username_wrapped purple_account_set_username
#define purple_accounts_find_wrapped purple_accounts_find
#define purple_account_new_wrapped purple_account_new
#define purple_accounts_add_wrapped purple_accounts_add
#define purple_account_set_password_wrapped purple_account_set_password
#define purple_account_set_enabled_wrapped purple_account_set_enabled
#define purple_account_set_privacy_type_wrapped purple_account_set_privacy_type
#define purple_account_get_status_type_with_primitive_wrapped purple_account_get_status_type_with_primitive
#define purple_account_set_status_wrapped purple_account_set_status
#define purple_account_get_int_wrapped purple_account_get_int
#define purple_account_disconnect_wrapped purple_account_disconnect
#define purple_accounts_delete_wrapped purple_accounts_delete
#define purple_account_get_connection_wrapped purple_account_get_connection
#define purple_account_set_alias_wrapped purple_account_set_alias
#define purple_account_set_public_alias_wrapped purple_account_set_public_alias
#define purple_account_remove_buddy_wrapped purple_account_remove_buddy
#define purple_account_add_buddy_wrapped purple_account_add_buddy
#define purple_account_get_name_for_display_wrapped purple_account_get_name_for_display
#define purple_accounts_set_ui_ops_wrapped purple_accounts_set_ui_ops
#define purple_status_type_get_id_wrapped purple_status_type_get_id
#define purple_presence_get_active_status_wrapped purple_presence_get_active_status
#define purple_status_type_get_primitive_wrapped purple_status_type_get_primitive
#define purple_status_get_type_wrapped purple_status_get_type
#define purple_status_get_attr_string_wrapped purple_status_get_attr_string
#define serv_get_info_wrapped serv_get_info
#define serv_alias_buddy_wrapped serv_alias_buddy
#define serv_send_typing_wrapped serv_send_typing
#define serv_join_chat_wrapped serv_join_chat
#define purple_dnsquery_set_ui_ops_wrapped purple_dnsquery_set_ui_ops
#define purple_conversation_get_im_data_wrapped purple_conversation_get_im_data
#define purple_conversation_get_chat_data_wrapped purple_conversation_get_chat_data
#define purple_find_conversation_with_account_wrapped purple_find_conversation_with_account
#define purple_conversation_new_wrapped purple_conversation_new
#define purple_conversation_get_type_wrapped purple_conversation_get_type
#define purple_conv_im_send_wrapped purple_conv_im_send
#define purple_conv_chat_send_wrapped purple_conv_chat_send
#define purple_conversation_destroy_wrapped purple_conversation_destroy
#define purple_conversation_get_account_wrapped purple_conversation_get_account
#define purple_conversation_get_name_wrapped purple_conversation_get_name
#define purple_conversations_set_ui_ops_wrapped purple_conversations_set_ui_ops
#define purple_conversations_get_handle_wrapped purple_conversations_get_handle
#define purple_plugin_action_free_wrapped purple_plugin_action_free
#define purple_certificate_add_ca_search_path_wrapped purple_certificate_add_ca_search_path
#define purple_plugins_add_search_path_wrapped purple_plugins_add_search_path
#define purple_connection_get_state_wrapped purple_connection_get_state
#define purple_connection_get_account_wrapped purple_connection_get_account
#define purple_connection_get_display_name_wrapped purple_connection_get_display_name
#define purple_connections_set_ui_ops_wrapped purple_connections_set_ui_ops
#define purple_connections_get_handle_wrapped purple_connections_get_handle
#define purple_core_set_ui_ops_wrapped purple_core_set_ui_ops
#define purple_core_init_wrapped purple_core_init
#define purple_input_add_wrapped purple_input_add
#define purple_timeout_add_wrapped purple_timeout_add
#define purple_timeout_add_seconds_wrapped purple_timeout_add_seconds
#define purple_timeout_remove_wrapped purple_timeout_remove
#define purple_eventloop_set_ui_ops_wrapped purple_eventloop_set_ui_ops
#define purple_input_remove_wrapped purple_input_remove
#define purple_privacy_deny_wrapped purple_privacy_deny
#define purple_privacy_allow_wrapped purple_privacy_allow
#define purple_privacy_check_wrapped purple_privacy_check
#define purple_find_prpl_wrapped purple_find_prpl
#define purple_prpl_send_attention_wrapped purple_prpl_send_attention
#define purple_account_option_get_type_wrapped purple_account_option_get_type
#define purple_account_option_get_setting_wrapped purple_account_option_get_setting
#define wpurple_g_io_channel_win32_new_socket_wrapped wpurple_g_io_channel_win32_new_socket
#endif
bool resolvePurpleFunctions(const std::string& libPurpleDllPath);
bool resolvePurpleFunctions();

View file

@ -18,14 +18,20 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
*/
// win32/libc_interface.h defines its own socket(), read() and so on.
// We don't want to use it here.
#define _LIBC_INTERFACE_H_ 1
#include "utils.h"
#include "glib.h"
#include "purple.h"
#include <algorithm>
#include <iostream>
#include <vector>
#include "errno.h"
#include <string.h>
#ifndef WIN32
#include "sys/wait.h"
@ -45,14 +51,19 @@
#define getpid _getpid
#define ssize_t SSIZE_T
#include "win32/win32dep.h"
#define close closesocket
#endif
#include "purple_defs.h"
#include <boost/numeric/conversion/cast.hpp>
using std::vector;
static GHashTable *ui_info = NULL;
void execute_purple_plugin_action(PurpleConnection *gc, const std::string &name) {
PurplePlugin *plugin = gc && PURPLE_CONNECTION_IS_CONNECTED(gc) ? gc->prpl : NULL;
PurplePlugin *plugin = gc && PURPLE_CONNECTION_IS_CONNECTED_WRAPPED(gc) ? gc->prpl : NULL;
if (plugin && PURPLE_PLUGIN_HAS_ACTIONS(plugin)) {
PurplePluginAction *action = NULL;
GList *actions, *l;
@ -67,7 +78,7 @@ void execute_purple_plugin_action(PurpleConnection *gc, const std::string &name)
if ((std::string) action->label == name) {
action->callback(action);
}
purple_plugin_action_free(action);
purple_plugin_action_free_wrapped(action);
}
}
}
@ -125,7 +136,7 @@ void spectrum_sigchld_handler(int sig)
}
#endif
int create_socket(char *host, int portno) {
int create_socket(const char *host, int portno) {
struct sockaddr_in serv_addr;
int main_socket = socket(AF_INET, SOCK_STREAM, 0);
@ -151,3 +162,34 @@ int create_socket(char *host, int portno) {
// fcntl(main_socket, F_SETFL, flags);
return main_socket;
}
#ifdef _WIN32
std::wstring utf8ToUtf16(const std::string& str)
{
try
{
if (str.empty())
return L"";
// First request the size of the required UTF-16 buffer
int numRequiredBytes = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), boost::numeric_cast<int>(str.size()), NULL, 0);
if (!numRequiredBytes)
return L"";
// Allocate memory for the UTF-16 string
std::vector<wchar_t> utf16Str(numRequiredBytes);
int numConverted = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), boost::numeric_cast<int>(str.size()), &utf16Str[0], numRequiredBytes);
if (!numConverted)
return L"";
std::wstring wstr(&utf16Str[0], numConverted);
return wstr;
}
catch (...)
{
// I don't believe libtransport is exception-safe so we'll just return an empty string instead
return L"";
}
}
#endif // _WIN32

View file

@ -27,7 +27,11 @@
void spectrum_sigchld_handler(int sig);
#endif
int create_socket(char *host, int portno);
int create_socket(const char *host, int portno);
GHashTable *spectrum_ui_get_info(void);
void execute_purple_plugin_action(PurpleConnection *gc, const std::string &name);
#ifdef _WIN32
std::wstring utf8ToUtf16(const std::string& str);
#endif

View file

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

View file

@ -0,0 +1,163 @@
#include "httpfetch.h"
#include "transport/logging.h"
#if WIN32
#define snprintf sprintf_s
#endif
DEFINE_LOGGER(logger, "HTTPFetch");
static int url_to_host_port_path(const char *url,
char *host, int *port, char *path, int *ssl)
{
char *urlcopy = NULL;
char *slash = NULL;
char *colon = NULL;
/*
* http://hostname
* http://hostname/
* http://hostname/path
* http://hostname/path:foo
* http://hostname:port
* http://hostname:port/
* http://hostname:port/path
* http://hostname:port/path:foo
* and https:// variants of the above
*/
if (strstr(url, "http://") == url) {
urlcopy = strdup(url + 7);
} else if (strstr(url, "https://") == url) {
urlcopy = strdup(url + 8);
*ssl = 1;
} else {
return 0;
}
slash = strchr(urlcopy, '/');
colon = strchr(urlcopy, ':');
if (!colon || (slash && slash < colon)) {
if (*ssl)
*port = 443;
else
*port = 80;
} else {
*colon = 0;
*port = atoi(colon + 1);
}
if (!slash) {
strcpy(path, "/");
} else {
strcpy(path, slash);
*slash = 0;
}
strcpy(host, urlcopy);
free(urlcopy);
return 1;
}
HTTPFetch::HTTPFetch(Swift::BoostIOServiceThread *ioService, Swift::ConnectionFactory *factory) : m_ioService(ioService), m_factory(factory) {
m_afterHeader = false;
}
HTTPFetch::~HTTPFetch() {
}
void HTTPFetch::_connected(boost::shared_ptr<Swift::Connection> conn, const std::string url, bool error) {
if (error) {
_disconnected(conn);
}
else {
char host[255];
int port = 80;
char path[255];
int ssl = 0;
if (!url_to_host_port_path(url.c_str(), host, &port, path, &ssl))
return;
static char buff[2048];
snprintf(buff, sizeof(buff),
"GET %s HTTP/1.1\r\n"
"Host: %s\r\n"
"User-Agent: Mozilla/4.5 [en] (1/1)\r\n"
"Accept: */*\r\n"
"%s" "\r\n", path, host,
"Connection: close\r\n");
LOG4CXX_INFO(logger, "Sending " << buff << "\n");
conn->write(Swift::createSafeByteArray(buff));
}
}
void HTTPFetch::_disconnected(boost::shared_ptr<Swift::Connection> conn) {
conn->onConnectFinished.disconnect_all_slots();
conn->onDisconnected.disconnect_all_slots();
conn->onDataRead.disconnect_all_slots();
if (m_buffer.size() == 0) {
onURLFetched("");
}
else {
std::string img = m_buffer.substr(m_buffer.find("\r\n\r\n") + 4);
onURLFetched(img);
}
}
void HTTPFetch::_read(boost::shared_ptr<Swift::Connection> conn, boost::shared_ptr<Swift::SafeByteArray> data) {
std::string d(data->begin(), data->end());
// std::cout << d << "\n";
std::string img = d.substr(d.find("\r\n\r\n") + 4);
if (d.find("Location: ") == std::string::npos) {
m_buffer += d;
}
else {
d = d.substr(d.find("Location: ") + 10);
if (d.find("\r") == std::string::npos) {
d = d.substr(0, d.find("\n"));
}
else {
d = d.substr(0, d.find("\r"));
}
LOG4CXX_INFO(logger, "Next url is '" << d << "'");
fetchURL(d);
conn->onConnectFinished.disconnect_all_slots();
conn->onDisconnected.disconnect_all_slots();
conn->onDataRead.disconnect_all_slots();
}
}
bool HTTPFetch::fetchURL(const std::string &url) {
char host[255];
int port = 80;
char path[255];
char buff[1024];
int ssl = 0;
if (!url_to_host_port_path(url.c_str(), host, &port, path, &ssl)) {
LOG4CXX_ERROR(logger, "Invalid URL " << url);
return false;
}
LOG4CXX_INFO(logger, "Connecting to " << host << ":" << port);
boost::asio::ip::tcp::resolver resolver(*m_ioService->getIOService());
boost::asio::ip::tcp::resolver::query query(host, "");
boost::asio::ip::address address;
for(boost::asio::ip::tcp::resolver::iterator i = resolver.resolve(query); i != boost::asio::ip::tcp::resolver::iterator(); ++i) {
boost::asio::ip::tcp::endpoint end = *i;
address = end.address();
break;
}
boost::shared_ptr<Swift::Connection> conn = m_factory->createConnection();
conn->onConnectFinished.connect(boost::bind(&HTTPFetch::_connected, this, conn, url, _1));
conn->onDisconnected.connect(boost::bind(&HTTPFetch::_disconnected, this, conn));
conn->onDataRead.connect(boost::bind(&HTTPFetch::_read, this, conn, _1));
conn->connect(Swift::HostAddressPort(Swift::HostAddress(address), port));
return true;
}

View file

@ -0,0 +1,37 @@
#pragma once
// Transport includes
#include "transport/config.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
// Swiften
#include "Swiften/Swiften.h"
#include "Swiften/TLS/OpenSSL/OpenSSLContextFactory.h"
// Boost
#include <boost/algorithm/string.hpp>
using namespace boost::filesystem;
using namespace boost::program_options;
using namespace Transport;
class HTTPFetch {
public:
HTTPFetch(Swift::BoostIOServiceThread *ioSerice, Swift::ConnectionFactory *factory);
virtual ~HTTPFetch();
bool fetchURL(const std::string &url);
boost::signal<void (const std::string &data)> onURLFetched;
private:
void _connected(boost::shared_ptr<Swift::Connection> conn, const std::string url, bool error);
void _disconnected(boost::shared_ptr<Swift::Connection> conn);
void _read(boost::shared_ptr<Swift::Connection> conn, boost::shared_ptr<Swift::SafeByteArray> data);
Swift::BoostIOServiceThread *m_ioService;
Swift::ConnectionFactory *m_factory;
std::string m_buffer;
bool m_afterHeader;
};

762
backends/libyahoo2/main.cpp Normal file
View file

@ -0,0 +1,762 @@
// Transport includes
#include "transport/config.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
// Yahoo2
#include <yahoo2.h>
#include <yahoo2_callbacks.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include "yahoohandler.h"
#include "yahoolocalaccount.h"
#include "httpfetch.h"
// Swiften
#include "Swiften/Swiften.h"
#include "Swiften/Network/TLSConnectionFactory.h"
#include "Swiften/TLS/OpenSSL/OpenSSLContextFactory.h"
#ifndef _WIN32
// for signal handler
#include "unistd.h"
#include "signal.h"
#include "sys/wait.h"
#include "sys/signal.h"
#endif
// Boost
#include <boost/algorithm/string.hpp>
using namespace boost::filesystem;
using namespace boost::program_options;
using namespace Transport;
class YahooHandler;
class YahooLocalAccount;
static std::string *currently_read_data;
static YahooLocalAccount *currently_writting_account;
YahooHandler::YahooHandler(YahooLocalAccount *account, int conn_tag, int handler_tag, void *data, yahoo_input_condition cond) :
handler_tag(handler_tag), conn_tag(conn_tag), data(data), cond(cond), remove_later(false), account(account) {}
YahooHandler::~YahooHandler() {}
void YahooHandler::ready(std::string *buffer) {
if (cond == YAHOO_INPUT_WRITE) {
YahooLocalAccount *old = currently_writting_account;
currently_writting_account = account;
yahoo_write_ready(account->id, (void *) conn_tag, data);
currently_writting_account = old;
}
else {
if (!buffer) {
return;
}
// yahoo_read_ready calls ext_yahoo_read(...) in a loop, so we just have to choose proper buffer from which will
// that method read. We do that by static currently_read_data pointer.
currently_read_data = buffer;
// libyahoo2 reads data per 1024 bytes, so if we still have some data after the first ext_yahoo_read call,
// we have to call yahoo_read_ready again...
do {
yahoo_read_ready(account->id, (void *) conn_tag, data);
} while (currently_read_data->size() != 0);
}
}
typedef struct {
std::string yahoo_id;
std::string name;
int status;
int away;
std::string msg;
std::string group;
} yahoo_account;
typedef struct {
int id;
char *label;
} yahoo_idlabel;
typedef struct {
int id;
char *who;
} yahoo_authorize_data;
DEFINE_LOGGER(logger, "Yahoo2");
// eventloop
Swift::SimpleEventLoop *loop_;
// Plugin
class YahooPlugin;
YahooPlugin * np = NULL;
class YahooPlugin : public NetworkPlugin {
public:
Swift::BoostNetworkFactories *m_factories;
Swift::OpenSSLContextFactory *m_sslFactory;
Swift::TLSConnectionFactory *m_tlsFactory;
Swift::BoostIOServiceThread m_boostIOServiceThread;
boost::shared_ptr<Swift::Connection> m_conn;
YahooPlugin(Config *config, Swift::SimpleEventLoop *loop, const std::string &host, int port) : NetworkPlugin() {
this->config = config;
m_factories = new Swift::BoostNetworkFactories(loop);
m_sslFactory = new Swift::OpenSSLContextFactory();
m_tlsFactory = new Swift::TLSConnectionFactory(m_sslFactory, m_factories->getConnectionFactory());
m_conn = m_factories->getConnectionFactory()->createConnection();
m_conn->onDataRead.connect(boost::bind(&YahooPlugin::_handleDataRead, this, _1));
m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(host), port));
LOG4CXX_INFO(logger, "Starting the plugin.");
}
// NetworkPlugin uses this method to send the data to networkplugin server
void sendData(const std::string &string) {
m_conn->write(Swift::createSafeByteArray(string));
}
// This method has to call handleDataRead with all received data from network plugin server
void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
std::string d(data->begin(), data->end());
handleDataRead(d);
}
void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
YahooLocalAccount *account = new YahooLocalAccount(user, legacyName, password);
m_users[user] = account;
m_ids[account->id] = user;
LOG4CXX_INFO(logger, user << ": Logging in the user as " << legacyName << " with id=" << account->id);
account->login();
}
void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
YahooLocalAccount *account = m_users[user];
if (account) {
yahoo_logoff(account->id);
m_ids.erase(account->id);
m_users.erase(user);
delete account;
}
}
void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml = "") {
YahooLocalAccount *account = m_users[user];
if (account) {
LOG4CXX_INFO(logger, "Sending message from " << user << " to " << legacyName << ": " << message << ".");
yahoo_send_im(account->id, NULL, legacyName.c_str(), message.c_str(), 0, 0);
_yahoo_write_ready(account);
}
}
void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups) {
LOG4CXX_INFO(logger, user << ": Added buddy " << buddyName << ".");
handleBuddyChanged(user, buddyName, alias, groups, pbnetwork::STATUS_ONLINE);
}
void _avatar_fetched(HTTPFetch *fetch, int account_id, unsigned int id, const std::string &img) {
handleVCard(m_ids[account_id], id, "", "", "", img);
delete fetch;
}
void handleVCardRequest(const std::string &user, const std::string &legacyName, unsigned int id) {
YahooLocalAccount *account = m_users[user];
if (!account) {
return;
}
if (account->urls.find(legacyName) == account->urls.end()) {
return;
}
HTTPFetch *fetch = new HTTPFetch(&m_boostIOServiceThread, m_factories->getConnectionFactory());
fetch->onURLFetched.connect(boost::bind(&YahooPlugin::_avatar_fetched, this, fetch, account->id, id, _1));
fetch->fetchURL(account->urls[legacyName]);
}
void handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups) {
}
YahooLocalAccount *getAccount(int id) {
return m_users[m_ids[id]];
}
void _yahoo_remove_account(YahooLocalAccount *account) {
m_ids.erase(account->id);
m_users.erase(account->user);
delete account;
}
void _yahoo_connect_finished(YahooLocalAccount *account, yahoo_connect_callback callback, void *data, int conn_tag, bool error) {
currently_writting_account = account;
if (error) {
LOG4CXX_ERROR(logger, account->user << ": Connection error!");
callback(NULL, 0, data);
// np->handleDisconnected(user, 0, "Connection error.");
}
else {
LOG4CXX_INFO(logger, account->user << ": Connected");
// We will have dangling pointer here, but we can't pass boost::shared_ptr here...
callback((void *) conn_tag, 0, data);
}
}
void _yahoo_write_ready(YahooLocalAccount *account) {
// Find all WRITE handlers and inform that they really can write.
for (std::map<int, YahooHandler *>::iterator it = account->handlers.begin(); it != account->handlers.end(); it++) {
if (it->second->cond == YAHOO_INPUT_WRITE && !it->second->remove_later) {
it->second->ready();
}
}
}
void _yahoo_data_read(YahooLocalAccount *account, int conn_tag, boost::shared_ptr<Swift::SafeByteArray> data) {
std::string d(data->begin(), data->end());
// Find the handler that handles READing for this conn_tag
for (std::map<int, YahooHandler *>::iterator it = account->handlers_per_conn[conn_tag].begin(); it != account->handlers_per_conn[conn_tag].end(); it++) {
if (it->second->cond == YAHOO_INPUT_READ && !it->second->remove_later) {
std::string cpy(d);
it->second->ready(&cpy);
// Look like libyahoo2 needs to be informed it can write to socket after the read
// even we have informed it before...
_yahoo_write_ready(account);
break;
}
}
account->removeOldHandlers();
}
void _yahoo_data_written(YahooLocalAccount *account, int conn_tag) {
LOG4CXX_INFO(logger, "data written");
for (std::map<int, YahooHandler *>::iterator it = account->handlers_per_conn[conn_tag].begin(); it != account->handlers_per_conn[conn_tag].end(); it++) {
if (it->second->cond == YAHOO_INPUT_WRITE) {
it->second->ready();
}
}
account->removeOldHandlers();
}
void _yahoo_disconnected(YahooLocalAccount *account, int conn_tag, const boost::optional<Swift::Connection::Error> &error) {
for (std::map<int, YahooHandler *>::iterator it = account->handlers_per_conn[conn_tag].begin(); it != account->handlers_per_conn[conn_tag].end(); it++) {
if (it->second->cond == YAHOO_INPUT_READ && !it->second->remove_later) {
std::string cpy;
it->second->ready(&cpy);
_yahoo_write_ready(account);
break;
}
}
account->removeConn(conn_tag);
}
int _yahoo_connect_async(int id, const char *host, int port, yahoo_connect_callback callback, void *data, int use_ssl) {
YahooLocalAccount *account = getAccount(id);
if (!account) {
LOG4CXX_ERROR(logger, "Unknown account id=" << id);
return -1;
}
boost::asio::ip::tcp::resolver resolver(*m_boostIOServiceThread.getIOService());
boost::asio::ip::tcp::resolver::query query(host, "");
boost::asio::ip::address address;
for(boost::asio::ip::tcp::resolver::iterator i = resolver.resolve(query); i != boost::asio::ip::tcp::resolver::iterator(); ++i) {
boost::asio::ip::tcp::endpoint end = *i;
address = end.address();
break;
}
LOG4CXX_INFO(logger, m_ids[id] << ": Connecting " << host << ":" << port);
int tag = account->conn_tag++;
if (use_ssl) {
account->conns[tag] = m_tlsFactory->createConnection();
}
else {
account->conns[tag] = m_factories->getConnectionFactory()->createConnection();
}
account->conns[tag]->onConnectFinished.connect(boost::bind(&YahooPlugin::_yahoo_connect_finished, this, account, callback, data, tag, _1));
account->conns[tag]->onDisconnected.connect(boost::bind(&YahooPlugin::_yahoo_disconnected, this, account, tag, _1));
account->conns[tag]->onDataRead.connect(boost::bind(&YahooPlugin::_yahoo_data_read, this, account, tag, _1));
account->conns[tag]->onDataWritten.connect(boost::bind(&YahooPlugin::_yahoo_data_written, this, account, tag));
account->conns[tag]->connect(Swift::HostAddressPort(Swift::HostAddress(address), port));
return tag;
}
private:
Config *config;
std::map<std::string, YahooLocalAccount *> m_users;
std::map<int, std::string> m_ids;
};
static void spectrum_sigchld_handler(int sig)
{
int status;
pid_t pid;
do {
pid = waitpid(-1, &status, WNOHANG);
} while (pid != 0 && pid != (pid_t)-1);
if ((pid == (pid_t) - 1) && (errno != ECHILD)) {
char errmsg[BUFSIZ];
snprintf(errmsg, BUFSIZ, "Warning: waitpid() returned %d", pid);
perror(errmsg);
}
}
static void ext_yahoo_got_conf_invite(int id, const char *me, const char *who, const char *room, const char *msg, YList *members) {
}
static void ext_yahoo_conf_userdecline(int id, const char *me, const char *who, const char *room, const char *msg) {
}
static void ext_yahoo_conf_userjoin(int id, const char *me, const char *who, const char *room) {
}
static void ext_yahoo_conf_userleave(int id, const char *me, const char *who, const char *room) {
}
static void ext_yahoo_conf_message(int id, const char *me, const char *who, const char *room, const char *msg, int utf8) {
}
static void ext_yahoo_chat_cat_xml(int id, const char *xml) {
}
static void ext_yahoo_chat_join(int id, const char *me, const char *room, const char * topic, YList *members, void *fd) {
}
static void ext_yahoo_chat_userjoin(int id, const char *me, const char *room, struct yahoo_chat_member *who) {
}
static void ext_yahoo_chat_userleave(int id, const char *me, const char *room, const char *who) {
}
static void ext_yahoo_chat_message(int id, const char *me, const char *who, const char *room, const char *msg, int msgtype, int utf8) {
}
static void ext_yahoo_status_changed(int id, const char *who, int stat, const char *msg, int away, int idle, int mobile) {
YahooLocalAccount *account = np->getAccount(id);
if (!account) {
return;
}
LOG4CXX_INFO(logger, account->user << ": " << who << " status changed");
pbnetwork::StatusType status = pbnetwork::STATUS_NONE;
switch (stat) {
case YAHOO_STATUS_AVAILABLE:
status = pbnetwork::STATUS_ONLINE;
break;
case YAHOO_STATUS_NOTATHOME:
case YAHOO_STATUS_NOTATDESK:
case YAHOO_STATUS_NOTINOFFICE:
case YAHOO_STATUS_ONPHONE:
case YAHOO_STATUS_ONVACATION:
case YAHOO_STATUS_OUTTOLUNCH:
case YAHOO_STATUS_STEPPEDOUT:
status = pbnetwork::STATUS_AWAY;
break;
case YAHOO_STATUS_BRB:
status = pbnetwork::STATUS_XA;
break;
case YAHOO_STATUS_BUSY:
status = pbnetwork::STATUS_DND;
break;
case YAHOO_STATUS_OFFLINE:
status = pbnetwork::STATUS_NONE;
break;
default:
status = pbnetwork::STATUS_ONLINE;
break;
}
yahoo_buddyicon_request(id, who);
np->_yahoo_write_ready(account);
np->handleBuddyChanged(account->user, who, "", std::vector<std::string>(), status, msg ? msg : "");
}
static void ext_yahoo_got_buddies(int id, YList * buds) {
YahooLocalAccount *account = np->getAccount(id);
if (!account) {
return;
}
LOG4CXX_INFO(logger, account->user << ": Got buddy list");
for(; buds; buds = buds->next) {
struct yahoo_buddy *bud = (struct yahoo_buddy *) buds->data;
std::vector<std::string> groups;
groups.push_back(bud->group);
np->handleBuddyChanged(account->user, bud->id, bud->real_name ? bud->real_name : "", groups, pbnetwork::STATUS_NONE);
}
// yahoo_set_away(id, YAHOO_STATUS_AVAILABLE, "", 1);
np->_yahoo_write_ready(account);
np->handleConnected(account->user);
}
static void ext_yahoo_got_ignore(int id, YList * igns)
{
}
static void ext_yahoo_got_buzz(int id, const char *me, const char *who, long tm) {
}
static void ext_yahoo_got_im(int id, const char *me, const char *who, const char *msg, long tm, int stat, int utf8) {
YahooLocalAccount *account = np->getAccount(id);
if (!account) {
return;
}
np->handleMessage(account->user, who, msg);
}
static void ext_yahoo_rejected(int id, const char *who, const char *msg) {
}
static void ext_yahoo_contact_added(int id, const char *myid, const char *who, const char *msg) {
}
static void ext_yahoo_typing_notify(int id, const char* me, const char *who, int stat) {
}
static void ext_yahoo_game_notify(int id, const char *me, const char *who, int stat, const char *msg)
{
}
static void ext_yahoo_mail_notify(int id, const char *from, const char *subj, int cnt) {
}
static void ext_yahoo_got_webcam_image(int id, const char *who, const unsigned char *image, unsigned int image_size, unsigned int real_size, unsigned int timestamp) {
}
static void ext_yahoo_webcam_viewer(int id, const char *who, int connect) {
}
static void ext_yahoo_webcam_closed(int id, const char *who, int reason) {
}
static void ext_yahoo_webcam_data_request(int id, int send) {
}
static void ext_yahoo_webcam_invite(int id, const char *me, const char *from) {
}
static void ext_yahoo_webcam_invite_reply(int id, const char *me, const char *from, int accept) {
}
static void ext_yahoo_system_message(int id, const char *me, const char *who, const char *msg) {
}
static void ext_yahoo_got_cookies(int id) {
}
static void ext_yahoo_login_response(int id, int succ, const char *url) {
YahooLocalAccount *account = np->getAccount(id);
if (!account) {
return;
}
if (succ == YAHOO_LOGIN_OK) {
account->status = yahoo_current_status(id);
// We will fire handleConnected in Got Buddy List.
return;
}
else if (succ == YAHOO_LOGIN_UNAME) {
np->handleDisconnected(account->user, 0, "Could not log into Yahoo service - username not recognised. Please verify that your username is correctly typed.");
}
else if (succ == YAHOO_LOGIN_PASSWD) {
np->handleDisconnected(account->user, 0, "Could not log into Yahoo service - password incorrect. Please verify that your password is correctly typed.");
}
else if (succ == YAHOO_LOGIN_LOCK) {
np->handleDisconnected(account->user, 0, std::string("Could not log into Yahoo service. Your account has been locked. Visit ") + url + " to reactivate it.");
}
else if (succ == YAHOO_LOGIN_DUPL) {
np->handleDisconnected(account->user, 0, "You have been logged out of the yahoo service, possibly due to a duplicate login.");
}
else if (succ == YAHOO_LOGIN_SOCK) {
np->handleDisconnected(account->user, 0, "The server closed the socket.");
}
else {
np->handleDisconnected(account->user, 0, "Could not log in, unknown reason.");
}
np->handleLogoutRequest(account->user, "");
}
static void ext_yahoo_error(int id, const char *_err, int fatal, int num) {
std::string err(_err);
std::string msg("Yahoo Error: ");
msg += err + " - ";
switch(num) {
case E_UNKNOWN:
msg += "unknown error " + err;
break;
case E_CUSTOM:
msg += "custom error " + err;
break;
case E_CONFNOTAVAIL:
msg += err + " is not available for the conference";
break;
case E_IGNOREDUP:
msg += err + " is already ignored";
break;
case E_IGNORENONE:
msg += err +" is not in the ignore list";
break;
case E_IGNORECONF:
msg += err + " is in buddy list - cannot ignore ";
break;
case E_SYSTEM:
msg += "system error " + err;
break;
case E_CONNECTION:
msg += err + "server connection error %s";
break;
}
LOG4CXX_ERROR(logger, msg);
YahooLocalAccount *account = np->getAccount(id);
if (!account) {
return;
}
if(fatal) {
np->handleDisconnected(account->user, 0, msg);
np->handleLogoutRequest(account->user, "");
}
}
static int ext_yahoo_connect(const char *host, int port) {
return -1;
}
static int ext_yahoo_add_handler(int id, void *fd, yahoo_input_condition cond, void *data) {
YahooLocalAccount *account = np->getAccount(id);
if (!account) {
return -1;
}
int conn_tag = (unsigned long) fd;
YahooHandler *handler = new YahooHandler(account, conn_tag, account->handler_tag++, data, cond);
account->addHandler(handler);
// We are ready to write right now, so why not...
handler->ready();
return handler->handler_tag;
}
static void ext_yahoo_remove_handler(int id, int tag) {
YahooLocalAccount *account = np->getAccount(id);
if (!account) {
return;
}
if (account->handlers.find(tag) == account->handlers.end()) {
return;
}
YahooHandler *handler = account->handlers[tag];
handler->remove_later = true;
}
static int ext_yahoo_write(void *fd, char *buf, int len) {
int conn_tag = (unsigned long) fd;
YahooLocalAccount *account = currently_writting_account;
std::string string(buf, len);
account->conns[conn_tag]->write(Swift::createSafeByteArray(string));
return len;
}
static int ext_yahoo_read(void *fd, char *buf, int len) {
if (currently_read_data->size() < len) {
len = currently_read_data->size();
}
memcpy(buf, currently_read_data->c_str(), len);
currently_read_data->erase(0, len);
return len;
}
static void ext_yahoo_close(void *fd) {
// No need to do anything here. We close it properly in _yahoo_disconnected(...);
}
static int ext_yahoo_connect_async(int id, const char *host, int port, yahoo_connect_callback callback, void *data, int use_ssl) {
return np->_yahoo_connect_async(id, host, port, callback, data, use_ssl);
}
static void ext_yahoo_got_file(int id, const char *me, const char *who, const char *msg, const char *fname, unsigned long fesize, char *trid) {
}
static void ext_yahoo_file_transfer_done(int id, int response, void *data) {
}
static char *ext_yahoo_get_ip_addr(const char *domain) {
return NULL;
}
static void ext_yahoo_got_ft_data(int id, const unsigned char *in, int count, void *data) {
}
static void ext_yahoo_got_identities(int id, YList * ids) {
}
static void ext_yahoo_chat_yahoologout(int id, const char *me) {
}
static void ext_yahoo_chat_yahooerror(int id, const char *me) {
}
static void ext_yahoo_got_ping(int id, const char *errormsg){
}
static void ext_yahoo_got_search_result(int id, int found, int start, int total, YList *contacts) {
}
static void ext_yahoo_got_buddyicon_checksum(int id, const char *a, const char *b, int checksum) {
LOG4CXX_INFO(logger, "got buddyicon_checksum");
}
static void ext_yahoo_got_buddy_change_group(int id, const char *me, const char *who, const char *old_group, const char *new_group) {
}
static void ext_yahoo_got_buddyicon(int id, const char *me, const char *who, const char *url, int checksum) {
YahooLocalAccount *account = np->getAccount(id);
if (!account) {
return;
}
LOG4CXX_INFO(logger, account->user << ": got buddyicon of " << who);
account->urls[who] = url;
}
static void ext_yahoo_buddyicon_uploaded(int id, const char *url) {
}
static void ext_yahoo_got_buddyicon_request(int id, const char *me, const char *who) {
LOG4CXX_INFO(logger, "got buddyicon_request");
}
static int ext_yahoo_log(const char *fmt,...)
{
static char log[8192];
static std::string buffered;
va_list ap;
va_start(ap, fmt);
vsnprintf(log, 8191, fmt, ap);
buffered += log;
if (buffered.find('\n') != std::string::npos) {
buffered.erase(buffered.find('\n'), 1);
LOG4CXX_INFO(logger, buffered);
buffered.clear();
}
fflush(stderr);
va_end(ap);
return 0;
}
static void register_callbacks()
{
static struct yahoo_callbacks yc;
yc.ext_yahoo_login_response = ext_yahoo_login_response;
yc.ext_yahoo_got_buddies = ext_yahoo_got_buddies;
yc.ext_yahoo_got_ignore = ext_yahoo_got_ignore;
yc.ext_yahoo_got_identities = ext_yahoo_got_identities;
yc.ext_yahoo_got_cookies = ext_yahoo_got_cookies;
yc.ext_yahoo_status_changed = ext_yahoo_status_changed;
yc.ext_yahoo_got_im = ext_yahoo_got_im;
yc.ext_yahoo_got_buzz = ext_yahoo_got_buzz;
yc.ext_yahoo_got_conf_invite = ext_yahoo_got_conf_invite;
yc.ext_yahoo_conf_userdecline = ext_yahoo_conf_userdecline;
yc.ext_yahoo_conf_userjoin = ext_yahoo_conf_userjoin;
yc.ext_yahoo_conf_userleave = ext_yahoo_conf_userleave;
yc.ext_yahoo_conf_message = ext_yahoo_conf_message;
yc.ext_yahoo_chat_cat_xml = ext_yahoo_chat_cat_xml;
yc.ext_yahoo_chat_join = ext_yahoo_chat_join;
yc.ext_yahoo_chat_userjoin = ext_yahoo_chat_userjoin;
yc.ext_yahoo_chat_userleave = ext_yahoo_chat_userleave;
yc.ext_yahoo_chat_message = ext_yahoo_chat_message;
yc.ext_yahoo_chat_yahoologout = ext_yahoo_chat_yahoologout;
yc.ext_yahoo_chat_yahooerror = ext_yahoo_chat_yahooerror;
yc.ext_yahoo_got_webcam_image = ext_yahoo_got_webcam_image;
yc.ext_yahoo_webcam_invite = ext_yahoo_webcam_invite;
yc.ext_yahoo_webcam_invite_reply = ext_yahoo_webcam_invite_reply;
yc.ext_yahoo_webcam_closed = ext_yahoo_webcam_closed;
yc.ext_yahoo_webcam_viewer = ext_yahoo_webcam_viewer;
yc.ext_yahoo_webcam_data_request = ext_yahoo_webcam_data_request;
yc.ext_yahoo_got_file = ext_yahoo_got_file;
yc.ext_yahoo_got_ft_data = ext_yahoo_got_ft_data;
yc.ext_yahoo_get_ip_addr = ext_yahoo_get_ip_addr;
yc.ext_yahoo_file_transfer_done = ext_yahoo_file_transfer_done;
yc.ext_yahoo_contact_added = ext_yahoo_contact_added;
yc.ext_yahoo_rejected = ext_yahoo_rejected;
yc.ext_yahoo_typing_notify = ext_yahoo_typing_notify;
yc.ext_yahoo_game_notify = ext_yahoo_game_notify;
yc.ext_yahoo_mail_notify = ext_yahoo_mail_notify;
yc.ext_yahoo_got_search_result = ext_yahoo_got_search_result;
yc.ext_yahoo_system_message = ext_yahoo_system_message;
yc.ext_yahoo_error = ext_yahoo_error;
yc.ext_yahoo_log = ext_yahoo_log;
yc.ext_yahoo_add_handler = ext_yahoo_add_handler;
yc.ext_yahoo_remove_handler = ext_yahoo_remove_handler;
yc.ext_yahoo_connect = ext_yahoo_connect;
yc.ext_yahoo_connect_async = ext_yahoo_connect_async;
yc.ext_yahoo_read = ext_yahoo_read;
yc.ext_yahoo_write = ext_yahoo_write;
yc.ext_yahoo_close = ext_yahoo_close;
yc.ext_yahoo_got_buddyicon = ext_yahoo_got_buddyicon;
yc.ext_yahoo_got_buddyicon_checksum = ext_yahoo_got_buddyicon_checksum;
yc.ext_yahoo_buddyicon_uploaded = ext_yahoo_buddyicon_uploaded;
yc.ext_yahoo_got_buddyicon_request = ext_yahoo_got_buddyicon_request;
yc.ext_yahoo_got_ping = ext_yahoo_got_ping;
yc.ext_yahoo_got_buddy_change_group = ext_yahoo_got_buddy_change_group;
yahoo_register_callbacks(&yc);
}
int main (int argc, char* argv[]) {
std::string host;
int port;
#ifndef _WIN32
if (signal(SIGCHLD, spectrum_sigchld_handler) == SIG_ERR) {
std::cout << "SIGCHLD handler can't be set\n";
return -1;
}
#endif
std::string error;
Config *cfg = Config::createFromArgs(argc, argv, error, host, port);
if (cfg == NULL) {
std::cerr << error;
return 1;
}
Logging::initBackendLogging(cfg);
register_callbacks();
yahoo_set_log_level(YAHOO_LOG_DEBUG);
Swift::SimpleEventLoop eventLoop;
loop_ = &eventLoop;
np = new YahooPlugin(cfg, &eventLoop, host, port);
loop_->run();
return 0;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,208 @@
/* One way encryption based on MD5 sum.
Copyright (C) 1996, 1997, 1999, 2000 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
/* warmenhoven took this file and made it work with the md5.[ch] we
* already had. isn't that lovely. people should just use linux or
* freebsd, crypt works properly on those systems. i hate solaris */
#if HAVE_CONFIG_H
# include <config.h>
#endif
#if HAVE_STRING_H
# include <string.h>
#elif HAVE_STRINGS_H
# include <strings.h>
#endif
#include <stdlib.h>
#include "yahoo_util.h"
#include "md5.h"
/* Define our magic string to mark salt for MD5 "encryption"
replacement. This is meant to be the same as for other MD5 based
encryption implementations. */
static const char md5_salt_prefix[] = "$1$";
/* Table with characters for base64 transformation. */
static const char b64t[64] =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char *yahoo_crypt(char *key, char *salt)
{
char *buffer = NULL;
int buflen = 0;
int needed = 3 + strlen(salt) + 1 + 26 + 1;
md5_byte_t alt_result[16];
md5_state_t ctx;
md5_state_t alt_ctx;
size_t salt_len;
size_t key_len;
size_t cnt;
char *cp;
if (buflen < needed) {
buflen = needed;
if ((buffer = realloc(buffer, buflen)) == NULL)
return NULL;
}
/* Find beginning of salt string. The prefix should normally always
be present. Just in case it is not. */
if (strncmp(md5_salt_prefix, salt, sizeof(md5_salt_prefix) - 1) == 0)
/* Skip salt prefix. */
salt += sizeof(md5_salt_prefix) - 1;
salt_len = MIN(strcspn(salt, "$"), 8);
key_len = strlen(key);
/* Prepare for the real work. */
md5_init(&ctx);
/* Add the key string. */
md5_append(&ctx, (md5_byte_t *)key, key_len);
/* Because the SALT argument need not always have the salt prefix we
add it separately. */
md5_append(&ctx, (md5_byte_t *)md5_salt_prefix,
sizeof(md5_salt_prefix) - 1);
/* The last part is the salt string. This must be at most 8
characters and it ends at the first `$' character (for
compatibility which existing solutions). */
md5_append(&ctx, (md5_byte_t *)salt, salt_len);
/* Compute alternate MD5 sum with input KEY, SALT, and KEY. The
final result will be added to the first context. */
md5_init(&alt_ctx);
/* Add key. */
md5_append(&alt_ctx, (md5_byte_t *)key, key_len);
/* Add salt. */
md5_append(&alt_ctx, (md5_byte_t *)salt, salt_len);
/* Add key again. */
md5_append(&alt_ctx, (md5_byte_t *)key, key_len);
/* Now get result of this (16 bytes) and add it to the other
context. */
md5_finish(&alt_ctx, alt_result);
/* Add for any character in the key one byte of the alternate sum. */
for (cnt = key_len; cnt > 16; cnt -= 16)
md5_append(&ctx, alt_result, 16);
md5_append(&ctx, alt_result, cnt);
/* For the following code we need a NUL byte. */
alt_result[0] = '\0';
/* The original implementation now does something weird: for every 1
bit in the key the first 0 is added to the buffer, for every 0
bit the first character of the key. This does not seem to be
what was intended but we have to follow this to be compatible. */
for (cnt = key_len; cnt > 0; cnt >>= 1)
md5_append(&ctx,
(cnt & 1) != 0 ? alt_result : (md5_byte_t *)key, 1);
/* Create intermediate result. */
md5_finish(&ctx, alt_result);
/* Now comes another weirdness. In fear of password crackers here
comes a quite long loop which just processes the output of the
previous round again. We cannot ignore this here. */
for (cnt = 0; cnt < 1000; ++cnt) {
/* New context. */
md5_init(&ctx);
/* Add key or last result. */
if ((cnt & 1) != 0)
md5_append(&ctx, (md5_byte_t *)key, key_len);
else
md5_append(&ctx, alt_result, 16);
/* Add salt for numbers not divisible by 3. */
if (cnt % 3 != 0)
md5_append(&ctx, (md5_byte_t *)salt, salt_len);
/* Add key for numbers not divisible by 7. */
if (cnt % 7 != 0)
md5_append(&ctx, (md5_byte_t *)key, key_len);
/* Add key or last result. */
if ((cnt & 1) != 0)
md5_append(&ctx, alt_result, 16);
else
md5_append(&ctx, (md5_byte_t *)key, key_len);
/* Create intermediate result. */
md5_finish(&ctx, alt_result);
}
/* Now we can construct the result string. It consists of three
parts. */
strncpy(buffer, md5_salt_prefix, MAX(0, buflen));
cp = buffer + strlen(buffer);
buflen -= sizeof(md5_salt_prefix);
strncpy(cp, salt, MIN((size_t) buflen, salt_len));
cp = cp + strlen(cp);
buflen -= MIN((size_t) buflen, salt_len);
if (buflen > 0) {
*cp++ = '$';
--buflen;
}
#define b64_from_24bit(B2, B1, B0, N) \
do { \
unsigned int w = ((B2) << 16) | ((B1) << 8) | (B0); \
int n = (N); \
while (n-- > 0 && buflen > 0) { \
*cp++ = b64t[w & 0x3f]; \
--buflen; \
w >>= 6; \
}\
} while (0)
b64_from_24bit(alt_result[0], alt_result[6], alt_result[12], 4);
b64_from_24bit(alt_result[1], alt_result[7], alt_result[13], 4);
b64_from_24bit(alt_result[2], alt_result[8], alt_result[14], 4);
b64_from_24bit(alt_result[3], alt_result[9], alt_result[15], 4);
b64_from_24bit(alt_result[4], alt_result[10], alt_result[5], 4);
b64_from_24bit(0, 0, alt_result[11], 2);
if (buflen <= 0) {
FREE(buffer);
} else
*cp = '\0'; /* Terminate the string. */
/* Clear the buffer for the intermediate result so that people
attaching to processes or reading core dumps cannot get any
information. We do it in this way to clear correct_words[]
inside the MD5 implementation as well. */
md5_init(&ctx);
md5_finish(&ctx, alt_result);
memset(&ctx, '\0', sizeof(ctx));
memset(&alt_ctx, '\0', sizeof(alt_ctx));
return buffer;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,405 @@
/*
Copyright (C) 1999 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
*/
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321.
It is derived directly from the text of the RFC and not from the
reference implementation.
The original and principal author of md5.c is L. Peter Deutsch
<ghost@aladdin.com>. Other authors are noted in the change history
that follows (in reverse chronological order):
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include "md5.h"
#if STDC_HEADERS
# include <string.h>
#else
# if !HAVE_STRCHR
# define strchr index
# define strrchr rindex
# endif
char *strchr(), *strrchr();
# if !HAVE_MEMCPY
# define memcpy(d, s, n) bcopy ((s), (d), (n))
# define memmove(d, s, n) bcopy ((s), (d), (n))
# endif
#endif
#ifdef TEST
/*
* Compile with -DTEST to create a self-contained executable test program.
* The test program should print out the same values as given in section
* A.5 of RFC 1321, reproduced below.
*/
main()
{
static const char *const test[7] = {
"", /*d41d8cd98f00b204e9800998ecf8427e */
"945399884.61923487334tuvga", /*0cc175b9c0f1b6a831c399e269772661 */
"abc", /*900150983cd24fb0d6963f7d28e17f72 */
"message digest", /*f96b697d7cb7938d525a2f31aaf161d0 */
"abcdefghijklmnopqrstuvwxyz", /*c3fcd3d76192e4007dfb496cca67e13b */
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
/*d174ab98d277d9f5a5611c2c9f419d9f */
"12345678901234567890123456789012345678901234567890123456789012345678901234567890" /*57edf4a22be3c955ac49da2e2107b67a */
};
int i;
for (i = 0; i < 7; ++i) {
md5_state_t state;
md5_byte_t digest[16];
int di;
md5_init(&state);
md5_append(&state, (const md5_byte_t *)test[i],
strlen(test[i]));
md5_finish(&state, digest);
printf("MD5 (\"%s\") = ", test[i]);
for (di = 0; di < 16; ++di)
printf("%02x", digest[di]);
printf("\n");
}
return 0;
}
#endif /* TEST */
/*
* For reference, here is the program that computed the T values.
*/
#if 0
#include <math.h>
main()
{
int i;
for (i = 1; i <= 64; ++i) {
unsigned long v =
(unsigned long)(4294967296.0 * fabs(sin((double)i)));
printf("#define T%d 0x%08lx\n", i, v);
}
return 0;
}
#endif
/*
* End of T computation program.
*/
#define T1 0xd76aa478
#define T2 0xe8c7b756
#define T3 0x242070db
#define T4 0xc1bdceee
#define T5 0xf57c0faf
#define T6 0x4787c62a
#define T7 0xa8304613
#define T8 0xfd469501
#define T9 0x698098d8
#define T10 0x8b44f7af
#define T11 0xffff5bb1
#define T12 0x895cd7be
#define T13 0x6b901122
#define T14 0xfd987193
#define T15 0xa679438e
#define T16 0x49b40821
#define T17 0xf61e2562
#define T18 0xc040b340
#define T19 0x265e5a51
#define T20 0xe9b6c7aa
#define T21 0xd62f105d
#define T22 0x02441453
#define T23 0xd8a1e681
#define T24 0xe7d3fbc8
#define T25 0x21e1cde6
#define T26 0xc33707d6
#define T27 0xf4d50d87
#define T28 0x455a14ed
#define T29 0xa9e3e905
#define T30 0xfcefa3f8
#define T31 0x676f02d9
#define T32 0x8d2a4c8a
#define T33 0xfffa3942
#define T34 0x8771f681
#define T35 0x6d9d6122
#define T36 0xfde5380c
#define T37 0xa4beea44
#define T38 0x4bdecfa9
#define T39 0xf6bb4b60
#define T40 0xbebfbc70
#define T41 0x289b7ec6
#define T42 0xeaa127fa
#define T43 0xd4ef3085
#define T44 0x04881d05
#define T45 0xd9d4d039
#define T46 0xe6db99e5
#define T47 0x1fa27cf8
#define T48 0xc4ac5665
#define T49 0xf4292244
#define T50 0x432aff97
#define T51 0xab9423a7
#define T52 0xfc93a039
#define T53 0x655b59c3
#define T54 0x8f0ccc92
#define T55 0xffeff47d
#define T56 0x85845dd1
#define T57 0x6fa87e4f
#define T58 0xfe2ce6e0
#define T59 0xa3014314
#define T60 0x4e0811a1
#define T61 0xf7537e82
#define T62 0xbd3af235
#define T63 0x2ad7d2bb
#define T64 0xeb86d391
static void md5_process(md5_state_t *pms, const md5_byte_t *data /*[64] */ )
{
md5_word_t
a = pms->abcd[0], b = pms->abcd[1],
c = pms->abcd[2], d = pms->abcd[3];
md5_word_t t;
#ifndef ARCH_IS_BIG_ENDIAN
# define ARCH_IS_BIG_ENDIAN 1 /* slower, default implementation */
#endif
#if ARCH_IS_BIG_ENDIAN
/*
* On big-endian machines, we must arrange the bytes in the right
* order. (This also works on machines of unknown byte order.)
*/
md5_word_t X[16];
const md5_byte_t *xp = data;
int i;
for (i = 0; i < 16; ++i, xp += 4)
X[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
#else /* !ARCH_IS_BIG_ENDIAN */
/*
* On little-endian machines, we can process properly aligned data
* without copying it.
*/
md5_word_t xbuf[16];
const md5_word_t *X;
if (!((data - (const md5_byte_t *)0) & 3)) {
/* data are properly aligned */
X = (const md5_word_t *)data;
} else {
/* not aligned */
memcpy(xbuf, data, 64);
X = xbuf;
}
#endif
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
/* Round 1. */
/* Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + F(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 7, T1);
SET(d, a, b, c, 1, 12, T2);
SET(c, d, a, b, 2, 17, T3);
SET(b, c, d, a, 3, 22, T4);
SET(a, b, c, d, 4, 7, T5);
SET(d, a, b, c, 5, 12, T6);
SET(c, d, a, b, 6, 17, T7);
SET(b, c, d, a, 7, 22, T8);
SET(a, b, c, d, 8, 7, T9);
SET(d, a, b, c, 9, 12, T10);
SET(c, d, a, b, 10, 17, T11);
SET(b, c, d, a, 11, 22, T12);
SET(a, b, c, d, 12, 7, T13);
SET(d, a, b, c, 13, 12, T14);
SET(c, d, a, b, 14, 17, T15);
SET(b, c, d, a, 15, 22, T16);
#undef SET
/* Round 2. */
/* Let [abcd k s i] denote the operation
a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + G(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 1, 5, T17);
SET(d, a, b, c, 6, 9, T18);
SET(c, d, a, b, 11, 14, T19);
SET(b, c, d, a, 0, 20, T20);
SET(a, b, c, d, 5, 5, T21);
SET(d, a, b, c, 10, 9, T22);
SET(c, d, a, b, 15, 14, T23);
SET(b, c, d, a, 4, 20, T24);
SET(a, b, c, d, 9, 5, T25);
SET(d, a, b, c, 14, 9, T26);
SET(c, d, a, b, 3, 14, T27);
SET(b, c, d, a, 8, 20, T28);
SET(a, b, c, d, 13, 5, T29);
SET(d, a, b, c, 2, 9, T30);
SET(c, d, a, b, 7, 14, T31);
SET(b, c, d, a, 12, 20, T32);
#undef SET
/* Round 3. */
/* Let [abcd k s t] denote the operation
a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define SET(a, b, c, d, k, s, Ti)\
t = a + H(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 5, 4, T33);
SET(d, a, b, c, 8, 11, T34);
SET(c, d, a, b, 11, 16, T35);
SET(b, c, d, a, 14, 23, T36);
SET(a, b, c, d, 1, 4, T37);
SET(d, a, b, c, 4, 11, T38);
SET(c, d, a, b, 7, 16, T39);
SET(b, c, d, a, 10, 23, T40);
SET(a, b, c, d, 13, 4, T41);
SET(d, a, b, c, 0, 11, T42);
SET(c, d, a, b, 3, 16, T43);
SET(b, c, d, a, 6, 23, T44);
SET(a, b, c, d, 9, 4, T45);
SET(d, a, b, c, 12, 11, T46);
SET(c, d, a, b, 15, 16, T47);
SET(b, c, d, a, 2, 23, T48);
#undef SET
/* Round 4. */
/* Let [abcd k s t] denote the operation
a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + I(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 6, T49);
SET(d, a, b, c, 7, 10, T50);
SET(c, d, a, b, 14, 15, T51);
SET(b, c, d, a, 5, 21, T52);
SET(a, b, c, d, 12, 6, T53);
SET(d, a, b, c, 3, 10, T54);
SET(c, d, a, b, 10, 15, T55);
SET(b, c, d, a, 1, 21, T56);
SET(a, b, c, d, 8, 6, T57);
SET(d, a, b, c, 15, 10, T58);
SET(c, d, a, b, 6, 15, T59);
SET(b, c, d, a, 13, 21, T60);
SET(a, b, c, d, 4, 6, T61);
SET(d, a, b, c, 11, 10, T62);
SET(c, d, a, b, 2, 15, T63);
SET(b, c, d, a, 9, 21, T64);
#undef SET
/* Then perform the following additions. (That is increment each
of the four registers by the value it had before this block
was started.) */
pms->abcd[0] += a;
pms->abcd[1] += b;
pms->abcd[2] += c;
pms->abcd[3] += d;
}
void md5_init(md5_state_t *pms)
{
pms->count[0] = pms->count[1] = 0;
pms->abcd[0] = 0x67452301;
pms->abcd[1] = 0xefcdab89;
pms->abcd[2] = 0x98badcfe;
pms->abcd[3] = 0x10325476;
}
void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
{
const md5_byte_t *p = data;
int left = nbytes;
int offset = (pms->count[0] >> 3) & 63;
md5_word_t nbits = (md5_word_t) (nbytes << 3);
if (nbytes <= 0)
return;
/* Update the message length. */
pms->count[1] += nbytes >> 29;
pms->count[0] += nbits;
if (pms->count[0] < nbits)
pms->count[1]++;
/* Process an initial partial block. */
if (offset) {
int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
memcpy(pms->buf + offset, p, copy);
if (offset + copy < 64)
return;
p += copy;
left -= copy;
md5_process(pms, pms->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64)
md5_process(pms, p);
/* Process a final partial block. */
if (left)
memcpy(pms->buf, p, left);
}
void md5_finish(md5_state_t *pms, md5_byte_t digest[16])
{
static const md5_byte_t pad[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
md5_byte_t data[8];
int i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i)
data[i] = (md5_byte_t) (pms->count[i >> 2] >> ((i & 3) << 3));
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
md5_append(pms, data, 8);
for (i = 0; i < 16; ++i)
digest[i] = (md5_byte_t) (pms->abcd[i >> 2] >> ((i & 3) << 3));
}

View file

@ -0,0 +1,92 @@
/*
Copyright (C) 1999 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
*/
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321.
It is derived directly from the text of the RFC and not from the
reference implementation.
The original and principal author of md5.h is L. Peter Deutsch
<ghost@aladdin.com>. Other authors are noted in the change history
that follows (in reverse chronological order):
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
added conditionalization for C++ compilation from Martin
Purschke <purschke@bnl.gov>.
1999-05-03 lpd Original version.
*/
#ifndef md5_INCLUDED
# define md5_INCLUDED
/*
* This code has some adaptations for the Ghostscript environment, but it
* will compile and run correctly in any environment with 8-bit chars and
* 32-bit ints. Specifically, it assumes that if the following are
* defined, they have the same meaning as in Ghostscript: P1, P2, P3,
* ARCH_IS_BIG_ENDIAN.
*/
typedef unsigned char md5_byte_t; /* 8-bit byte */
typedef unsigned int md5_word_t; /* 32-bit word */
/* Define the state of the MD5 Algorithm. */
typedef struct md5_state_s {
md5_word_t count[2]; /* message length in bits, lsw first */
md5_word_t abcd[4]; /* digest buffer */
md5_byte_t buf[64]; /* accumulate block */
} md5_state_t;
#ifdef __cplusplus
extern "C" {
#endif
/* Initialize the algorithm. */
#ifdef P1
void md5_init(P1(md5_state_t *pms));
#else
void md5_init(md5_state_t *pms);
#endif
/* Append a string to the message. */
#ifdef P3
void md5_append(P3(md5_state_t *pms, const md5_byte_t *data,
int nbytes));
#else
void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes);
#endif
/* Finish the message and return the digest. */
#ifdef P2
void md5_finish(P2(md5_state_t *pms, md5_byte_t digest[16]));
#else
void md5_finish(md5_state_t *pms, md5_byte_t digest[16]);
#endif
#ifdef __cplusplus
} /* end extern "C" */
#endif
#endif /* md5_INCLUDED */

View file

@ -0,0 +1,613 @@
/*-
* Copyright (c) 2001-2003 Allan Saddi <allan@saddi.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY ALLAN SADDI AND HIS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL ALLAN SADDI OR HIS CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Define WORDS_BIGENDIAN if compiling on a big-endian architecture.
*
* Define SHA1_TEST to test the implementation using the NIST's
* sample messages. The output should be:
*
* a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d
* 84983e44 1c3bd26e baae4aa1 f95129e5 e54670f1
* 34aa973c d4c4daa4 f61eeb2b dbad2731 6534016f
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */
#if HAVE_INTTYPES_H
# include <inttypes.h>
#else
# if HAVE_STDINT_H
# include <stdint.h>
# endif
#endif
#include <string.h>
#include "sha1.h"
#define ROTL(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
#define ROTR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
#define F_0_19(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
#define F_20_39(x, y, z) ((x) ^ (y) ^ (z))
#define F_40_59(x, y, z) (((x) & ((y) | (z))) | ((y) & (z)))
#define F_60_79(x, y, z) ((x) ^ (y) ^ (z))
#define DO_ROUND(F, K) { \
temp = ROTL(a, 5) + F(b, c, d) + e + *(W++) + K; \
e = d; \
d = c; \
c = ROTL(b, 30); \
b = a; \
a = temp; \
}
#define K_0_19 0x5a827999L
#define K_20_39 0x6ed9eba1L
#define K_40_59 0x8f1bbcdcL
#define K_60_79 0xca62c1d6L
#ifndef RUNTIME_ENDIAN
#ifdef WORDS_BIGENDIAN
#define BYTESWAP(x) (x)
#define BYTESWAP64(x) (x)
#else /* WORDS_BIGENDIAN */
#define BYTESWAP(x) ((ROTR((x), 8) & 0xff00ff00L) | (ROTL((x), 8) & 0x00ff00ffL))
static uint64_t _byteswap64(uint64_t x)
{
uint32_t a = x >> 32;
uint32_t b = (uint32_t) x;
return ((uint64_t) BYTESWAP(b) << 32) | (uint64_t) BYTESWAP(a);
}
#define BYTESWAP64(x) _byteswap64(x)
#endif /* WORDS_BIGENDIAN */
#else /* !RUNTIME_ENDIAN */
#define BYTESWAP(x) _byteswap(sc->littleEndian, x)
#define BYTESWAP64(x) _byteswap64(sc->littleEndian, x)
#define _BYTESWAP(x) ((ROTR((x), 8) & 0xff00ff00L) | \
(ROTL((x), 8) & 0x00ff00ffL))
#define _BYTESWAP64(x) __byteswap64(x)
static uint64_t __byteswap64(uint64_t x)
{
uint32_t a = x >> 32;
uint32_t b = (uint32_t) x;
return ((uint64_t) _BYTESWAP(b) << 32) | (uint64_t) _BYTESWAP(a);
}
static uint32_t _byteswap(int littleEndian, uint32_t x)
{
if (!littleEndian)
return x;
else
return _BYTESWAP(x);
}
static uint64_t _byteswap64(int littleEndian, uint64_t x)
{
if (!littleEndian)
return x;
else
return _BYTESWAP64(x);
}
static void setEndian(int *littleEndianp)
{
union {
uint32_t w;
uint8_t b[4];
} endian;
endian.w = 1L;
*littleEndianp = endian.b[0] != 0;
}
#endif /* !RUNTIME_ENDIAN */
static const uint8_t padding[64] = {
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
void SHA1Init(SHA1Context *sc)
{
#ifdef RUNTIME_ENDIAN
setEndian(&sc->littleEndian);
#endif /* RUNTIME_ENDIAN */
sc->totalLength = 0LL;
sc->hash[0] = 0x67452301L;
sc->hash[1] = 0xefcdab89L;
sc->hash[2] = 0x98badcfeL;
sc->hash[3] = 0x10325476L;
sc->hash[4] = 0xc3d2e1f0L;
sc->bufferLength = 0L;
}
static void burnStack(int size)
{
char buf[128];
memset(buf, 0, sizeof(buf));
size -= sizeof(buf);
if (size > 0)
burnStack(size);
}
static void SHA1Guts(SHA1Context *sc, const uint32_t *cbuf)
{
uint32_t buf[80];
uint32_t *W, *W3, *W8, *W14, *W16;
uint32_t a, b, c, d, e, temp;
int i;
W = buf;
for (i = 15; i >= 0; i--) {
*(W++) = BYTESWAP(*cbuf);
cbuf++;
}
W16 = &buf[0];
W14 = &buf[2];
W8 = &buf[8];
W3 = &buf[13];
for (i = 63; i >= 0; i--) {
*W = *(W3++) ^ *(W8++) ^ *(W14++) ^ *(W16++);
*W = ROTL(*W, 1);
W++;
}
a = sc->hash[0];
b = sc->hash[1];
c = sc->hash[2];
d = sc->hash[3];
e = sc->hash[4];
W = buf;
#ifndef SHA1_UNROLL
#define SHA1_UNROLL 20
#endif /* !SHA1_UNROLL */
#if SHA1_UNROLL == 1
for (i = 19; i >= 0; i--)
DO_ROUND(F_0_19, K_0_19);
for (i = 19; i >= 0; i--)
DO_ROUND(F_20_39, K_20_39);
for (i = 19; i >= 0; i--)
DO_ROUND(F_40_59, K_40_59);
for (i = 19; i >= 0; i--)
DO_ROUND(F_60_79, K_60_79);
#elif SHA1_UNROLL == 2
for (i = 9; i >= 0; i--) {
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
}
for (i = 9; i >= 0; i--) {
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
}
for (i = 9; i >= 0; i--) {
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
}
for (i = 9; i >= 0; i--) {
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
}
#elif SHA1_UNROLL == 4
for (i = 4; i >= 0; i--) {
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
}
for (i = 4; i >= 0; i--) {
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
}
for (i = 4; i >= 0; i--) {
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
}
for (i = 4; i >= 0; i--) {
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
}
#elif SHA1_UNROLL == 5
for (i = 3; i >= 0; i--) {
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
}
for (i = 3; i >= 0; i--) {
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
}
for (i = 3; i >= 0; i--) {
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
}
for (i = 3; i >= 0; i--) {
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
}
#elif SHA1_UNROLL == 10
for (i = 1; i >= 0; i--) {
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
}
for (i = 1; i >= 0; i--) {
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
}
for (i = 1; i >= 0; i--) {
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
}
for (i = 1; i >= 0; i--) {
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
}
#elif SHA1_UNROLL == 20
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_0_19, K_0_19);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_20_39, K_20_39);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_40_59, K_40_59);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
DO_ROUND(F_60_79, K_60_79);
#else /* SHA1_UNROLL */
#error SHA1_UNROLL must be 1, 2, 4, 5, 10 or 20!
#endif
sc->hash[0] += a;
sc->hash[1] += b;
sc->hash[2] += c;
sc->hash[3] += d;
sc->hash[4] += e;
}
void SHA1Update(SHA1Context *sc, const void *vdata, uint32_t len)
{
const uint8_t *data = vdata;
uint32_t bufferBytesLeft;
uint32_t bytesToCopy;
int needBurn = 0;
#ifdef SHA1_FAST_COPY
if (sc->bufferLength) {
bufferBytesLeft = 64L - sc->bufferLength;
bytesToCopy = bufferBytesLeft;
if (bytesToCopy > len)
bytesToCopy = len;
memcpy(&sc->buffer.bytes[sc->bufferLength], data, bytesToCopy);
sc->totalLength += bytesToCopy * 8L;
sc->bufferLength += bytesToCopy;
data += bytesToCopy;
len -= bytesToCopy;
if (sc->bufferLength == 64L) {
SHA1Guts(sc, sc->buffer.words);
needBurn = 1;
sc->bufferLength = 0L;
}
}
while (len > 63) {
sc->totalLength += 512L;
SHA1Guts(sc, data);
needBurn = 1;
data += 64L;
len -= 64L;
}
if (len) {
memcpy(&sc->buffer.bytes[sc->bufferLength], data, len);
sc->totalLength += len * 8L;
sc->bufferLength += len;
}
#else /* SHA1_FAST_COPY */
while (len) {
bufferBytesLeft = 64L - sc->bufferLength;
bytesToCopy = bufferBytesLeft;
if (bytesToCopy > len)
bytesToCopy = len;
memcpy(&sc->buffer.bytes[sc->bufferLength], data, bytesToCopy);
sc->totalLength += bytesToCopy * 8L;
sc->bufferLength += bytesToCopy;
data += bytesToCopy;
len -= bytesToCopy;
if (sc->bufferLength == 64L) {
SHA1Guts(sc, sc->buffer.words);
needBurn = 1;
sc->bufferLength = 0L;
}
}
#endif /* SHA1_FAST_COPY */
if (needBurn)
burnStack(sizeof(uint32_t[86]) + sizeof(uint32_t *[5]) +
sizeof(int));
}
void SHA1Final(SHA1Context *sc, uint8_t hash[SHA1_HASH_SIZE])
{
uint32_t bytesToPad;
uint64_t lengthPad;
int i;
bytesToPad = 120L - sc->bufferLength;
if (bytesToPad > 64L)
bytesToPad -= 64L;
lengthPad = BYTESWAP64(sc->totalLength);
SHA1Update(sc, padding, bytesToPad);
SHA1Update(sc, &lengthPad, 8L);
if (hash) {
for (i = 0; i < SHA1_HASH_WORDS; i++) {
#ifdef SHA1_FAST_COPY
*((uint32_t *)hash) = BYTESWAP(sc->hash[i]);
#else /* SHA1_FAST_COPY */
hash[0] = (uint8_t) (sc->hash[i] >> 24);
hash[1] = (uint8_t) (sc->hash[i] >> 16);
hash[2] = (uint8_t) (sc->hash[i] >> 8);
hash[3] = (uint8_t) sc->hash[i];
#endif /* SHA1_FAST_COPY */
hash += 4;
}
}
}
#ifdef SHA1_TEST
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
SHA1Context foo;
uint8_t hash[SHA1_HASH_SIZE];
char buf[1000];
int i;
SHA1Init(&foo);
SHA1Update(&foo, "abc", 3);
SHA1Final(&foo, hash);
for (i = 0; i < SHA1_HASH_SIZE;) {
printf("%02x", hash[i++]);
if (!(i % 4))
printf(" ");
}
printf("\n");
SHA1Init(&foo);
SHA1Update(&foo,
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", 56);
SHA1Final(&foo, hash);
for (i = 0; i < SHA1_HASH_SIZE;) {
printf("%02x", hash[i++]);
if (!(i % 4))
printf(" ");
}
printf("\n");
SHA1Init(&foo);
memset(buf, 'a', sizeof(buf));
for (i = 0; i < 1000; i++)
SHA1Update(&foo, buf, sizeof(buf));
SHA1Final(&foo, hash);
for (i = 0; i < SHA1_HASH_SIZE;) {
printf("%02x", hash[i++]);
if (!(i % 4))
printf(" ");
}
printf("\n");
exit(0);
}
#endif /* SHA1_TEST */

View file

@ -0,0 +1,69 @@
/*-
* Copyright (c) 2001-2003 Allan Saddi <allan@saddi.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY ALLAN SADDI AND HIS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL ALLAN SADDI OR HIS CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _SHA1_H
#define _SHA1_H
#if HAVE_INTTYPES_H
# include <inttypes.h>
#else
# if HAVE_STDINT_H
# include <stdint.h>
# endif
#endif
#define SHA1_HASH_SIZE 20
/* Hash size in 32-bit words */
#define SHA1_HASH_WORDS 5
struct _SHA1Context {
uint64_t totalLength;
uint32_t hash[SHA1_HASH_WORDS];
uint32_t bufferLength;
union {
uint32_t words[16];
uint8_t bytes[64];
} buffer;
#ifdef RUNTIME_ENDIAN
int littleEndian;
#endif /* RUNTIME_ENDIAN */
};
typedef struct _SHA1Context SHA1Context;
#ifdef __cplusplus
extern "C" {
#endif
void SHA1Init(SHA1Context *sc);
void SHA1Update(SHA1Context *sc, const void *data, uint32_t len);
void SHA1Final(SHA1Context *sc, uint8_t hash[SHA1_HASH_SIZE]);
#ifdef __cplusplus
}
#endif
#endif /* _SHA1_H */

View file

@ -0,0 +1,225 @@
/*
* libyahoo2: yahoo2.h
*
* Copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef YAHOO2_H
#define YAHOO2_H
#ifdef __cplusplus
extern "C" {
#endif
#include "yahoo2_types.h"
/* returns the socket descriptor object for a given pager connection. shouldn't be needed */
void *yahoo_get_fd(int id);
/* says how much logging to do */
/* see yahoo2_types.h for the different values */
int yahoo_set_log_level(enum yahoo_log_level level);
enum yahoo_log_level yahoo_get_log_level(void);
/* these functions should be self explanatory */
/* who always means the buddy you're acting on */
/* id is the successful value returned by yahoo_init */
/* init returns a connection id used to identify the connection hereon */
/* or 0 on failure */
/* you must call init before calling any other function */
/*
* The optional parameters to init are key/value pairs that specify
* server settings to use. This list must be NULL terminated - even
* if the list is empty. If a parameter isn't set, a default value
* will be used. Parameter keys are strings, parameter values are
* either strings or ints, depending on the key. Values passed in
* are copied, so you can use const/auto/static/pointers/whatever
* you want. Parameters are:
* NAME TYPE DEFAULT
* pager_host char * scs.msg.yahoo.com
* pager_port int 5050
* filetransfer_host char * filetransfer.msg.yahoo.com
* filetransfer_port int 80
* webcam_host char * webcam.yahoo.com
* webcam_port int 5100
* webcam_description char * ""
* local_host char * ""
* conn_type int Y_WCM_DSL
*
* You should set at least local_host if you intend to use webcams
*/
int yahoo_init_with_attributes(const char *username,
const char *password, ...);
/* yahoo_init does the same as yahoo_init_with_attributes, assuming defaults
* for all attributes */
int yahoo_init(const char *username, const char *password);
/* release all resources held by this session */
/* you need to call yahoo_close for a session only if
* yahoo_logoff is never called for it (ie, it was never logged in) */
void yahoo_close(int id);
/* login logs in to the server */
/* initial is of type enum yahoo_status. see yahoo2_types.h */
void yahoo_login(int id, int initial);
void yahoo_logoff(int id);
/* reloads status of all buddies */
void yahoo_refresh(int id);
/* activates/deactivates an identity */
void yahoo_set_identity_status(int id, const char *identity,
int active);
/* regets the entire buddy list from the server */
void yahoo_get_list(int id);
/* download buddy contact information from your yahoo addressbook */
void yahoo_get_yab(int id);
/* add/modify an address book entry. if yab->dbid is set, it will */
/* modify that entry else it creates a new entry */
void yahoo_set_yab(int id, struct yab *yab);
void yahoo_keepalive(int id);
void yahoo_chat_keepalive(int id);
/* from is the identity you're sending from. if NULL, the default is used */
/* utf8 is whether msg is a utf8 string or not. */
void yahoo_send_im(int id, const char *from, const char *who,
const char *msg, int utf8, int picture);
void yahoo_send_buzz(int id, const char *from, const char *who);
/* if type is true, send typing notice, else send stopped typing notice */
void yahoo_send_typing(int id, const char *from, const char *who,
int typ);
/* used to set away/back status. */
/* away says whether the custom message is an away message or a sig */
void yahoo_set_away(int id, enum yahoo_status state, const char *msg,
int away);
void yahoo_add_buddy(int id, const char *who, const char *group,
const char *msg);
void yahoo_remove_buddy(int id, const char *who, const char *group);
void yahoo_confirm_buddy(int id, const char *who, int reject,
const char *msg);
void yahoo_stealth_buddy(int id, const char *who, int unstealth);
/* if unignore is true, unignore, else ignore */
void yahoo_ignore_buddy(int id, const char *who, int unignore);
void yahoo_change_buddy_group(int id, const char *who,
const char *old_group, const char *new_group);
void yahoo_group_rename(int id, const char *old_group,
const char *new_group);
void yahoo_conference_invite(int id, const char *from, YList *who,
const char *room, const char *msg);
void yahoo_conference_addinvite(int id, const char *from,
const char *who, const char *room, const YList *members,
const char *msg);
void yahoo_conference_decline(int id, const char *from, YList *who,
const char *room, const char *msg);
void yahoo_conference_message(int id, const char *from, YList *who,
const char *room, const char *msg, int utf8);
void yahoo_conference_logon(int id, const char *from, YList *who,
const char *room);
void yahoo_conference_logoff(int id, const char *from, YList *who,
const char *room);
/* Get a list of chatrooms */
void yahoo_get_chatrooms(int id, int chatroomid);
/* join room with specified roomname and roomid */
void yahoo_chat_logon(int id, const char *from, const char *room,
const char *roomid);
/* Send message "msg" to room with specified roomname, msgtype is 1-normal message or 2-/me mesage */
void yahoo_chat_message(int id, const char *from, const char *room,
const char *msg, const int msgtype, const int utf8);
/* Log off chat */
void yahoo_chat_logoff(int id, const char *from);
/* requests a webcam feed */
/* who is the person who's webcam you would like to view */
/* if who is null, then you're the broadcaster */
void yahoo_webcam_get_feed(int id, const char *who);
void yahoo_webcam_close_feed(int id, const char *who);
/* sends an image when uploading */
/* image points to a JPEG-2000 image, length is the length of the image */
/* in bytes. The timestamp is the time in milliseconds since we started the */
/* webcam. */
void yahoo_webcam_send_image(int id, unsigned char *image,
unsigned int length, unsigned int timestamp);
/* this function should be called if we want to allow a user to watch the */
/* webcam. Who is the user we want to accept. */
/* Accept user (accept = 1), decline user (accept = 0) */
void yahoo_webcam_accept_viewer(int id, const char *who, int accept);
/* send an invitation to a user to view your webcam */
void yahoo_webcam_invite(int id, const char *who);
/* will set up a connection and initiate file transfer.
* callback will be called with the fd that you should write
* the file data to
*/
void yahoo_send_file(int id, const char *who, const char *msg,
const char *name, unsigned long size,
yahoo_get_fd_callback callback, void *data);
/*
* Respond to a file transfer request. Be sure to provide the callback data
* since that is your only chance to recognize future callbacks
*/
void yahoo_send_file_transfer_response(int client_id, int response,
char *id, void *data);
/* send a search request
*/
void yahoo_search(int id, enum yahoo_search_type t, const char *text,
enum yahoo_search_gender g, enum yahoo_search_agerange ar,
int photo, int yahoo_only);
/* continue last search
* should be called if only (start+found >= total)
*
* where the above three are passed to ext_yahoo_got_search_result
*/
void yahoo_search_again(int id, int start);
/* these should be called when input is available on a fd */
/* registered by ext_yahoo_add_handler */
/* if these return negative values, errno may be set */
int yahoo_read_ready(int id, void *fd, void *data);
int yahoo_write_ready(int id, void *fd, void *data);
/* utility functions. these do not hit the server */
enum yahoo_status yahoo_current_status(int id);
const YList *yahoo_get_buddylist(int id);
const YList *yahoo_get_ignorelist(int id);
const YList *yahoo_get_identities(int id);
/* 'which' could be y, t, c or login. This may change in later versions. */
const char *yahoo_get_cookie(int id, const char *which);
/* returns the url used to get user profiles - you must append the user id */
/* as of now this is http://profiles.yahoo.com/ */
/* You'll have to do urlencoding yourself, but see yahoo_httplib.h first */
const char *yahoo_get_profile_url(void);
void yahoo_buddyicon_request(int id, const char *who);
#include "yahoo_httplib.h"
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,776 @@
/*
* libyahoo2: yahoo2_callbacks.h
*
* Copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*
* The functions in this file *must* be defined in your client program
* If you want to use a callback structure instead of direct functions,
* then you must define USE_STRUCT_CALLBACKS in all files that #include
* this one.
*
* Register the callback structure by calling yahoo_register_callbacks -
* declared in this file and defined in libyahoo2.c
*/
#ifndef YAHOO2_CALLBACKS_H
#define YAHOO2_CALLBACKS_H
#ifdef __cplusplus
extern "C" {
#endif
#include "yahoo2_types.h"
/*
* yahoo2_callbacks.h
*
* Callback interface for libyahoo2
*/
typedef enum {
YAHOO_INPUT_READ = 1 << 0,
YAHOO_INPUT_WRITE = 1 << 1,
YAHOO_INPUT_EXCEPTION = 1 << 2
} yahoo_input_condition;
/*
* A callback function called when an asynchronous connect completes.
*
* Params:
* fd - The file descriptor object that has been connected, or NULL on
* error
* error - The value of errno set by the call to connect or 0 if no error
* Set both fd and error to 0 if the connect was cancelled by the
* user
* callback_data - the callback_data passed to the ext_yahoo_connect_async
* function
*/
typedef void (*yahoo_connect_callback) (void *fd, int error,
void *callback_data);
/*
* The following functions need to be implemented in the client
* interface. They will be called by the library when each
* event occurs.
*/
/*
* should we use a callback structure or directly call functions
* if you want the structure, you *must* define USE_STRUCT_CALLBACKS
* both when you compile the library, and when you compile your code
* that uses the library
*/
#define YAHOO_CALLBACK_TYPE(x) (*x)
struct yahoo_callbacks {
/*
* Name: ext_yahoo_login_response
* Called when the login process is complete
* Params:
* id - the id that identifies the server connection
* succ - enum yahoo_login_status
* url - url to reactivate account if locked
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_login_response) (int id, int succ,
const char *url);
/*
* Name: ext_yahoo_got_buddies
* Called when the contact list is got from the server
* Params:
* id - the id that identifies the server connection
* buds - the buddy list
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_buddies) (int id, YList *buds);
/*
* Name: ext_yahoo_got_ignore
* Called when the ignore list is got from the server
* Params:
* id - the id that identifies the server connection
* igns - the ignore list
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_ignore) (int id, YList *igns);
/*
* Name: ext_yahoo_got_identities
* Called when the contact list is got from the server
* Params:
* id - the id that identifies the server connection
* ids - the identity list
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_identities) (int id, YList *ids);
/*
* Name: ext_yahoo_got_cookies
* Called when the cookie list is got from the server
* Params:
* id - the id that identifies the server connection
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_cookies) (int id);
/*
* Name: ext_yahoo_got_ping
* Called when the ping packet is received from the server
* Params:
* id - the id that identifies the server connection
* errormsg - optional error message
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_ping) (int id,
const char *errormsg);
/*
* Name: ext_yahoo_status_changed
* Called when remote user's status changes.
* Params:
* id - the id that identifies the server connection
* who - the handle of the remote user
* stat - status code (enum yahoo_status)
* msg - the message if stat == YAHOO_STATUS_CUSTOM
* away - whether the contact is away or not (YAHOO_STATUS_CUSTOM)
* idle - this is the number of seconds he is idle [if he is idle]
* mobile - this is set for mobile users/buddies
* TODO: add support for pager, chat, and game states
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_status_changed) (int id,
const char *who, int stat, const char *msg, int away, int idle,
int mobile);
/*
* Name: ext_yahoo_got_buzz
* Called when remote user sends you a buzz.
* Params:
* id - the id that identifies the server connection
* me - the identity the message was sent to
* who - the handle of the remote user
* tm - timestamp of message if offline
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_buzz) (int id, const char *me,
const char *who, long tm);
/*
* Name: ext_yahoo_got_im
* Called when remote user sends you a message.
* Params:
* id - the id that identifies the server connection
* me - the identity the message was sent to
* who - the handle of the remote user
* msg - the message - NULL if stat == 2
* tm - timestamp of message if offline
* stat - message status - 0
* 1
* 2 == error sending message
* 5
* utf8 - whether the message is encoded as utf8 or not
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_im) (int id, const char *me,
const char *who, const char *msg, long tm, int stat, int utf8);
/*
* Name: ext_yahoo_got_conf_invite
* Called when remote user sends you a conference invitation.
* Params:
* id - the id that identifies the server connection
* me - the identity the invitation was sent to
* who - the user inviting you
* room - the room to join
* msg - the message
* members - the initial members of the conference (null terminated list)
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_conf_invite) (int id,
const char *me, const char *who, const char *room,
const char *msg, YList *members);
/*
* Name: ext_yahoo_conf_userdecline
* Called when someone declines to join the conference.
* Params:
* id - the id that identifies the server connection
* me - the identity in the conference
* who - the user who has declined
* room - the room
* msg - the declining message
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_conf_userdecline) (int id,
const char *me, const char *who, const char *room,
const char *msg);
/*
* Name: ext_yahoo_conf_userjoin
* Called when someone joins the conference.
* Params:
* id - the id that identifies the server connection
* me - the identity in the conference
* who - the user who has joined
* room - the room joined
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_conf_userjoin) (int id,
const char *me, const char *who, const char *room);
/*
* Name: ext_yahoo_conf_userleave
* Called when someone leaves the conference.
* Params:
* id - the id that identifies the server connection
* me - the identity in the conference
* who - the user who has left
* room - the room left
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_conf_userleave) (int id,
const char *me, const char *who, const char *room);
/*
* Name: ext_yahoo_chat_cat_xml
* Called when ?
* Params:
* id - the id that identifies the server connection
* xml - ?
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_chat_cat_xml) (int id,
const char *xml);
/*
* Name: ext_yahoo_chat_join
* Called when joining the chatroom.
* Params:
* id - the id that identifies the server connection
* me - the identity in the chatroom
* room - the room joined, used in all other chat calls, freed by
* library after call
* topic - the topic of the room, freed by library after call
* members - the initial members of the chatroom (null terminated YList
* of yahoo_chat_member's) Must be freed by the client
* fd - the object where the connection is coming from (for tracking)
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_chat_join) (int id, const char *me,
const char *room, const char *topic, YList *members, void *fd);
/*
* Name: ext_yahoo_chat_userjoin
* Called when someone joins the chatroom.
* Params:
* id - the id that identifies the server connection
* me - the identity in the chatroom
* room - the room joined
* who - the user who has joined, Must be freed by the client
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_chat_userjoin) (int id,
const char *me, const char *room,
struct yahoo_chat_member *who);
/*
* Name: ext_yahoo_chat_userleave
* Called when someone leaves the chatroom.
* Params:
* id - the id that identifies the server connection
* me - the identity in the chatroom
* room - the room left
* who - the user who has left (Just the User ID)
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_chat_userleave) (int id,
const char *me, const char *room, const char *who);
/*
* Name: ext_yahoo_chat_message
* Called when someone messages in the chatroom.
* Params:
* id - the id that identifies the server connection
* me - the identity in the chatroom
* room - the room
* who - the user who messaged (Just the user id)
* msg - the message
* msgtype - 1 = Normal message
* 2 = /me type message
* utf8 - whether the message is utf8 encoded or not
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_chat_message) (int id,
const char *me, const char *who, const char *room,
const char *msg, int msgtype, int utf8);
/*
*
* Name: ext_yahoo_chat_yahoologout
* called when yahoo disconnects your chat session
* Note this is called whenver a disconnect happens, client or server
* requested. Care should be taken to make sure you know the origin
* of the disconnect request before doing anything here (auto-join's etc)
* Params:
* id - the id that identifies this connection
* me - the identity in the chatroom
* Returns:
* nothing.
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_chat_yahoologout) (int id,
const char *me);
/*
*
* Name: ext_yahoo_chat_yahooerror
* called when yahoo sends back an error to you
* Note this is called whenver chat message is sent into a room
* in error (fd not connected, room doesn't exists etc)
* Care should be taken to make sure you know the origin
* of the error before doing anything about it.
* Params:
* id - the id that identifies this connection
* me - the identity in the chatroom
* Returns:
* nothing.
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_chat_yahooerror) (int id,
const char *me);
/*
* Name: ext_yahoo_conf_message
* Called when someone messages in the conference.
* Params:
* id - the id that identifies the server connection
* me - the identity the conf message was sent to
* who - the user who messaged
* room - the room
* msg - the message
* utf8 - whether the message is utf8 encoded or not
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_conf_message) (int id,
const char *me, const char *who, const char *room,
const char *msg, int utf8);
/*
* Name: ext_yahoo_got_file
* Called when someone sends you a file
* Params:
* id - the id that identifies the server connection
* me - the identity the file was sent to
* who - the user who sent the file
* msg - the message
* fname- the file name if direct transfer
* fsize- the file size if direct transfer
* trid - transfer id. Unique for this transfer
*
* NOTE: Subsequent callbacks for file transfer do not send all of this
* information again since it is wasteful. Implementations are expected to
* save this information and supply it as callback data when the file or
* confirmation is sent
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_file) (int id, const char *me,
const char *who, const char *msg, const char *fname,
unsigned long fesize, char *trid);
/*
* Name: ext_yahoo_got_ft_data
* Called multiple times when parts of the file are received
* Params:
* id - the id that identifies the server connection
* in - The data
* len - Length of the data
* data - callback data
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_ft_data) (int id,
const unsigned char *in, int len, void *data);
/*
* Name: ext_yahoo_file_transfer_done
* File transfer is done
* Params:
* id - the id that identifies the server connection
* result - To notify if it finished successfully or with a failure
* data - callback data
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_file_transfer_done) (int id,
int result, void *data);
/*
* Name: ext_yahoo_contact_added
* Called when a contact is added to your list
* Params:
* id - the id that identifies the server connection
* myid - the identity he was added to
* who - who was added
* msg - any message sent
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_contact_added) (int id,
const char *myid, const char *who, const char *msg);
/*
* Name: ext_yahoo_rejected
* Called when a contact rejects your add
* Params:
* id - the id that identifies the server connection
* who - who rejected you
* msg - any message sent
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_rejected) (int id, const char *who,
const char *msg);
/*
* Name: ext_yahoo_typing_notify
* Called when remote user starts or stops typing.
* Params:
* id - the id that identifies the server connection
* me - the handle of the identity the notification is sent to
* who - the handle of the remote user
* stat - 1 if typing, 0 if stopped typing
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_typing_notify) (int id,
const char *me, const char *who, int stat);
/*
* Name: ext_yahoo_game_notify
* Called when remote user starts or stops a game.
* Params:
* id - the id that identifies the server connection
* me - the handle of the identity the notification is sent to
* who - the handle of the remote user
* stat - 1 if game, 0 if stopped gaming
* msg - game description and/or other text
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_game_notify) (int id, const char *me,
const char *who, int stat, const char *msg);
/*
* Name: ext_yahoo_mail_notify
* Called when you receive mail, or with number of messages
* Params:
* id - the id that identifies the server connection
* from - who the mail is from - NULL if only mail count
* subj - the subject of the mail - NULL if only mail count
* cnt - mail count - 0 if new mail notification
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_mail_notify) (int id,
const char *from, const char *subj, int cnt);
/*
* Name: ext_yahoo_system_message
* System message
* Params:
* id - the id that identifies the server connection
* me - the handle of the identity the notification is sent to
* who - the source of the system message (there are different types)
* msg - the message
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_system_message) (int id,
const char *me, const char *who, const char *msg);
/*
* Name: ext_yahoo_got_buddyicon
* Buddy icon received
* Params:
* id - the id that identifies the server connection
* me - the handle of the identity the notification is sent to
* who - the person the buddy icon is for
* url - the url to use to load the icon
* checksum - the checksum of the icon content
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_buddyicon) (int id,
const char *me, const char *who, const char *url, int checksum);
/*
* Name: ext_yahoo_got_buddyicon_checksum
* Buddy icon checksum received
* Params:
* id - the id that identifies the server connection
* me - the handle of the identity the notification is sent to
* who - the yahoo id of the buddy icon checksum is for
* checksum - the checksum of the icon content
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_buddyicon_checksum) (int id,
const char *me, const char *who, int checksum);
/*
* Name: ext_yahoo_got_buddyicon_request
* Buddy icon request received
* Params:
* id - the id that identifies the server connection
* me - the handle of the identity the notification is sent to
* who - the yahoo id of the buddy that requested the buddy icon
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_buddyicon_request) (int id,
const char *me, const char *who);
/*
* Name: ext_yahoo_got_buddyicon_request
* Buddy icon request received
* Params:
* id - the id that identifies the server connection
* url - remote url, the uploaded buddy icon can be fetched from
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_buddyicon_uploaded) (int id,
const char *url);
/*
* Name: ext_yahoo_got_webcam_image
* Called when you get a webcam update
* An update can either be receiving an image, a part of an image or
* just an update with a timestamp
* Params:
* id - the id that identifies the server connection
* who - the user who's webcam we're viewing
* image - image data
* image_size - length of the image in bytes
* real_size - actual length of image data
* timestamp - milliseconds since the webcam started
*
* If the real_size is smaller then the image_size then only part of
* the image has been read. This function will keep being called till
* the total amount of bytes in image_size has been read. The image
* received is in JPEG-2000 Code Stream Syntax (ISO/IEC 15444-1).
* The size of the image will be either 160x120 or 320x240.
* Each webcam image contains a timestamp. This timestamp should be
* used to keep the image in sync since some images can take longer
* to transport then others. When image_size is 0 we can still receive
* a timestamp to stay in sync
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_webcam_image) (int id,
const char *who, const unsigned char *image,
unsigned int image_size, unsigned int real_size,
unsigned int timestamp);
/*
* Name: ext_yahoo_webcam_invite
* Called when you get a webcam invitation
* Params:
* id - the id that identifies the server connection
* me - identity the invitation is to
* from - who the invitation is from
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_webcam_invite) (int id,
const char *me, const char *from);
/*
* Name: ext_yahoo_webcam_invite_reply
* Called when you get a response to a webcam invitation
* Params:
* id - the id that identifies the server connection
* me - identity the invitation response is to
* from - who the invitation response is from
* accept - 0 (decline), 1 (accept)
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_webcam_invite_reply) (int id,
const char *me, const char *from, int accept);
/*
* Name: ext_yahoo_webcam_closed
* Called when the webcam connection closed
* Params:
* id - the id that identifies the server connection
* who - the user who we where connected to
* reason - reason why the connection closed
* 1 = user stopped broadcasting
* 2 = user cancelled viewing permission
* 3 = user declines permission
* 4 = user does not have webcam online
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_webcam_closed) (int id,
const char *who, int reason);
/*
* Name: ext_yahoo_got_search_result
* Called when the search result received from server
* Params:
* id - the id that identifies the server connection
* found - total number of results returned in the current result set
* start - offset from where the current result set starts
* total - total number of results available (start + found <= total)
* contacts - the list of results as a YList of yahoo_found_contact
* these will be freed after this function returns, so
* if you need to use the information, make a copy
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_search_result) (int id,
int found, int start, int total, YList *contacts);
/*
* Name: ext_yahoo_error
* Called on error.
* Params:
* id - the id that identifies the server connection
* err - the error message
* fatal- whether this error is fatal to the connection or not
* num - Which error is this
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_error) (int id, const char *err,
int fatal, int num);
/*
* Name: ext_yahoo_webcam_viewer
* Called when a viewer disconnects/connects/requests to connect
* Params:
* id - the id that identifies the server connection
* who - the viewer
* connect - 0=disconnect 1=connect 2=request
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_webcam_viewer) (int id,
const char *who, int connect);
/*
* Name: ext_yahoo_webcam_data_request
* Called when you get a request for webcam images
* Params:
* id - the id that identifies the server connection
* send - whether to send images or not
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_webcam_data_request) (int id,
int send);
/*
* Name: ext_yahoo_log
* Called to log a message.
* Params:
* fmt - the printf formatted message
* Returns:
* 0
*/
int YAHOO_CALLBACK_TYPE(ext_yahoo_log) (const char *fmt, ...);
/*
* Name: ext_yahoo_add_handler
* Add a listener for the fd. Must call yahoo_read_ready
* when a YAHOO_INPUT_READ fd is ready and yahoo_write_ready
* when a YAHOO_INPUT_WRITE fd is ready.
* Params:
* id - the id that identifies the server connection
* fd - the fd object on which to listen
* cond - the condition on which to call the callback
* data - callback data to pass to yahoo_*_ready
*
* Returns: a tag to be used when removing the handler
*/
int YAHOO_CALLBACK_TYPE(ext_yahoo_add_handler) (int id, void *fd,
yahoo_input_condition cond, void *data);
/*
* Name: ext_yahoo_remove_handler
* Remove the listener for the fd.
* Params:
* id - the id that identifies the connection
* tag - the handler tag to remove
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_remove_handler) (int id, int tag);
/*
* Name: ext_yahoo_connect
* Connect to a host:port
* Params:
* host - the host to connect to
* port - the port to connect on
* Returns:
* a unix file descriptor to the socket
*/
int YAHOO_CALLBACK_TYPE(ext_yahoo_connect) (const char *host, int port);
/*
* Name: ext_yahoo_connect_async
* Connect to a host:port asynchronously. This function should return
* immediately returing a tag used to identify the connection handler,
* or a pre-connect error (eg: host name lookup failure).
* Once the connect completes (successfully or unsuccessfully), callback
* should be called (see the signature for yahoo_connect_callback).
* The callback may safely be called before this function returns, but
* it should not be called twice.
* Params:
* id - the id that identifies this connection
* host - the host to connect to
* port - the port to connect on
* callback - function to call when connect completes
* callback_data - data to pass to the callback function
* use_ssl - Whether we need an SSL connection
* Returns:
* a tag signifying the connection attempt
*/
int YAHOO_CALLBACK_TYPE(ext_yahoo_connect_async) (int id,
const char *host, int port, yahoo_connect_callback callback,
void *callback_data, int use_ssl);
/*
* Name: ext_yahoo_get_ip_addr
* get IP Address for a domain name
* Params:
* domain - Domain name
* Returns:
* Newly allocated string containing the IP Address in IPv4 notation
*/
char *YAHOO_CALLBACK_TYPE(ext_yahoo_get_ip_addr) (const char *domain);
/*
* Name: ext_yahoo_write
* Write data from the buffer into the socket for the specified connection
* Params:
* fd - the file descriptor object that identifies this connection
* buf - Buffer to write the data from
* len - Length of the data
* Returns:
* Number of bytes written or -1 for error
*/
int YAHOO_CALLBACK_TYPE(ext_yahoo_write) (void *fd, char *buf, int len);
/*
* Name: ext_yahoo_read
* Read data into a buffer from socket for the specified connection
* Params:
* fd - the file descriptor object that identifies this connection
* buf - Buffer to read the data into
* len - Max length to read
* Returns:
* Number of bytes read or -1 for error
*/
int YAHOO_CALLBACK_TYPE(ext_yahoo_read) (void *fd, char *buf, int len);
/*
* Name: ext_yahoo_close
* Close the file descriptor object and free its resources. Libyahoo2 will not
* use this object again.
* Params:
* fd - the file descriptor object that identifies this connection
* Returns:
* Nothing
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_close) (void *fd);
/*
* Name: ext_yahoo_got_buddy_change_group
* Acknowledgement of buddy changing group
* Params:
* id: client id
* me: The user
* who: Buddy name
* old_group: Old group name
* new_group: New group name
* Returns:
* Nothing
*/
void YAHOO_CALLBACK_TYPE(ext_yahoo_got_buddy_change_group) (int id,
const char *me, const char *who, const char *old_group,
const char *new_group);
};
/*
* if using a callback structure, call yahoo_register_callbacks
* before doing anything else
*/
void yahoo_register_callbacks(struct yahoo_callbacks *tyc);
#undef YAHOO_CALLBACK_TYPE
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,396 @@
/*
* libyahoo2: yahoo2_types.h
*
* Copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef YAHOO2_TYPES_H
#define YAHOO2_TYPES_H
#include "yahoo_list.h"
#ifdef __cplusplus
extern "C" {
#endif
enum yahoo_service { /* these are easier to see in hex */
YAHOO_SERVICE_LOGON = 1,
YAHOO_SERVICE_LOGOFF,
YAHOO_SERVICE_ISAWAY,
YAHOO_SERVICE_ISBACK,
YAHOO_SERVICE_IDLE, /* 5 (placemarker) */
YAHOO_SERVICE_MESSAGE,
YAHOO_SERVICE_IDACT,
YAHOO_SERVICE_IDDEACT,
YAHOO_SERVICE_MAILSTAT,
YAHOO_SERVICE_USERSTAT, /* 0xa */
YAHOO_SERVICE_NEWMAIL,
YAHOO_SERVICE_CHATINVITE,
YAHOO_SERVICE_CALENDAR,
YAHOO_SERVICE_NEWPERSONALMAIL,
YAHOO_SERVICE_NEWCONTACT,
YAHOO_SERVICE_ADDIDENT, /* 0x10 */
YAHOO_SERVICE_ADDIGNORE,
YAHOO_SERVICE_PING,
YAHOO_SERVICE_GOTGROUPRENAME, /* < 1, 36(old), 37(new) */
YAHOO_SERVICE_SYSMESSAGE = 0x14,
YAHOO_SERVICE_SKINNAME = 0x15,
YAHOO_SERVICE_PASSTHROUGH2 = 0x16,
YAHOO_SERVICE_CONFINVITE = 0x18,
YAHOO_SERVICE_CONFLOGON,
YAHOO_SERVICE_CONFDECLINE,
YAHOO_SERVICE_CONFLOGOFF,
YAHOO_SERVICE_CONFADDINVITE,
YAHOO_SERVICE_CONFMSG,
YAHOO_SERVICE_CHATLOGON,
YAHOO_SERVICE_CHATLOGOFF,
YAHOO_SERVICE_CHATMSG = 0x20,
YAHOO_SERVICE_GAMELOGON = 0x28,
YAHOO_SERVICE_GAMELOGOFF,
YAHOO_SERVICE_GAMEMSG = 0x2a,
YAHOO_SERVICE_FILETRANSFER = 0x46,
YAHOO_SERVICE_VOICECHAT = 0x4A,
YAHOO_SERVICE_NOTIFY,
YAHOO_SERVICE_VERIFY,
YAHOO_SERVICE_P2PFILEXFER,
YAHOO_SERVICE_PEERTOPEER = 0x4F, /* Checks if P2P possible */
YAHOO_SERVICE_WEBCAM,
YAHOO_SERVICE_AUTHRESP = 0x54,
YAHOO_SERVICE_LIST,
YAHOO_SERVICE_AUTH = 0x57,
YAHOO_SERVICE_AUTHBUDDY = 0x6d,
YAHOO_SERVICE_ADDBUDDY = 0x83,
YAHOO_SERVICE_REMBUDDY,
YAHOO_SERVICE_IGNORECONTACT, /* > 1, 7, 13 < 1, 66, 13, 0 */
YAHOO_SERVICE_REJECTCONTACT,
YAHOO_SERVICE_GROUPRENAME = 0x89, /* > 1, 65(new), 66(0), 67(old) */
YAHOO_SERVICE_Y7_PING = 0x8A,
YAHOO_SERVICE_CHATONLINE = 0x96, /* > 109(id), 1, 6(abcde) < 0,1 */
YAHOO_SERVICE_CHATGOTO,
YAHOO_SERVICE_CHATJOIN, /* > 1 104-room 129-1600326591 62-2 */
YAHOO_SERVICE_CHATLEAVE,
YAHOO_SERVICE_CHATEXIT = 0x9b,
YAHOO_SERVICE_CHATADDINVITE = 0x9d,
YAHOO_SERVICE_CHATLOGOUT = 0xa0,
YAHOO_SERVICE_CHATPING,
YAHOO_SERVICE_COMMENT = 0xa8,
YAHOO_SERVICE_GAME_INVITE = 0xb7,
YAHOO_SERVICE_STEALTH_PERM = 0xb9,
YAHOO_SERVICE_STEALTH_SESSION = 0xba,
YAHOO_SERVICE_AVATAR = 0xbc,
YAHOO_SERVICE_PICTURE_CHECKSUM = 0xbd,
YAHOO_SERVICE_PICTURE = 0xbe,
YAHOO_SERVICE_PICTURE_UPDATE = 0xc1,
YAHOO_SERVICE_PICTURE_UPLOAD = 0xc2,
YAHOO_SERVICE_YAB_UPDATE = 0xc4,
YAHOO_SERVICE_Y6_VISIBLE_TOGGLE = 0xc5, /* YMSG13, key 13: 2 = invisible, 1 = visible */
YAHOO_SERVICE_Y6_STATUS_UPDATE = 0xc6, /* YMSG13 */
YAHOO_SERVICE_PICTURE_STATUS = 0xc7, /* YMSG13, key 213: 0 = none, 1 = avatar, 2 = picture */
YAHOO_SERVICE_VERIFY_ID_EXISTS = 0xc8,
YAHOO_SERVICE_AUDIBLE = 0xd0,
YAHOO_SERVICE_Y7_PHOTO_SHARING = 0xd2,
YAHOO_SERVICE_Y7_CONTACT_DETAILS = 0xd3, /* YMSG13 */
YAHOO_SERVICE_Y7_CHAT_SESSION = 0xd4,
YAHOO_SERVICE_Y7_AUTHORIZATION = 0xd6, /* YMSG13 */
YAHOO_SERVICE_Y7_FILETRANSFER = 0xdc, /* YMSG13 */
YAHOO_SERVICE_Y7_FILETRANSFERINFO, /* YMSG13 */
YAHOO_SERVICE_Y7_FILETRANSFERACCEPT, /* YMSG13 */
YAHOO_SERVICE_Y7_MINGLE = 0xe1, /* YMSG13 */
YAHOO_SERVICE_Y7_CHANGE_GROUP = 0xe7, /* YMSG13 */
YAHOO_SERVICE_MYSTERY = 0xef, /* Don't know what this is for */
YAHOO_SERVICE_Y8_STATUS = 0xf0, /* YMSG15 */
YAHOO_SERVICE_Y8_LIST = 0Xf1, /* YMSG15 */
YAHOO_SERVICE_MESSAGE_CONFIRM = 0xfb,
YAHOO_SERVICE_WEBLOGIN = 0x0226,
YAHOO_SERVICE_SMS_MSG = 0x02ea
};
enum yahoo_status {
YAHOO_STATUS_AVAILABLE = 0,
YAHOO_STATUS_BRB,
YAHOO_STATUS_BUSY,
YAHOO_STATUS_NOTATHOME,
YAHOO_STATUS_NOTATDESK,
YAHOO_STATUS_NOTINOFFICE,
YAHOO_STATUS_ONPHONE,
YAHOO_STATUS_ONVACATION,
YAHOO_STATUS_OUTTOLUNCH,
YAHOO_STATUS_STEPPEDOUT,
YAHOO_STATUS_INVISIBLE = 12,
YAHOO_STATUS_CUSTOM = 99,
YAHOO_STATUS_IDLE = 999,
YAHOO_STATUS_OFFLINE = 0x5a55aa56 /* don't ask */
};
enum ypacket_status {
YPACKET_STATUS_DISCONNECTED = -1,
YPACKET_STATUS_DEFAULT = 0,
YPACKET_STATUS_SERVERACK = 1,
YPACKET_STATUS_GAME = 0x2,
YPACKET_STATUS_AWAY = 0x4,
YPACKET_STATUS_CONTINUED = 0x5,
YPACKET_STATUS_INVISIBLE = 12,
YPACKET_STATUS_NOTIFY = 0x16, /* TYPING */
YPACKET_STATUS_WEBLOGIN = 0x5a55aa55,
YPACKET_STATUS_OFFLINE = 0x5a55aa56
};
#define YAHOO_STATUS_GAME 0x2 /* Games don't fit into the regular status model */
enum yahoo_login_status {
YAHOO_LOGIN_OK = 0,
YAHOO_LOGIN_LOGOFF = 1,
YAHOO_LOGIN_UNAME = 3,
YAHOO_LOGIN_PASSWD = 13,
YAHOO_LOGIN_LOCK = 14,
YAHOO_LOGIN_DUPL = 99,
YAHOO_LOGIN_SOCK = -1,
YAHOO_LOGIN_UNKNOWN = 999
};
enum yahoo_error {
E_UNKNOWN = -1,
E_CONNECTION = -2,
E_SYSTEM = -3,
E_CUSTOM = 0,
/* responses from ignore buddy */
E_IGNOREDUP = 2,
E_IGNORENONE = 3,
E_IGNORECONF = 12,
/* conference */
E_CONFNOTAVAIL = 20
};
enum yahoo_log_level {
YAHOO_LOG_NONE = 0,
YAHOO_LOG_FATAL,
YAHOO_LOG_ERR,
YAHOO_LOG_WARNING,
YAHOO_LOG_NOTICE,
YAHOO_LOG_INFO,
YAHOO_LOG_DEBUG
};
enum yahoo_file_transfer {
YAHOO_FILE_TRANSFER_INIT = 1,
YAHOO_FILE_TRANSFER_ACCEPT = 3,
YAHOO_FILE_TRANSFER_REJECT = 4,
YAHOO_FILE_TRANSFER_DONE = 5,
YAHOO_FILE_TRANSFER_RELAY,
YAHOO_FILE_TRANSFER_FAILED,
YAHOO_FILE_TRANSFER_UNKNOWN
};
#define YAHOO_PROTO_VER 0x0010
/* Yahoo style/color directives */
#define YAHOO_COLOR_BLACK "\033[30m"
#define YAHOO_COLOR_BLUE "\033[31m"
#define YAHOO_COLOR_LIGHTBLUE "\033[32m"
#define YAHOO_COLOR_GRAY "\033[33m"
#define YAHOO_COLOR_GREEN "\033[34m"
#define YAHOO_COLOR_PINK "\033[35m"
#define YAHOO_COLOR_PURPLE "\033[36m"
#define YAHOO_COLOR_ORANGE "\033[37m"
#define YAHOO_COLOR_RED "\033[38m"
#define YAHOO_COLOR_OLIVE "\033[39m"
#define YAHOO_COLOR_ANY "\033[#"
#define YAHOO_STYLE_ITALICON "\033[2m"
#define YAHOO_STYLE_ITALICOFF "\033[x2m"
#define YAHOO_STYLE_BOLDON "\033[1m"
#define YAHOO_STYLE_BOLDOFF "\033[x1m"
#define YAHOO_STYLE_UNDERLINEON "\033[4m"
#define YAHOO_STYLE_UNDERLINEOFF "\033[x4m"
#define YAHOO_STYLE_URLON "\033[lm"
#define YAHOO_STYLE_URLOFF "\033[xlm"
enum yahoo_connection_type {
YAHOO_CONNECTION_PAGER = 0,
YAHOO_CONNECTION_FT,
YAHOO_CONNECTION_YAB,
YAHOO_CONNECTION_WEBCAM_MASTER,
YAHOO_CONNECTION_WEBCAM,
YAHOO_CONNECTION_CHATCAT,
YAHOO_CONNECTION_SEARCH,
YAHOO_CONNECTION_AUTH
};
enum yahoo_webcam_direction_type {
YAHOO_WEBCAM_DOWNLOAD = 0,
YAHOO_WEBCAM_UPLOAD
};
enum yahoo_stealth_visibility_type {
YAHOO_STEALTH_DEFAULT = 0,
YAHOO_STEALTH_ONLINE,
YAHOO_STEALTH_PERM_OFFLINE
};
/* chat member attribs */
#define YAHOO_CHAT_MALE 0x8000
#define YAHOO_CHAT_FEMALE 0x10000
#define YAHOO_CHAT_FEMALE 0x10000
#define YAHOO_CHAT_DUNNO 0x400
#define YAHOO_CHAT_WEBCAM 0x10
enum yahoo_webcam_conn_type { Y_WCM_DIALUP, Y_WCM_DSL, Y_WCM_T1 };
struct yahoo_webcam {
int direction; /* Uploading or downloading */
int conn_type; /* 0=Dialup, 1=DSL/Cable, 2=T1/Lan */
char *user; /* user we are viewing */
char *server; /* webcam server to connect to */
int port; /* webcam port to connect on */
char *key; /* key to connect to the server with */
char *description; /* webcam description */
char *my_ip; /* own ip number */
};
struct yahoo_webcam_data {
unsigned int data_size;
unsigned int to_read;
unsigned int timestamp;
unsigned char packet_type;
};
struct yahoo_data {
char *user;
char *password;
char *cookie_y;
char *cookie_t;
char *cookie_c;
char *cookie_b;
char *login_cookie;
char *crumb;
char *seed;
YList *buddies;
YList *ignore;
YList *identities;
char *login_id;
int current_status;
int initial_status;
int logged_in;
int session_id;
int client_id;
char *rawbuddylist;
char *ignorelist;
void *server_settings;
struct yahoo_process_status_entry *half_user;
};
struct yab {
int yid;
char *id;
char *fname;
char *lname;
char *nname;
char *email;
char *hphone;
char *wphone;
char *mphone;
int dbid;
};
struct yahoo_buddy {
char *group;
char *id;
char *real_name;
struct yab *yab_entry;
};
enum yahoo_search_type {
YAHOO_SEARCH_KEYWORD = 0,
YAHOO_SEARCH_YID,
YAHOO_SEARCH_NAME
};
enum yahoo_search_gender {
YAHOO_GENDER_NONE = 0,
YAHOO_GENDER_MALE,
YAHOO_GENDER_FEMALE
};
enum yahoo_search_agerange {
YAHOO_AGERANGE_NONE = 0
};
struct yahoo_found_contact {
char *id;
char *gender;
char *location;
int age;
int online;
};
/*
* Function pointer to be passed to http get/post and send file
*/
typedef void (*yahoo_get_fd_callback) (int id, void *fd, int error,
void *data);
/*
* Function pointer to be passed to yahoo_get_url_handle
*/
typedef void (*yahoo_get_url_handle_callback) (int id, void *fd,
int error, const char *filename, unsigned long size,
void *data);
struct yahoo_chat_member {
char *id;
int age;
int attribs;
char *alias;
char *location;
};
struct yahoo_process_status_entry {
char *name; /* 7 name */
int state; /* 10 state */
int flags; /* 13 flags, bit 0 = pager, bit 1 = chat, bit 2 = game */
int mobile; /* 60 mobile */
char *msg; /* 19 custom status message */
int away; /* 47 away (or invisible) */
int buddy_session; /* 11 state */
int f17; /* 17 in chat? then what about flags? */
int idle; /* 137 seconds idle */
int f138; /* 138 state */
char *f184; /* 184 state */
int f192; /* 192 state */
int f10001; /* 10001 state */
int f10002; /* 10002 state */
int f198; /* 198 state */
char *f197; /* 197 state */
char *f205; /* 205 state */
int f213; /* 213 state */
};
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,36 @@
/*
* libyahoo2: yahoo_debug.h
*
* Copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
extern int yahoo_log_message(char *fmt, ...);
#define NOTICE(x) if(yahoo_get_log_level() >= YAHOO_LOG_NOTICE) { yahoo_log_message x; yahoo_log_message("\n"); }
#define LOG(x) if(yahoo_get_log_level() >= YAHOO_LOG_INFO) { yahoo_log_message("%s:%d: ", __FILE__, __LINE__); \
yahoo_log_message x; \
yahoo_log_message("\n"); }
#define WARNING(x) if(yahoo_get_log_level() >= YAHOO_LOG_WARNING) { yahoo_log_message("%s:%d: warning: ", __FILE__, __LINE__); \
yahoo_log_message x; \
yahoo_log_message("\n"); }
#define DEBUG_MSG(x) if(yahoo_get_log_level() >= YAHOO_LOG_DEBUG) { yahoo_log_message("%s:%d: debug: ", __FILE__, __LINE__); \
yahoo_log_message x; \
yahoo_log_message("\n"); }

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,32 @@
/*
* libyahoo2 - originally from gaim patches by Amatus
*
* Copyright (C) 2003-2004
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define IDENT 1 /* identify function */
#define XOR 2 /* xor with arg1 */
#define MULADD 3 /* multipy by arg1 then add arg2 */
#define LOOKUP 4 /* lookup each byte in the table pointed to by arg1 */
#define BITFLD 5 /* reorder bits according to table pointed to by arg1 */
struct yahoo_fn {
int type;
long arg1, arg2;
};
int yahoo_xfrm(int table, int depth, int seed);

View file

@ -0,0 +1,404 @@
/*
* libyahoo2: yahoo_httplib.c
*
* Copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#if STDC_HEADERS
# include <string.h>
#else
# if !HAVE_STRCHR
# define strchr index
# define strrchr rindex
# endif
char *strchr(), *strrchr();
# if !HAVE_MEMCPY
# define memcpy(d, s, n) bcopy ((s), (d), (n))
# define memmove(d, s, n) bcopy ((s), (d), (n))
# endif
#endif
#include <errno.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <ctype.h>
#include "yahoo2.h"
#include "yahoo2_callbacks.h"
#include "yahoo_httplib.h"
#include "yahoo_util.h"
#include "yahoo_debug.h"
#ifdef __MINGW32__
# include <winsock2.h>
# define snprintf _snprintf
#endif
extern struct yahoo_callbacks *yc;
#define YAHOO_CALLBACK(x) yc->x
extern enum yahoo_log_level log_level;
int yahoo_tcp_readline(char *ptr, int maxlen, void *fd)
{
int n, rc;
char c;
for (n = 1; n < maxlen; n++) {
do {
rc = YAHOO_CALLBACK(ext_yahoo_read) (fd, &c, 1);
} while (rc == -1 && (errno == EINTR || errno == EAGAIN)); /* this is bad - it should be done asynchronously */
if (rc == 1) {
if (c == '\r') /* get rid of \r */
continue;
*ptr = c;
if (c == '\n')
break;
ptr++;
} else if (rc == 0) {
if (n == 1)
return (0); /* EOF, no data */
else
break; /* EOF, w/ data */
} else {
return -1;
}
}
*ptr = 0;
return (n);
}
static int url_to_host_port_path(const char *url,
char *host, int *port, char *path, int *ssl)
{
char *urlcopy = NULL;
char *slash = NULL;
char *colon = NULL;
/*
* http://hostname
* http://hostname/
* http://hostname/path
* http://hostname/path:foo
* http://hostname:port
* http://hostname:port/
* http://hostname:port/path
* http://hostname:port/path:foo
* and https:// variants of the above
*/
if (strstr(url, "http://") == url) {
urlcopy = strdup(url + 7);
} else if (strstr(url, "https://") == url) {
urlcopy = strdup(url + 8);
*ssl = 1;
} else {
WARNING(("Weird url - unknown protocol: %s", url));
return 0;
}
slash = strchr(urlcopy, '/');
colon = strchr(urlcopy, ':');
if (!colon || (slash && slash < colon)) {
if (*ssl)
*port = 443;
else
*port = 80;
} else {
*colon = 0;
*port = atoi(colon + 1);
}
if (!slash) {
strcpy(path, "/");
} else {
strcpy(path, slash);
*slash = 0;
}
strcpy(host, urlcopy);
FREE(urlcopy);
return 1;
}
static int isurlchar(unsigned char c)
{
return (isalnum(c));
}
char *yahoo_urlencode(const char *instr)
{
int ipos = 0, bpos = 0;
char *str = NULL;
int len = strlen(instr);
if (!(str = y_new(char, 3 *len + 1)))
return "";
while (instr[ipos]) {
while (isurlchar(instr[ipos]))
str[bpos++] = instr[ipos++];
if (!instr[ipos])
break;
snprintf(&str[bpos], 4, "%%%02x", instr[ipos] & 0xff);
bpos += 3;
ipos++;
}
str[bpos] = '\0';
/* free extra alloc'ed mem. */
len = strlen(str);
str = y_renew(char, str, len + 1);
return (str);
}
char *yahoo_urldecode(const char *instr)
{
int ipos = 0, bpos = 0;
char *str = NULL;
char entity[3] = { 0, 0, 0 };
unsigned dec;
int len = strlen(instr);
if (!(str = y_new(char, len + 1)))
return "";
while (instr[ipos]) {
while (instr[ipos] && instr[ipos] != '%')
if (instr[ipos] == '+') {
str[bpos++] = ' ';
ipos++;
} else
str[bpos++] = instr[ipos++];
if (!instr[ipos])
break;
if (instr[ipos + 1] && instr[ipos + 2]) {
ipos++;
entity[0] = instr[ipos++];
entity[1] = instr[ipos++];
sscanf(entity, "%2x", &dec);
str[bpos++] = (char)dec;
} else {
str[bpos++] = instr[ipos++];
}
}
str[bpos] = '\0';
/* free extra alloc'ed mem. */
len = strlen(str);
str = y_renew(char, str, len + 1);
return (str);
}
char *yahoo_xmldecode(const char *instr)
{
int ipos = 0, bpos = 0, epos = 0;
char *str = NULL;
char entity[4] = { 0, 0, 0, 0 };
char *entitymap[5][2] = {
{"amp;", "&"},
{"quot;", "\""},
{"lt;", "<"},
{"gt;", "<"},
{"nbsp;", " "}
};
unsigned dec;
int len = strlen(instr);
if (!(str = y_new(char, len + 1)))
return "";
while (instr[ipos]) {
while (instr[ipos] && instr[ipos] != '&')
if (instr[ipos] == '+') {
str[bpos++] = ' ';
ipos++;
} else
str[bpos++] = instr[ipos++];
if (!instr[ipos] || !instr[ipos + 1])
break;
ipos++;
if (instr[ipos] == '#') {
ipos++;
epos = 0;
while (instr[ipos] != ';')
entity[epos++] = instr[ipos++];
sscanf(entity, "%u", &dec);
str[bpos++] = (char)dec;
ipos++;
} else {
int i;
for (i = 0; i < 5; i++)
if (!strncmp(instr + ipos, entitymap[i][0],
strlen(entitymap[i][0]))) {
str[bpos++] = entitymap[i][1][0];
ipos += strlen(entitymap[i][0]);
break;
}
}
}
str[bpos] = '\0';
/* free extra alloc'ed mem. */
len = strlen(str);
str = y_renew(char, str, len + 1);
return (str);
}
typedef void (*http_connected) (int id, void *fd, int error);
struct callback_data {
int id;
yahoo_get_fd_callback callback;
char *request;
void *user_data;
};
static void connect_complete(void *fd, int error, void *data)
{
struct callback_data *ccd = data;
if (error == 0)
YAHOO_CALLBACK(ext_yahoo_write) (fd, ccd->request,
strlen(ccd->request));
free(ccd->request);
ccd->callback(ccd->id, fd, error, ccd->user_data);
FREE(ccd);
}
static void yahoo_send_http_request(int id, char *host, int port, char *request,
yahoo_get_fd_callback callback, void *data, int use_ssl)
{
struct callback_data *ccd = y_new0(struct callback_data, 1);
ccd->callback = callback;
ccd->id = id;
ccd->request = strdup(request);
ccd->user_data = data;
YAHOO_CALLBACK(ext_yahoo_connect_async) (id, host, port,
connect_complete, ccd, use_ssl);
}
void yahoo_http_post(int id, const char *url, const char *cookies,
long content_length, yahoo_get_fd_callback callback, void *data)
{
char host[255];
int port = 80;
char path[255];
char buff[1024];
int ssl = 0;
if (!url_to_host_port_path(url, host, &port, path, &ssl))
return;
/* thanks to kopete dumpcap */
snprintf(buff, sizeof(buff),
"POST %s HTTP/1.1\r\n"
"Cookie: %s\r\n"
"User-Agent: Mozilla/5.0\r\n"
"Host: %s\r\n"
"Content-Length: %ld\r\n"
"Cache-Control: no-cache\r\n"
"\r\n", path, cookies, host, content_length);
yahoo_send_http_request(id, host, port, buff, callback, data, ssl);
}
void yahoo_http_get(int id, const char *url, const char *cookies, int http11,
int keepalive, yahoo_get_fd_callback callback, void *data)
{
char host[255];
int port = 80;
char path[255];
char buff[2048];
char cookiebuff[1024];
int ssl = 0;
if (!url_to_host_port_path(url, host, &port, path, &ssl))
return;
/* Allow cases when we don't need to send a cookie */
if (cookies)
snprintf(cookiebuff, sizeof(cookiebuff), "Cookie: %s\r\n",
cookies);
else
cookiebuff[0] = '\0';
snprintf(buff, sizeof(buff),
"GET %s HTTP/1.%s\r\n"
"%sHost: %s\r\n"
"User-Agent: Mozilla/4.5 [en] (" "1" "/" "1" ")\r\n"
"Accept: */*\r\n"
"%s" "\r\n", path, http11?"1":"0", cookiebuff, host,
keepalive? "Connection: Keep-Alive\r\n":"Connection: close\r\n");
yahoo_send_http_request(id, host, port, buff, callback, data, ssl);
}
void yahoo_http_head(int id, const char *url, const char *cookies, int len,
char *payload, yahoo_get_fd_callback callback, void *data)
{
char host[255];
int port = 80;
char path[255];
char buff[2048];
char cookiebuff[1024];
int ssl = 0;
if (!url_to_host_port_path(url, host, &port, path, &ssl))
return;
/* Allow cases when we don't need to send a cookie */
if (cookies)
snprintf(cookiebuff, sizeof(cookiebuff), "Cookie: %s\r\n",
cookies);
else
cookiebuff[0] = '\0';
snprintf(buff, sizeof(buff),
"HEAD %s HTTP/1.0\r\n"
"Accept: */*\r\n"
"Host: %s:%d\r\n"
"User-Agent: Mozilla/4.5 [en] (" "1" "/" "1" ")\r\n"
"%s"
"Content-Length: %d\r\n"
"Cache-Control: no-cache\r\n"
"\r\n%s", path, host, port, cookiebuff, len,
payload?payload:"");
yahoo_send_http_request(id, host, port, buff, callback, data, ssl);
}

View file

@ -0,0 +1,48 @@
/*
* libyahoo2: yahoo_httplib.h
*
* Copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef YAHOO_HTTPLIB_H
#define YAHOO_HTTPLIB_H
#ifdef __cplusplus
extern "C" {
#endif
#include "yahoo2_types.h"
char *yahoo_urlencode(const char *instr);
char *yahoo_urldecode(const char *instr);
char *yahoo_xmldecode(const char *instr);
int yahoo_tcp_readline(char *ptr, int maxlen, void *fd);
void yahoo_http_post(int id, const char *url, const char *cookies,
long size, yahoo_get_fd_callback callback, void *data);
void yahoo_http_get(int id, const char *url, const char *cookies,
int http11, int keepalive, yahoo_get_fd_callback callback,
void *data);
void yahoo_http_head(int id, const char *url, const char *cookies,
int size, char *payload, yahoo_get_fd_callback callback,
void *data);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,233 @@
/*
* yahoo_list.c: linked list routines
*
* Some code copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
* Other code copyright Meredydd Luff <meredydd AT everybuddy.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Some of this code was borrowed from elist.c in the eb-lite sources
*
*/
#include <stdlib.h>
#include "yahoo_list.h"
YList *y_list_append(YList *list, void *data)
{
YList *n;
YList *new_list = malloc(sizeof(YList));
YList *attach_to = NULL;
new_list->next = NULL;
new_list->data = data;
for (n = list; n != NULL; n = n->next) {
attach_to = n;
}
if (attach_to == NULL) {
new_list->prev = NULL;
return new_list;
} else {
new_list->prev = attach_to;
attach_to->next = new_list;
return list;
}
}
YList *y_list_prepend(YList *list, void *data)
{
YList *n = malloc(sizeof(YList));
n->next = list;
n->prev = NULL;
n->data = data;
if (list)
list->prev = n;
return n;
}
YList *y_list_concat(YList *list, YList *add)
{
YList *l;
if (!list)
return add;
if (!add)
return list;
for (l = list; l->next; l = l->next) ;
l->next = add;
add->prev = l;
return list;
}
YList *y_list_remove(YList *list, void *data)
{
YList *n;
for (n = list; n != NULL; n = n->next) {
if (n->data == data) {
list = y_list_remove_link(list, n);
y_list_free_1(n);
break;
}
}
return list;
}
/* Warning */
/* link MUST be part of list */
/* caller must free link using y_list_free_1 */
YList *y_list_remove_link(YList *list, const YList *link)
{
if (!link)
return list;
if (link->next)
link->next->prev = link->prev;
if (link->prev)
link->prev->next = link->next;
if (link == list)
list = link->next;
return list;
}
int y_list_length(const YList *list)
{
int retval = 0;
const YList *n = list;
for (n = list; n != NULL; n = n->next) {
retval++;
}
return retval;
}
/* well, you could just check for list == NULL, but that would be
* implementation dependent
*/
int y_list_empty(const YList *list)
{
if (!list)
return 1;
else
return 0;
}
int y_list_singleton(const YList *list)
{
if (!list || list->next)
return 0;
return 1;
}
YList *y_list_copy(YList *list)
{
YList *n;
YList *copy = NULL;
for (n = list; n != NULL; n = n->next) {
copy = y_list_append(copy, n->data);
}
return copy;
}
void y_list_free_1(YList *list)
{
free(list);
}
void y_list_free(YList *list)
{
YList *n = list;
while (n != NULL) {
YList *next = n->next;
free(n);
n = next;
}
}
YList *y_list_find(YList *list, const void *data)
{
YList *l;
for (l = list; l && l->data != data; l = l->next) ;
return l;
}
void y_list_foreach(YList *list, YListFunc fn, void *user_data)
{
for (; list; list = list->next)
fn(list->data, user_data);
}
YList *y_list_find_custom(YList *list, const void *data, YListCompFunc comp)
{
YList *l;
for (l = list; l; l = l->next)
if (comp(l->data, data) == 0)
return l;
return NULL;
}
YList *y_list_nth(YList *list, int n)
{
int i = n;
for (; list && i; list = list->next, i--) ;
return list;
}
YList *y_list_insert_sorted(YList *list, void *data, YListCompFunc comp)
{
YList *l, *n, *prev = NULL;
if (!list)
return y_list_append(list, data);
n = malloc(sizeof(YList));
n->data = data;
for (l = list; l && comp(l->data, n->data) <= 0; l = l->next)
prev = l;
if (l) {
n->prev = l->prev;
l->prev = n;
} else
n->prev = prev;
n->next = l;
if (n->prev) {
n->prev->next = n;
return list;
} else {
return n;
}
}

View file

@ -0,0 +1,76 @@
/*
* yahoo_list.h: linked list routines
*
* Some code copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
* Other code copyright Meredydd Luff <meredydd AT everybuddy.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*
* This is a replacement for the GList. It only provides functions that
* we use in Ayttm. Thanks to Meredyyd from everybuddy dev for doing
* most of it.
*/
#ifndef __YLIST_H__
#define __YLIST_H__
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _YList {
struct _YList *next;
struct _YList *prev;
void *data;
} YList;
typedef int (*YListCompFunc) (const void *, const void *);
typedef void (*YListFunc) (void *, void *);
YList *y_list_append(YList *list, void *data);
YList *y_list_prepend(YList *list, void *data);
YList *y_list_remove_link(YList *list, const YList *link);
YList *y_list_remove(YList *list, void *data);
YList *y_list_insert_sorted(YList *list, void *data,
YListCompFunc comp);
YList *y_list_copy(YList *list);
YList *y_list_concat(YList *list, YList *add);
YList *y_list_find(YList *list, const void *data);
YList *y_list_find_custom(YList *list, const void *data,
YListCompFunc comp);
YList *y_list_nth(YList *list, int n);
void y_list_foreach(YList *list, YListFunc fn, void *user_data);
void y_list_free_1(YList *list);
void y_list_free(YList *list);
int y_list_length(const YList *list);
int y_list_empty(const YList *list);
int y_list_singleton(const YList *list);
#define y_list_next(list) list->next
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,162 @@
/*
* libyahoo2: yahoo_util.c
*
* Copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#if STDC_HEADERS
# include <string.h>
#else
# if !HAVE_STRCHR
# define strchr index
# define strrchr rindex
# endif
char *strchr(), *strrchr();
# if !HAVE_MEMCPY
# define memcpy(d, s, n) bcopy ((s), (d), (n))
# define memmove(d, s, n) bcopy ((s), (d), (n))
# endif
#endif
#include "yahoo_util.h"
char *y_string_append(char *string, char *append)
{
int size = strlen(string) + strlen(append) + 1;
char *new_string = y_renew(char, string, size);
if (new_string == NULL) {
new_string = y_new(char, size);
strcpy(new_string, string);
FREE(string);
}
strcat(new_string, append);
return new_string;
}
char *y_str_to_utf8(const char *in)
{
unsigned int n, i = 0;
char *result = NULL;
if (in == NULL || *in == '\0')
return strdup("");
result = y_new(char, strlen(in) * 2 + 1);
/* convert a string to UTF-8 Format */
for (n = 0; n < strlen(in); n++) {
unsigned char c = (unsigned char)in[n];
if (c < 128) {
result[i++] = (char)c;
} else {
result[i++] = (char)((c >> 6) | 192);
result[i++] = (char)((c & 63) | 128);
}
}
result[i] = '\0';
return result;
}
char *y_utf8_to_str(const char *in)
{
int i = 0;
unsigned int n;
char *result = NULL;
if (in == NULL || *in == '\0')
return strdup("");
result = y_new(char, strlen(in) + 1);
/* convert a string from UTF-8 Format */
for (n = 0; n < strlen(in); n++) {
unsigned char c = in[n];
if (c < 128) {
result[i++] = (char)c;
} else {
result[i++] = (c << 6) | (in[++n] & 63);
}
}
result[i] = '\0';
return result;
}
#if !HAVE_GLIB
void y_strfreev(char **vector)
{
char **v;
for (v = vector; *v; v++) {
FREE(*v);
}
FREE(vector);
}
char **y_strsplit(char *str, char *sep, int nelem)
{
char **vector;
char *s, *p;
int i = 0;
int l = strlen(sep);
if (nelem <= 0) {
char *s;
nelem = 0;
if (*str) {
for (s = strstr(str, sep); s;
s = strstr(s + l, sep), nelem++) ;
if (strcmp(str + strlen(str) - l, sep))
nelem++;
}
}
vector = y_new(char *, nelem + 1);
for (p = str, s = strstr(p, sep); i < nelem && s;
p = s + l, s = strstr(p, sep), i++) {
int len = s - p;
vector[i] = y_new(char, len + 1);
strncpy(vector[i], p, len);
vector[i][len] = '\0';
}
if (i < nelem && *str) /* str didn't end with sep, and str isn't empty */
vector[i++] = strdup(p);
vector[i] = NULL;
return vector;
}
void *y_memdup(const void *addr, int n)
{
void *new_chunk = malloc(n);
if (new_chunk)
memcpy(new_chunk, addr, n);
return new_chunk;
}
#endif

View file

@ -0,0 +1,103 @@
/*
* libyahoo2: yahoo_util.h
*
* Copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef __YAHOO_UTIL_H__
#define __YAHOO_UTIL_H__
#if HAVE_CONFIG_H
# include <config.h>
#endif
#if HAVE_GLIB
# include <glib.h>
# define FREE(x) if(x) {g_free(x); x=NULL;}
# define y_new g_new
# define y_new0 g_new0
# define y_renew g_renew
# define y_memdup g_memdup
# define y_strsplit g_strsplit
# define y_strfreev g_strfreev
# ifndef strdup
# define strdup g_strdup
# endif
# ifndef strncasecmp
# define strncasecmp g_strncasecmp
# define strcasecmp g_strcasecmp
# endif
# define snprintf g_snprintf
# define vsnprintf g_vsnprintf
#else
# include <stdlib.h>
# include <stdarg.h>
# define FREE(x) if(x) {free(x); x=NULL;}
# define y_new(type, n) (type *)malloc(sizeof(type) * (n))
# define y_new0(type, n) (type *)calloc((n), sizeof(type))
# define y_renew(type, mem, n) (type *)realloc(mem, n)
void *y_memdup(const void *addr, int n);
char **y_strsplit(char *str, char *sep, int nelem);
void y_strfreev(char **vector);
#ifndef _WIN32
int strncasecmp(const char *s1, const char *s2, size_t n);
int strcasecmp(const char *s1, const char *s2);
char *strdup(const char *s);
int snprintf(char *str, size_t size, const char *format, ...);
int vsnprintf(char *str, size_t size, const char *format, va_list ap);
#endif
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef MIN
#define MIN(x,y) ((x)<(y)?(x):(y))
#endif
#ifndef MAX
#define MAX(x,y) ((x)>(y)?(x):(y))
#endif
/*
* The following three functions return newly allocated memory.
* You must free it yourself
*/
char *y_string_append(char *str, char *append);
char *y_str_to_utf8(const char *in);
char *y_utf8_to_str(const char *in);
#endif

View file

@ -0,0 +1,42 @@
#pragma once
// Transport includes
#include "transport/config.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
// Yahoo2
#include <yahoo2.h>
#include <yahoo2_callbacks.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
// Swiften
#include "Swiften/Swiften.h"
#include "Swiften/TLS/OpenSSL/OpenSSLContextFactory.h"
// Boost
#include <boost/algorithm/string.hpp>
using namespace boost::filesystem;
using namespace boost::program_options;
using namespace Transport;
class YahooLocalAccount;
class YahooHandler {
public:
YahooHandler(YahooLocalAccount *account, int conn_tag, int handler_tag, void *data, yahoo_input_condition cond);
virtual ~YahooHandler();
void ready(std::string *buffer = NULL);
int handler_tag;
int conn_tag;
void *data;
yahoo_input_condition cond;
bool remove_later;
YahooLocalAccount *account;
};

View file

@ -0,0 +1,60 @@
#include "yahoolocalaccount.h"
#include "yahoohandler.h"
YahooLocalAccount::YahooLocalAccount(const std::string &user, const std::string &legacyName, const std::string &password) : user(user), id(0), conn_tag(1), handler_tag(1), status(YAHOO_STATUS_OFFLINE), msg(""), buffer("") {
id = yahoo_init_with_attributes(legacyName.c_str(), password.c_str(),
"local_host", "",
"pager_port", 5050,
NULL);
}
YahooLocalAccount::~YahooLocalAccount() {
// remove handlers
for (std::map<int, YahooHandler *>::iterator it = handlers.begin(); it != handlers.end(); it++) {
delete it->second;
}
// remove conns
for (std::map<int, boost::shared_ptr<Swift::Connection> >::iterator it = conns.begin(); it != conns.end(); it++) {
it->second->onConnectFinished.disconnect_all_slots();
it->second->onDisconnected.disconnect_all_slots();
it->second->onDataRead.disconnect_all_slots();
it->second->onDataWritten.disconnect_all_slots();
}
}
void YahooLocalAccount::login() {
yahoo_login(id, YAHOO_STATUS_AVAILABLE);
}
void YahooLocalAccount::addHandler(YahooHandler *handler) {
handlers[handler->handler_tag] = handler;
handlers_per_conn[handler->conn_tag][handler->handler_tag] = handler;
}
void YahooLocalAccount::removeOldHandlers() {
std::vector<int> handlers_to_remove;
for (std::map<int, YahooHandler *>::iterator it = handlers.begin(); it != handlers.end(); it++) {
if (it->second->remove_later) {
handlers_to_remove.push_back(it->first);
}
}
BOOST_FOREACH(int tag, handlers_to_remove) {
YahooHandler *handler = handlers[tag];
handlers.erase(tag);
handlers_per_conn[handler->conn_tag].erase(tag);
delete handler;
}
}
void YahooLocalAccount::removeConn(int conn_tag) {
for (std::map<int, YahooHandler *>::iterator it = handlers_per_conn[conn_tag].begin(); it != handlers_per_conn[conn_tag].end(); it++) {
it->second->remove_later = true;
}
removeOldHandlers();
conns.erase(conn_tag);
}

View file

@ -0,0 +1,50 @@
#pragma once
// Transport includes
#include "transport/config.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
// Yahoo2
#include <yahoo2.h>
#include <yahoo2_callbacks.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
// Swiften
#include "Swiften/Swiften.h"
#include "Swiften/TLS/OpenSSL/OpenSSLContextFactory.h"
// Boost
#include <boost/algorithm/string.hpp>
using namespace boost::filesystem;
using namespace boost::program_options;
using namespace Transport;
class YahooHandler;
class YahooLocalAccount {
public:
YahooLocalAccount(const std::string &user, const std::string &legacyName, const std::string &password);
virtual ~YahooLocalAccount();
void login();
void addHandler(YahooHandler *handler);
void removeOldHandlers();
void removeConn(int conn_tag);
std::string user;
int id;
std::map<int, boost::shared_ptr<Swift::Connection> > conns;
int conn_tag;
std::map<int, YahooHandler *> handlers;
std::map<int, std::map<int, YahooHandler *> > handlers_per_conn;
std::map<std::string, std::string> urls;
int handler_tag;
int status;
std::string msg;
std::string buffer;
};

View file

@ -42,27 +42,11 @@ class SpectrumNetworkPlugin;
SpectrumNetworkPlugin *np;
static gboolean nodaemon = FALSE;
static gchar *logfile = NULL;
static gchar *lock_file = NULL;
static gchar *host = NULL;
static int port = 10000;
static gboolean ver = FALSE;
static gboolean list_purple_settings = FALSE;
int m_sock;
static int writeInput;
static GOptionEntry options_entries[] = {
{ "nodaemon", 'n', 0, G_OPTION_ARG_NONE, &nodaemon, "Disable background daemon mode", NULL },
{ "logfile", 'l', 0, G_OPTION_ARG_STRING, &logfile, "Set file to log", NULL },
{ "pidfile", 'p', 0, G_OPTION_ARG_STRING, &lock_file, "File where to write transport PID", NULL },
{ "version", 'v', 0, G_OPTION_ARG_NONE, &ver, "Shows Spectrum version", NULL },
{ "list-purple-settings", 's', 0, G_OPTION_ARG_NONE, &list_purple_settings, "Lists purple settings which can be used in config file", NULL },
{ "host", 'h', 0, G_OPTION_ARG_STRING, &host, "Host to connect to", NULL },
{ "port", 'p', 0, G_OPTION_ARG_INT, &port, "Port to connect to", NULL },
{ NULL, 0, 0, G_OPTION_ARG_NONE, NULL, "", NULL }
};
static std::string host;
static int port = 10000;
DBusHandlerResult skype_notify_handler(DBusConnection *connection, DBusMessage *message, gpointer user_data);
@ -790,7 +774,7 @@ static void spectrum_sigchld_handler(int sig)
}
}
static int create_socket(char *host, int portno) {
static int create_socket(const char *host, int portno) {
struct sockaddr_in serv_addr;
int m_sock = socket(AF_INET, SOCK_STREAM, 0);
@ -843,97 +827,42 @@ static void log_glib_error(const gchar *string) {
}
int main(int argc, char **argv) {
GError *error = NULL;
GOptionContext *context;
context = g_option_context_new("config_file_name or profile name");
g_option_context_add_main_entries(context, options_entries, "");
if (!g_option_context_parse (context, &argc, &argv, &error)) {
std::cout << "option parsing failed: " << error->message << "\n";
return -1;
}
if (ver) {
// std::cout << VERSION << "\n";
std::cout << "verze\n";
g_option_context_free(context);
return 0;
}
if (argc != 2) {
#ifdef WIN32
std::cout << "Usage: spectrum.exe <configuration_file.cfg>\n";
#else
#if GLIB_CHECK_VERSION(2,14,0)
std::cout << g_option_context_get_help(context, FALSE, NULL);
#else
std::cout << "Usage: spectrum <configuration_file.cfg>\n";
std::cout << "See \"man spectrum\" for more info.\n";
#endif
#endif
}
else {
#ifndef WIN32
signal(SIGPIPE, SIG_IGN);
if (signal(SIGCHLD, spectrum_sigchld_handler) == SIG_ERR) {
std::cout << "SIGCHLD handler can't be set\n";
g_option_context_free(context);
return -1;
}
//
// if (signal(SIGINT, spectrum_sigint_handler) == SIG_ERR) {
// std::cout << "SIGINT handler can't be set\n";
// g_option_context_free(context);
// return -1;
// }
//
// if (signal(SIGTERM, spectrum_sigterm_handler) == SIG_ERR) {
// std::cout << "SIGTERM handler can't be set\n";
// g_option_context_free(context);
// return -1;
// }
//
// struct sigaction sa;
// memset(&sa, 0, sizeof(sa));
// sa.sa_handler = spectrum_sighup_handler;
// if (sigaction(SIGHUP, &sa, NULL)) {
// std::cout << "SIGHUP handler can't be set\n";
// g_option_context_free(context);
// return -1;
// }
#endif
Config config;
if (!config.load(argv[1])) {
std::cout << "Can't open " << argv[1] << " configuration file.\n";
return 1;
}
Logging::initBackendLogging(&config);
std::string error;
Config *cfg = Config::createFromArgs(argc, argv, error, host, port);
if (cfg == NULL) {
std::cerr << error;
return 1;
}
// initPurple(config);
Logging::initBackendLogging(cfg);
g_type_init();
g_type_init();
m_sock = create_socket(host, port);
m_sock = create_socket(host.c_str(), port);
g_set_printerr_handler(log_glib_error);
g_set_printerr_handler(log_glib_error);
GIOChannel *channel;
GIOCondition cond = (GIOCondition) G_IO_IN;
channel = g_io_channel_unix_new(m_sock);
g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, cond, transportDataReceived, NULL, io_destroy);
np = new SpectrumNetworkPlugin(&config, host, port);
np = new SpectrumNetworkPlugin(cfg, host, port);
GMainLoop *m_loop;
m_loop = g_main_loop_new(NULL, FALSE);
GMainLoop *m_loop;
m_loop = g_main_loop_new(NULL, FALSE);
if (m_loop) {
g_main_loop_run(m_loop);
}
if (m_loop) {
g_main_loop_run(m_loop);
}
g_option_context_free(context);
}

View file

@ -124,8 +124,8 @@ class SMSNetworkPlugin : public NetworkPlugin {
void handleSMSDir() {
std::string dir = "/var/spool/sms/incoming/";
if (config->getUnregistered().find("backend.incoming_dir") != config->getUnregistered().end()) {
dir = config->getUnregistered().find("backend.incoming_dir")->second;
if (CONFIG_HAS_KEY(config, "backend.incoming_dir")) {
dir = CONFIG_STRING(config, "backend.incoming_dir");
}
LOG4CXX_INFO(logger, "Checking directory " << dir << " for incoming SMS.");
@ -260,54 +260,16 @@ int main (int argc, char* argv[]) {
return -1;
}
boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <config_file.cfg>\nAllowed options");
desc.add_options()
("host,h", value<std::string>(&host), "host")
("port,p", value<int>(&port), "port")
;
try
{
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
}
catch (std::runtime_error& e)
{
std::cout << desc << "\n";
exit(1);
}
catch (...)
{
std::cout << desc << "\n";
exit(1);
}
if (argc < 5) {
return 1;
}
// QStringList channels;
// for (int i = 3; i < argc; ++i)
// {
// channels.append(argv[i]);
// }
//
// MyIrcSession session;
// session.setNick(argv[2]);
// session.setAutoJoinChannels(channels);
// session.connectToServer(argv[1], 6667);
Config config;
if (!config.load(argv[5])) {
std::cerr << "Can't open " << argv[1] << " configuration file.\n";
return 1;
}
Logging::initBackendLogging(&config);
std::string error;
StorageBackend *storageBackend = StorageBackend::createBackend(&config, error);
Config *cfg = Config::createFromArgs(argc, argv, error, host, port);
if (cfg == NULL) {
std::cerr << error;
return 1;
}
Logging::initBackendLogging(cfg);
StorageBackend *storageBackend = StorageBackend::createBackend(cfg, error);
if (storageBackend == NULL) {
if (!error.empty()) {
std::cerr << error << "\n";
@ -321,7 +283,7 @@ int main (int argc, char* argv[]) {
Swift::SimpleEventLoop eventLoop;
loop_ = &eventLoop;
np = new SMSNetworkPlugin(&config, &eventLoop, host, port);
np = new SMSNetworkPlugin(cfg, &eventLoop, host, port);
loop_->run();
return 0;

View file

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

282
backends/swiften/main.cpp Normal file
View file

@ -0,0 +1,282 @@
// Transport includes
#include "transport/config.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
// Swiften
#include "Swiften/Swiften.h"
#ifndef WIN32
// for signal handler
#include "unistd.h"
#include "signal.h"
#include "sys/wait.h"
#include "sys/signal.h"
#endif
// malloc_trim
#include "malloc.h"
// Boost
#include <boost/algorithm/string.hpp>
using namespace boost::filesystem;
using namespace boost::program_options;
using namespace Transport;
DEFINE_LOGGER(logger, "Swiften");
// eventloop
Swift::SimpleEventLoop *loop_;
// Plugins
class SwiftenPlugin;
SwiftenPlugin *np = NULL;
class SwiftenPlugin : public NetworkPlugin {
public:
Swift::BoostNetworkFactories *m_factories;
Swift::BoostIOServiceThread m_boostIOServiceThread;
boost::shared_ptr<Swift::Connection> m_conn;
SwiftenPlugin(Config *config, Swift::SimpleEventLoop *loop, const std::string &host, int port) : NetworkPlugin() {
this->config = config;
m_factories = new Swift::BoostNetworkFactories(loop);
m_conn = m_factories->getConnectionFactory()->createConnection();
m_conn->onDataRead.connect(boost::bind(&SwiftenPlugin::_handleDataRead, this, _1));
m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(host), port));
LOG4CXX_INFO(logger, "Starting the plugin.");
}
// NetworkPlugin uses this method to send the data to networkplugin server
void sendData(const std::string &string) {
m_conn->write(Swift::createSafeByteArray(string));
}
// This method has to call handleDataRead with all received data from network plugin server
void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
std::string d(data->begin(), data->end());
handleDataRead(d);
}
void handleSwiftDisconnected(const std::string &user, const boost::optional<Swift::ClientError> &error) {
std::string message = "";
if (error) {
switch(error->getType()) {
case Swift::ClientError::UnknownError: message = ("Unknown Error"); break;
case Swift::ClientError::DomainNameResolveError: message = ("Unable to find server"); break;
case Swift::ClientError::ConnectionError: message = ("Error connecting to server"); break;
case Swift::ClientError::ConnectionReadError: message = ("Error while receiving server data"); break;
case Swift::ClientError::ConnectionWriteError: message = ("Error while sending data to the server"); break;
case Swift::ClientError::XMLError: message = ("Error parsing server data"); break;
case Swift::ClientError::AuthenticationFailedError: message = ("Login/password invalid"); break;
case Swift::ClientError::CompressionFailedError: message = ("Error while compressing stream"); break;
case Swift::ClientError::ServerVerificationFailedError: message = ("Server verification failed"); break;
case Swift::ClientError::NoSupportedAuthMechanismsError: message = ("Authentication mechanisms not supported"); break;
case Swift::ClientError::UnexpectedElementError: message = ("Unexpected response"); break;
case Swift::ClientError::ResourceBindError: message = ("Error binding resource"); break;
case Swift::ClientError::SessionStartError: message = ("Error starting session"); break;
case Swift::ClientError::StreamError: message = ("Stream error"); break;
case Swift::ClientError::TLSError: message = ("Encryption error"); break;
case Swift::ClientError::ClientCertificateLoadError: message = ("Error loading certificate (Invalid password?)"); break;
case Swift::ClientError::ClientCertificateError: message = ("Certificate not authorized"); break;
case Swift::ClientError::UnknownCertificateError: message = ("Unknown certificate"); break;
case Swift::ClientError::CertificateExpiredError: message = ("Certificate has expired"); break;
case Swift::ClientError::CertificateNotYetValidError: message = ("Certificate is not yet valid"); break;
case Swift::ClientError::CertificateSelfSignedError: message = ("Certificate is self-signed"); break;
case Swift::ClientError::CertificateRejectedError: message = ("Certificate has been rejected"); break;
case Swift::ClientError::CertificateUntrustedError: message = ("Certificate is not trusted"); break;
case Swift::ClientError::InvalidCertificatePurposeError: message = ("Certificate cannot be used for encrypting your connection"); break;
case Swift::ClientError::CertificatePathLengthExceededError: message = ("Certificate path length constraint exceeded"); break;
case Swift::ClientError::InvalidCertificateSignatureError: message = ("Invalid certificate signature"); break;
case Swift::ClientError::InvalidCAError: message = ("Invalid Certificate Authority"); break;
case Swift::ClientError::InvalidServerIdentityError: message = ("Certificate does not match the host identity"); break;
}
}
LOG4CXX_INFO(logger, user << ": Disconnected " << message);
handleDisconnected(user, 3, message);
boost::shared_ptr<Swift::Client> client = m_users[user];
if (client) {
client->onConnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftConnected, this, user));
client->onDisconnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftDisconnected, this, user, _1));
client->onMessageReceived.disconnect(boost::bind(&SwiftenPlugin::handleSwiftMessageReceived, this, user, _1));
m_users.erase(user);
}
#ifndef WIN32
// force returning of memory chunks allocated by libxml2 to kernel
malloc_trim(0);
#endif
}
void handleSwiftConnected(const std::string &user) {
LOG4CXX_INFO(logger, user << ": Connected to XMPP server.");
handleConnected(user);
m_users[user]->requestRoster();
Swift::Presence::ref response = Swift::Presence::create();
response->setFrom(m_users[user]->getJID());
m_users[user]->sendPresence(response);
}
void handleSwiftRosterReceived(const std::string &user) {
Swift::PresenceOracle *oracle = m_users[user]->getPresenceOracle();
BOOST_FOREACH(const Swift::XMPPRosterItem &item, m_users[user]->getRoster()->getItems()) {
Swift::Presence::ref lastPresence = oracle->getLastPresence(item.getJID());
pbnetwork::StatusType status = lastPresence ? ((pbnetwork::StatusType) lastPresence->getShow()) : pbnetwork::STATUS_NONE;
handleBuddyChanged(user, item.getJID().toBare().toString(),
item.getName(), item.getGroups(), status);
}
}
void handleSwiftPresenceChanged(const std::string &user, Swift::Presence::ref presence) {
LOG4CXX_INFO(logger, user << ": " << presence->getFrom().toBare().toString() << " presence changed");
std::string message = presence->getStatus();
std::string photo = "";
boost::shared_ptr<Swift::VCardUpdate> update = presence->getPayload<Swift::VCardUpdate>();
if (update) {
photo = update->getPhotoHash();
}
boost::optional<Swift::XMPPRosterItem> item = m_users[user]->getRoster()->getItem(presence->getFrom());
if (item) {
handleBuddyChanged(user, presence->getFrom().toBare().toString(), item->getName(), item->getGroups(), (pbnetwork::StatusType) presence->getShow(), message, photo);
}
else {
std::vector<std::string> groups;
handleBuddyChanged(user, presence->getFrom().toBare().toString(), presence->getFrom().toBare(), groups, (pbnetwork::StatusType) presence->getShow(), message, photo);
}
}
void handleSwiftMessageReceived(const std::string &user, Swift::Message::ref message) {
std::string body = message->getBody();
boost::shared_ptr<Swift::Client> client = m_users[user];
if (client) {
handleMessage(user, message->getFrom().toBare().toString(), body, "", "");
}
}
void handleSwiftVCardReceived(const std::string &user, unsigned int id, Swift::VCard::ref vcard, Swift::ErrorPayload::ref error) {
if (error || !vcard) {
LOG4CXX_INFO(logger, user << ": error fetching VCard with id=" << id);
handleVCard(user, id, "", "", "", "");
return;
}
LOG4CXX_INFO(logger, user << ": VCard fetched - id=" << id);
std::string photo((const char *)&vcard->getPhoto()[0], vcard->getPhoto().size());
handleVCard(user, id, vcard->getFullName(), vcard->getFullName(), vcard->getNickname(), photo);
}
void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
LOG4CXX_INFO(logger, user << ": connecting as " << legacyName);
boost::shared_ptr<Swift::Client> client = boost::make_shared<Swift::Client>(Swift::JID(legacyName), password, m_factories);
m_users[user] = client;
client->setAlwaysTrustCertificates();
client->onConnected.connect(boost::bind(&SwiftenPlugin::handleSwiftConnected, this, user));
client->onDisconnected.connect(boost::bind(&SwiftenPlugin::handleSwiftDisconnected, this, user, _1));
client->onMessageReceived.connect(boost::bind(&SwiftenPlugin::handleSwiftMessageReceived, this, user, _1));
client->getRoster()->onInitialRosterPopulated.connect(boost::bind(&SwiftenPlugin::handleSwiftRosterReceived, this, user));
client->getPresenceOracle()->onPresenceChange.connect(boost::bind(&SwiftenPlugin::handleSwiftPresenceChanged, this, user, _1));
Swift::ClientOptions opt;
opt.allowPLAINWithoutTLS = true;
client->connect(opt);
}
void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
boost::shared_ptr<Swift::Client> client = m_users[user];
if (client) {
client->onConnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftConnected, this, user));
// client->onDisconnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftDisconnected, this, user, _1));
client->onMessageReceived.disconnect(boost::bind(&SwiftenPlugin::handleSwiftMessageReceived, this, user, _1));
client->getRoster()->onInitialRosterPopulated.disconnect(boost::bind(&SwiftenPlugin::handleSwiftRosterReceived, this, user));
client->getPresenceOracle()->onPresenceChange.disconnect(boost::bind(&SwiftenPlugin::handleSwiftPresenceChanged, this, user, _1));
client->disconnect();
}
}
void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &msg, const std::string &xhtml = "") {
LOG4CXX_INFO(logger, "Sending message from " << user << " to " << legacyName << ".");
boost::shared_ptr<Swift::Client> client = m_users[user];
if (client) {
boost::shared_ptr<Swift::Message> message(new Swift::Message());
message->setTo(Swift::JID(legacyName));
message->setFrom(client->getJID());
message->setBody(msg);
client->sendMessage(message);
}
}
void handleVCardRequest(const std::string &user, const std::string &legacyName, unsigned int id) {
boost::shared_ptr<Swift::Client> client = m_users[user];
if (client) {
LOG4CXX_INFO(logger, user << ": fetching VCard of " << legacyName << " id=" << id);
Swift::GetVCardRequest::ref request = Swift::GetVCardRequest::create(Swift::JID(legacyName), client->getIQRouter());
request->onResponse.connect(boost::bind(&SwiftenPlugin::handleSwiftVCardReceived, this, user, id, _1, _2));
request->send();
}
}
void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups) {
LOG4CXX_INFO(logger, user << ": Added/Updated buddy " << buddyName << ".");
// handleBuddyChanged(user, buddyName, alias, groups, pbnetwork::STATUS_ONLINE);
}
void handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups) {
}
private:
Config *config;
std::map<std::string, boost::shared_ptr<Swift::Client> > m_users;
};
#ifndef WIN32
static void spectrum_sigchld_handler(int sig)
{
int status;
pid_t pid;
do {
pid = waitpid(-1, &status, WNOHANG);
} while (pid != 0 && pid != (pid_t)-1);
if ((pid == (pid_t) - 1) && (errno != ECHILD)) {
char errmsg[BUFSIZ];
snprintf(errmsg, BUFSIZ, "Warning: waitpid() returned %d", pid);
perror(errmsg);
}
}
#endif
int main (int argc, char* argv[]) {
std::string host;
int port;
#ifndef WIN32
if (signal(SIGCHLD, spectrum_sigchld_handler) == SIG_ERR) {
std::cout << "SIGCHLD handler can't be set\n";
return -1;
}
#endif
std::string error;
Config *cfg = Config::createFromArgs(argc, argv, error, host, port);
if (cfg == NULL) {
std::cerr << error;
return 1;
}
Logging::initBackendLogging(cfg);
Swift::SimpleEventLoop eventLoop;
loop_ = &eventLoop;
np = new SwiftenPlugin(cfg, &eventLoop, host, port);
loop_->run();
return 0;
}

View file

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

View file

@ -1,3 +1,5 @@
#include "plugin.h"
// Transport includes
#include "transport/config.h"
#include "transport/networkplugin.h"
@ -6,82 +8,20 @@
// Swiften
#include "Swiften/Swiften.h"
#ifndef _WIN32
// for signal handler
#include "unistd.h"
#include "signal.h"
#include "sys/wait.h"
#include "sys/signal.h"
#endif
// Boost
#include <boost/algorithm/string.hpp>
using namespace boost::filesystem;
using namespace boost::program_options;
using namespace Transport;
DEFINE_LOGGER(logger, "Backend Template");
// eventloop
Swift::SimpleEventLoop *loop_;
// Plugin
class TemplatePlugin;
TemplatePlugin * np = NULL;
class TemplatePlugin : public NetworkPlugin {
public:
Swift::BoostNetworkFactories *m_factories;
Swift::BoostIOServiceThread m_boostIOServiceThread;
boost::shared_ptr<Swift::Connection> m_conn;
TemplatePlugin(Config *config, Swift::SimpleEventLoop *loop, const std::string &host, int port) : NetworkPlugin() {
this->config = config;
m_factories = new Swift::BoostNetworkFactories(loop);
m_conn = m_factories->getConnectionFactory()->createConnection();
m_conn->onDataRead.connect(boost::bind(&TemplatePlugin::_handleDataRead, this, _1));
m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(host), port));
LOG4CXX_INFO(logger, "Starting the plugin.");
}
// NetworkPlugin uses this method to send the data to networkplugin server
void sendData(const std::string &string) {
m_conn->write(Swift::createSafeByteArray(string));
}
// This method has to call handleDataRead with all received data from network plugin server
void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
std::string d(data->begin(), data->end());
handleDataRead(d);
}
void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
handleConnected(user);
LOG4CXX_INFO(logger, user << ": Added buddy - Echo.");
handleBuddyChanged(user, "echo", "Echo", std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
}
void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
}
void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml = "") {
LOG4CXX_INFO(logger, "Sending message from " << user << " to " << legacyName << ".");
if (legacyName == "echo") {
handleMessage(user, legacyName, message);
}
}
void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups) {
LOG4CXX_INFO(logger, user << ": Added buddy " << buddyName << ".");
handleBuddyChanged(user, buddyName, alias, groups, pbnetwork::STATUS_ONLINE);
}
void handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups) {
}
private:
Config *config;
};
#ifndef _WIN32
static void spectrum_sigchld_handler(int sig)
{
@ -98,56 +38,31 @@ static void spectrum_sigchld_handler(int sig)
perror(errmsg);
}
}
#endif
int main (int argc, char* argv[]) {
std::string host;
int port;
#ifndef _WIN32
if (signal(SIGCHLD, spectrum_sigchld_handler) == SIG_ERR) {
std::cout << "SIGCHLD handler can't be set\n";
return -1;
}
#endif
boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <config_file.cfg>\nAllowed options");
desc.add_options()
("host,h", value<std::string>(&host), "host")
("port,p", value<int>(&port), "port")
;
try
{
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
}
catch (std::runtime_error& e)
{
std::cout << desc << "\n";
exit(1);
}
catch (...)
{
std::cout << desc << "\n";
exit(1);
}
if (argc < 5) {
std::string error;
Config *cfg = Config::createFromArgs(argc, argv, error, host, port);
if (cfg == NULL) {
std::cerr << error;
return 1;
}
Config config;
if (!config.load(argv[5])) {
std::cerr << "Can't open " << argv[1] << " configuration file.\n";
return 1;
}
Logging::initBackendLogging(&config);
Logging::initBackendLogging(cfg);
Swift::SimpleEventLoop eventLoop;
loop_ = &eventLoop;
np = new TemplatePlugin(&config, &eventLoop, host, port);
loop_->run();
Plugin p(cfg, &eventLoop, host, port);
eventLoop.run();
return 0;
}

View file

@ -0,0 +1,62 @@
#include "plugin.h"
// Transport includes
#include "transport/config.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
// Swiften
#include "Swiften/Swiften.h"
// Boost
#include <boost/algorithm/string.hpp>
using namespace boost::filesystem;
using namespace boost::program_options;
using namespace Transport;
DEFINE_LOGGER(logger, "Backend Template");
Plugin::Plugin(Config *config, Swift::SimpleEventLoop *loop, const std::string &host, int port) : NetworkPlugin() {
this->config = config;
m_factories = new Swift::BoostNetworkFactories(loop);
m_conn = m_factories->getConnectionFactory()->createConnection();
m_conn->onDataRead.connect(boost::bind(&Plugin::_handleDataRead, this, _1));
m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(host), port));
LOG4CXX_INFO(logger, "Starting the plugin.");
}
// NetworkPlugin uses this method to send the data to networkplugin server
void Plugin::sendData(const std::string &string) {
m_conn->write(Swift::createSafeByteArray(string));
}
// This method has to call handleDataRead with all received data from network plugin server
void Plugin::_handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
std::string d(data->begin(), data->end());
handleDataRead(d);
}
void Plugin::handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
handleConnected(user);
LOG4CXX_INFO(logger, user << ": Added buddy - Echo.");
handleBuddyChanged(user, "echo", "Echo", std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
}
void Plugin::handleLogoutRequest(const std::string &user, const std::string &legacyName) {
}
void Plugin::handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml) {
LOG4CXX_INFO(logger, "Sending message from " << user << " to " << legacyName << ".");
if (legacyName == "echo") {
handleMessage(user, legacyName, message);
}
}
void Plugin::handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups) {
LOG4CXX_INFO(logger, user << ": Added buddy " << buddyName << ".");
handleBuddyChanged(user, buddyName, alias, groups, pbnetwork::STATUS_ONLINE);
}
void Plugin::handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups) {
}

View file

@ -0,0 +1,34 @@
#pragma once
#include "Swiften/Swiften.h"
#include "transport/config.h"
#include "transport/networkplugin.h"
class Plugin : public Transport::NetworkPlugin {
public:
Plugin(Transport::Config *config, Swift::SimpleEventLoop *loop, const std::string &host, int port);
// NetworkPlugin uses this method to send the data to networkplugin server
void sendData(const std::string &string);
void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password);
void handleLogoutRequest(const std::string &user, const std::string &legacyName);
void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml = "");
void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups);
void handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups);
private:
// This method has to call handleDataRead with all received data from network plugin server
void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data);
private:
Swift::BoostNetworkFactories *m_factories;
Swift::BoostIOServiceThread m_boostIOServiceThread;
boost::shared_ptr<Swift::Connection> m_conn;
Transport::Config *config;
};

View file

@ -0,0 +1,8 @@
include_directories (${libtransport_SOURCE_DIR}/backends/twitter/libtwitcurl)
FILE(GLOB SRC *.cpp libtwitcurl/*.cpp Requests/*.cpp)
add_executable(spectrum2_twitter_backend ${SRC})
#add_executable(parser TwitterResponseParser.cpp test.cpp)
target_link_libraries(spectrum2_twitter_backend curl transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
#target_link_libraries(parser curl transport pthread sqlite3 ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
INSTALL(TARGETS spectrum2_twitter_backend RUNTIME DESTINATION bin)

View file

@ -0,0 +1,72 @@
#include "HTTPRequest.h"
DEFINE_LOGGER(logger, "HTTPRequest")
bool HTTPRequest::init()
{
curlhandle = curl_easy_init();
if(curlhandle) {
curlhandle = curl_easy_init();
curl_easy_setopt(curlhandle, CURLOPT_PROXY, NULL);
curl_easy_setopt(curlhandle, CURLOPT_PROXYUSERPWD, NULL);
curl_easy_setopt(curlhandle, CURLOPT_PROXYAUTH, (long)CURLAUTH_ANY);
return true;
}
LOG4CXX_ERROR(logger, "Couldn't Initialize curl!")
return false;
}
void HTTPRequest::setProxy(std::string IP, std::string port, std::string username, std::string password)
{
if(curlhandle) {
std::string proxyIpPort = IP + ":" + port;
curl_easy_setopt(curlhandle, CURLOPT_PROXY, proxyIpPort.c_str());
if(username.length() && password.length()) {
std::string proxyUserPass = username + ":" + password;
curl_easy_setopt(curlhandle, CURLOPT_PROXYUSERPWD, proxyUserPass.c_str());
}
} else {
LOG4CXX_ERROR(logger, "Trying to set proxy while CURL isn't initialized")
}
}
int HTTPRequest::curlCallBack(char* data, size_t size, size_t nmemb, HTTPRequest* obj)
{
int writtenSize = 0;
if(obj && data) {
obj->callbackdata.append(data, size*nmemb);
writtenSize = (int)(size*nmemb);
}
return writtenSize;
}
bool HTTPRequest::GET(std::string url, std::string &data)
{
if(curlhandle) {
curl_easy_setopt(curlhandle, CURLOPT_CUSTOMREQUEST, NULL);
curl_easy_setopt(curlhandle, CURLOPT_ENCODING, "");
data = "";
callbackdata = "";
memset(curl_errorbuffer, 0, 1024);
curl_easy_setopt(curlhandle, CURLOPT_ERRORBUFFER, curl_errorbuffer);
curl_easy_setopt(curlhandle, CURLOPT_WRITEFUNCTION, curlCallBack);
curl_easy_setopt(curlhandle, CURLOPT_WRITEDATA, this);
/* Set http request and url */
curl_easy_setopt(curlhandle, CURLOPT_HTTPGET, 1);
curl_easy_setopt(curlhandle, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curlhandle, CURLOPT_URL, url.c_str());
/* Send http request and return status*/
if(CURLE_OK == curl_easy_perform(curlhandle)) {
data = callbackdata;
return true;
}
} else {
LOG4CXX_ERROR(logger, "CURL not initialized!")
strcpy(curl_errorbuffer, "CURL not initialized!");
}
return false;
}

View file

@ -0,0 +1,37 @@
#ifndef HTTPREQ_H
#define HTTPREQ_H
#include "libtwitcurl/curl/curl.h"
#include "transport/logging.h"
#include <iostream>
#include <sstream>
#include <string.h>
class HTTPRequest
{
CURL *curlhandle;
char curl_errorbuffer[1024];
std::string error;
std::string callbackdata;
static int curlCallBack(char* data, size_t size, size_t nmemb, HTTPRequest *obj);
public:
HTTPRequest() {
curlhandle = NULL;
}
~HTTPRequest() {
if(curlhandle) {
curl_easy_cleanup(curlhandle);
curlhandle = NULL;
}
}
bool init();
void setProxy(std::string, std::string, std::string, std::string);
bool GET(std::string, std::string &);
std::string getCurlError() {return std::string(curl_errorbuffer);}
};
#endif

View file

@ -0,0 +1,50 @@
#include "CreateFriendRequest.h"
#include "../HTTPRequest.h"
DEFINE_LOGGER(logger, "CreateFriendRequest")
void CreateFriendRequest::run()
{
LOG4CXX_INFO(logger, user << " - Sending follow request for " << frnd)
replyMsg = "";
success = twitObj->friendshipCreate(frnd, false);
if(success) {
twitObj->getLastWebResponse(replyMsg);
LOG4CXX_INFO(logger, user << replyMsg)
friendInfo = getUser(replyMsg);
if(friendInfo.getScreenName() == "") {LOG4CXX_INFO(logger, user << " - Was unable to fetch user info for " << frnd)}
HTTPRequest req;
std::string img;
req.init();
req.setProxy(twitObj->getProxyServerIp(), twitObj->getProxyServerPort(), twitObj->getProxyUserName(), twitObj->getProxyPassword());
profileImg = "";
if(req.GET(friendInfo.getProfileImgURL(), img)) profileImg = img;
else {
LOG4CXX_INFO(logger, user << " - Was unable to fetch profile image of user " << frnd);
}
}
}
void CreateFriendRequest::finalize()
{
Error error;
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - Curl error: " << curlerror)
callBack(user, friendInfo, profileImg, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) {
LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
}
else LOG4CXX_INFO(logger, user << ": Now following " << frnd)
callBack(user, friendInfo, profileImg, error);
}
}

View file

@ -0,0 +1,43 @@
#ifndef CREATE_FRIEND
#define CREATE_FRIEND
#include "transport/threadpool.h"
#include "../TwitterResponseParser.h"
#include "../libtwitcurl/twitcurl.h"
#include "transport/logging.h"
#include <string>
#include <boost/function.hpp>
#include <iostream>
#include <vector>
using namespace Transport;
class CreateFriendRequest : public Thread
{
twitCurl *twitObj;
std::string user;
std::string frnd;
std::string replyMsg;
boost::function< void (std::string&, User&, std::string &, Error&) > callBack;
User friendInfo;
std::string profileImg;
bool success;
public:
CreateFriendRequest(twitCurl *obj, const std::string &_user, const std::string & _frnd,
boost::function< void (std::string&, User&, std::string &, Error&) > cb) {
twitObj = obj->clone();
user = _user;
frnd = _frnd;
callBack = cb;
}
~CreateFriendRequest() {
delete twitObj;
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,33 @@
#include "DestroyFriendRequest.h"
DEFINE_LOGGER(logger, "DestroyFriendRequest")
void DestroyFriendRequest::run()
{
replyMsg = "";
success = twitObj->friendshipDestroy(frnd, false);
if(success) {
twitObj->getLastWebResponse(replyMsg);
LOG4CXX_INFO(logger, user << replyMsg)
friendInfo = getUser(replyMsg);
if(friendInfo.getScreenName() == "") LOG4CXX_INFO(logger, user << " - Was unable to fetch user info for " << frnd);
}
}
void DestroyFriendRequest::finalize()
{
Error error;
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " Curl error: " << curlerror)
callBack(user, friendInfo, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
callBack(user, friendInfo, error);
}
}

View file

@ -0,0 +1,42 @@
#ifndef DESTROY_FRIEND
#define DESTROY_FRIEND
#include "transport/threadpool.h"
#include "../TwitterResponseParser.h"
#include "../libtwitcurl/twitcurl.h"
#include "transport/logging.h"
#include <string>
#include <boost/function.hpp>
#include <iostream>
#include <vector>
using namespace Transport;
class DestroyFriendRequest : public Thread
{
twitCurl *twitObj;
std::string user;
std::string frnd;
std::string replyMsg;
boost::function< void (std::string&, User&, Error&) > callBack;
User friendInfo;
bool success;
public:
DestroyFriendRequest(twitCurl *obj, const std::string &_user, const std::string & _frnd,
boost::function< void (std::string&, User&, Error&) > cb) {
twitObj = obj->clone();
user = _user;
frnd = _frnd;
callBack = cb;
}
~DestroyFriendRequest() {
delete twitObj;
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,32 @@
#include "DirectMessageRequest.h"
DEFINE_LOGGER(logger, "DirectMessageRequest")
void DirectMessageRequest::run()
{
replyMsg = "";
if(username != "") success = twitObj->directMessageSend(username, data, false);
else success = twitObj->directMessageGet(data); /* data will contain sinceId */
if(success) {
twitObj->getLastWebResponse( replyMsg );
if(username == "" ) messages = getDirectMessages( replyMsg );
}
}
void DirectMessageRequest::finalize()
{
Error error;
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " Curl error: " << curlerror);
callBack(user, username, messages, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
else LOG4CXX_INFO(logger, user << " - " << replyMsg)
callBack(user, username, messages, error);
}
}

View file

@ -0,0 +1,43 @@
#ifndef DIRECT_MESSAGE
#define DIRECT_MESSAGE
#include "transport/threadpool.h"
#include "../TwitterResponseParser.h"
#include "../libtwitcurl/twitcurl.h"
#include "transport/logging.h"
#include <string>
#include <boost/function.hpp>
#include <iostream>
using namespace Transport;
class DirectMessageRequest : public Thread
{
twitCurl *twitObj;
std::string data;
std::string user;
std::string username;
std::string replyMsg;
boost::function< void (std::string&, std::string &, std::vector<DirectMessage>&, Error&) > callBack;
std::vector<DirectMessage> messages;
bool success;
public:
DirectMessageRequest(twitCurl *obj, const std::string &_user, const std::string & _username, const std::string &_data,
boost::function< void (std::string&, std::string &, std::vector<DirectMessage>&, Error&) > cb) {
twitObj = obj->clone();
data = _data;
user = _user;
username = _username;
callBack = cb;
}
~DirectMessageRequest() {
delete twitObj;
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,50 @@
#include "FetchFriends.h"
#include "../HTTPRequest.h"
DEFINE_LOGGER(logger, "FetchFriends")
void FetchFriends::run()
{
replyMsg = "";
success = twitObj->friendsIdsGet(twitObj->getTwitterUsername());
if(!success) return;
twitObj->getLastWebResponse( replyMsg );
std::vector<std::string> IDs = getIDs( replyMsg );
success = twitObj->userLookup(IDs, true);
if(!success) return;
twitObj->getLastWebResponse( replyMsg );
friends = getUsers( replyMsg );
HTTPRequest req;
req.init();
req.setProxy(twitObj->getProxyServerIp(), twitObj->getProxyServerPort(), twitObj->getProxyUserName(), twitObj->getProxyPassword());
for(int i=0 ; i<friends.size() ; i++) {
std::string img;
friendAvatars.push_back("");
if(req.GET(friends[i].getProfileImgURL(), img)) friendAvatars[i] = img;
else {
LOG4CXX_INFO(logger, "Warning: Couldn't fetch Profile Image for " << user << "'s friend " << friends[i].getScreenName())
}
}
}
void FetchFriends::finalize()
{
Error error;
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - " << curlerror)
callBack(user, friends, friendAvatars, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
callBack(user, friends, friendAvatars, error);
}
}

View file

@ -0,0 +1,41 @@
#ifndef FRIENDS_H
#define FRIENDS_H
#include "transport/threadpool.h"
#include "../libtwitcurl/twitcurl.h"
#include "../TwitterResponseParser.h"
#include "transport/logging.h"
#include <string>
#include <boost/signals.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
using namespace Transport;
class FetchFriends : public Thread
{
twitCurl *twitObj;
std::string user;
std::string replyMsg;
std::vector<User> friends;
std::vector<std::string> friendAvatars;
bool success;
boost::function< void (std::string, std::vector<User> &, std::vector<std::string> &, Error) > callBack;
public:
FetchFriends(twitCurl *obj, const std::string &_user,
boost::function< void (std::string, std::vector<User> &, std::vector<std::string> &, Error) > cb) {
twitObj = obj->clone();
user = _user;
callBack = cb;
}
~FetchFriends() {
delete twitObj;
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,21 @@
#include "HelpMessageRequest.h"
DEFINE_LOGGER(logger, "HelpMessageRequest")
void HelpMessageRequest::run()
{
helpMsg = helpMsg
+ "\n******************************HELP************************************\n"
+ "#status <your status> ==> Update your status\n"
+ "#timeline [username] ==> Retrieve <username>'s timeline; Default - own timeline\n"
+ "@<username> <message> ==> Send a directed message to the user <username>\n"
+ "#retweet <unique_tweet_id> ==> Retweet the tweet having id <unique_tweet_id> \n"
+ "#follow <username> ==> Follow user <username>\n"
+ "#unfollow <username> ==> Stop Following user <username>\n"
+ "#mode [012] ==> Switch mode to 0(single), 1(multiple) or 2(chatroom)\n"
+ "#help ==> Print this help message\n"
+ "************************************************************************\n";
}
void HelpMessageRequest::finalize()
{
callBack(user, helpMsg);
}

View file

@ -0,0 +1,30 @@
#ifndef HELPMESSAGE_H
#define HELPMESSAGE_H
#include "transport/threadpool.h"
#include "../libtwitcurl/twitcurl.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
#include <string>
#include <boost/function.hpp>
#include <iostream>
using namespace Transport;
class HelpMessageRequest : public Thread
{
std::string user;
std::string helpMsg;
boost::function<void (std::string &, std::string &)> callBack;
public:
HelpMessageRequest(const std::string &_user, boost::function<void (std::string &, std::string &)> cb) {
user = _user;
callBack = cb;
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,19 @@
#include "OAuthFlow.h"
DEFINE_LOGGER(logger, "OAuthFlow")
void OAuthFlow::run()
{
success = twitObj->oAuthRequestToken( authUrl );
}
void OAuthFlow::finalize()
{
if (!success) {
LOG4CXX_ERROR(logger, "Error creating twitter authorization url!");
np->handleMessage(user, "twitter.com", "Error creating twitter authorization url!");
np->handleLogoutRequest(user, username);
} else {
np->handleMessage(user, "twitter.com", std::string("Please visit the following link and authorize this application: ") + authUrl);
np->handleMessage(user, "twitter.com", std::string("Please reply with the PIN provided by twitter. Prefix the pin with '#pin'. Ex. '#pin 1234'"));
np->OAuthFlowComplete(user, twitObj);
}
}

View file

@ -0,0 +1,39 @@
#ifndef OAUTH_FLOW
#define OAUTH_FLOW
#include "transport/threadpool.h"
#include "../libtwitcurl/twitcurl.h"
#include "../TwitterPlugin.h"
#include "transport/logging.h"
#include <string>
#include <iostream>
//class TwitterPlugin;
using namespace Transport;
class OAuthFlow : public Thread
{
twitCurl *twitObj;
std::string username;
std::string user;
std::string authUrl;
TwitterPlugin *np;
bool success;
public:
OAuthFlow(TwitterPlugin *_np, twitCurl *obj, const std::string &_user, const std::string &_username) {
twitObj = obj->clone();
username = _username;
user = _user;
np = _np;
}
~OAuthFlow() {
delete twitObj;
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,70 @@
#include "PINExchangeProcess.h"
DEFINE_LOGGER(logger, "PINExchangeProcess")
void PINExchangeProcess::run()
{
LOG4CXX_INFO(logger, user << ": Sending PIN " << data)
LOG4CXX_INFO(logger, user << " " << twitObj->getProxyServerIp() << " " << twitObj->getProxyServerPort())
twitObj->getOAuth().setOAuthPin( data );
success = twitObj->oAuthAccessToken();
}
void PINExchangeProcess::finalize()
{
if(!success) {
LOG4CXX_ERROR(logger, user << ": Error while exchanging PIN for Access Token!")
np->handleMessage(user, "twitter.com", "Error while exchanging PIN for Access Token!");
np->handleLogoutRequest(user, "");
} else {
std::string replyMsg;
while(replyMsg.length() == 0) {
twitObj->getLastWebResponse(replyMsg);
}
Error error = getErrorMessage(replyMsg);
if(error.getMessage().length()) {
LOG4CXX_ERROR(logger, user << ": Error while exchanging PIN for Access Token! " << error.getMessage())
np->handleMessage(user, "twitter.com", error.getMessage());
np->handleLogoutRequest(user, "");
return;
}
std::string OAuthAccessTokenKey, OAuthAccessTokenSecret;
twitObj->getOAuth().getOAuthTokenKey( OAuthAccessTokenKey );
twitObj->getOAuth().getOAuthTokenSecret( OAuthAccessTokenSecret );
if(np->storeUserOAuthKeyAndSecret(user, OAuthAccessTokenKey, OAuthAccessTokenSecret) == false) {
np->handleLogoutRequest(user, "");
return;
}
np->pinExchangeComplete(user, OAuthAccessTokenKey, OAuthAccessTokenSecret);
np->handleMessage(user, "twitter.com", "PIN is OK. You are now authorized.");
LOG4CXX_INFO(logger, user << ": Sent PIN " << data << " and obtained Access Token");
}
}
/*void handlePINExchange(const std::string &user, std::string &data) {
sessions[user]->getOAuth().setOAuthPin( data );
if (sessions[user]->oAuthAccessToken() == false) {
LOG4CXX_ERROR(logger, user << ": Error while exchanging PIN for Access Token!")
handleLogoutRequest(user, "");
return;
}
std::string OAuthAccessTokenKey, OAuthAccessTokenSecret;
sessions[user]->getOAuth().getOAuthTokenKey( OAuthAccessTokenKey );
sessions[user]->getOAuth().getOAuthTokenSecret( OAuthAccessTokenSecret );
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
handleLogoutRequest(user, "");
return;
}
storagebackend->updateUserSetting((long)info.id, OAUTH_KEY, OAuthAccessTokenKey);
storagebackend->updateUserSetting((long)info.id, OAUTH_SECRET, OAuthAccessTokenSecret);
connectionState[user] = CONNECTED;
LOG4CXX_INFO(logger, user << ": Sent PIN " << data << " and obtained Access Token");
}*/

View file

@ -0,0 +1,39 @@
#ifndef PIN_EXCHANGE
#define PIN_EXCHANGE
#include "transport/threadpool.h"
#include "../libtwitcurl/twitcurl.h"
#include "../TwitterPlugin.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
#include <string>
#include <iostream>
//class TwitterPlugin;
using namespace Transport;
class PINExchangeProcess : public Thread
{
twitCurl *twitObj;
std::string data;
std::string user;
TwitterPlugin *np;
bool success;
public:
PINExchangeProcess(TwitterPlugin *_np, twitCurl *obj, const std::string &_user, const std::string &_data) {
twitObj = obj->clone();
data = _data;
user = _user;
np = _np;
}
~PINExchangeProcess() {
delete twitObj;
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,26 @@
#include "ProfileImageRequest.h"
#include "../HTTPRequest.h"
DEFINE_LOGGER(logger, "ProfileImageRequest")
void ProfileImageRequest::run()
{
HTTPRequest req;
req.init();
req.setProxy(ip, port, puser, ppasswd);
success = req.GET(url, callbackdata);
if(!success) error.assign(req.getCurlError());
}
void ProfileImageRequest::finalize()
{
Error errResponse;
if(!success) {
LOG4CXX_ERROR(logger, user << " - " << error)
img = "";
errResponse.setMessage(error);
callBack(user, buddy, img, reqID, errResponse);
} else {
LOG4CXX_INFO(logger, user << " - " << callbackdata);
img = callbackdata;
callBack(user, buddy, img, reqID, errResponse);
}
}

View file

@ -0,0 +1,62 @@
#ifndef PROFILEIMAGE_H
#define PROFILEIMAGE_H
#include "transport/threadpool.h"
#include "../TwitterResponseParser.h"
#include "transport/logging.h"
#include "transport/config.h"
#include <string>
#include <boost/signals.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <sstream>
using namespace Transport;
using namespace boost::program_options;
class ProfileImageRequest : public Thread
{
std::string user;
std::string buddy;
std::string url;
std::string img;
unsigned int reqID;
boost::function< void (std::string&, std::string&, std::string&, int, Error&) > callBack;
std::string ip, port, puser, ppasswd;
bool success;
std::string error;
std::string callbackdata;
public:
ProfileImageRequest(Config *config, const std::string &_user, const std::string &_buddy, const std::string &_url, unsigned int _reqID,
boost::function< void (std::string&, std::string&, std::string&, int, Error&) > cb) {
if(CONFIG_HAS_KEY(config,"proxy.server")) {
ip = CONFIG_STRING(config,"proxy.server");
std::ostringstream out;
out << CONFIG_INT(config,"proxy.port");
port = out.str();
puser = CONFIG_STRING(config,"proxy.user");
ppasswd = CONFIG_STRING(config,"proxy.password");
}
user = _user;
buddy = _buddy;
url = _url;
reqID = _reqID;
callBack = cb;
}
~ProfileImageRequest() {
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,25 @@
#include "RetweetRequest.h"
DEFINE_LOGGER(logger, "RetweetRequest")
void RetweetRequest::run()
{
LOG4CXX_INFO(logger, user << " Retweeting " << data)
success = twitObj->retweetById( data );
}
void RetweetRequest::finalize()
{
Error error;
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " Curl error: " << curlerror)
callBack(user, error);
} else {
twitObj->getLastWebResponse(replyMsg);
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
else LOG4CXX_INFO(logger, user << " " << replyMsg);
callBack(user, error);
}
}

View file

@ -0,0 +1,40 @@
#ifndef RETWEET_H
#define RETWEET_H
#include "transport/threadpool.h"
#include "../TwitterResponseParser.h"
#include "../libtwitcurl/twitcurl.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
#include <boost/function.hpp>
#include <string>
#include <iostream>
using namespace Transport;
class RetweetRequest : public Thread
{
twitCurl *twitObj;
std::string data;
std::string user;
std::string replyMsg;
bool success;
boost::function < void (std::string&, Error&) > callBack;
public:
RetweetRequest(twitCurl *obj, const std::string &_user, const std::string &_data,
boost::function < void (std::string &, Error&) > _cb) {
twitObj = obj->clone();
data = _data;
user = _user;
callBack = _cb;
}
~RetweetRequest() {
delete twitObj;
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,30 @@
#include "StatusUpdateRequest.h"
#include "../TwitterResponseParser.h"
DEFINE_LOGGER(logger, "StatusUpdateRequest")
void StatusUpdateRequest::run()
{
replyMsg = "";
success = twitObj->statusUpdate(data);
if(success) {
twitObj->getLastWebResponse( replyMsg );
LOG4CXX_INFO(logger, user << "StatusUpdateRequest response " << replyMsg );
}
}
void StatusUpdateRequest::finalize()
{
Error error;
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - Curl error: " << curlerror);
callBack(user, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
else LOG4CXX_INFO(logger, "Updated status for " << user << ": " << data);
callBack(user, error);
}
}

View file

@ -0,0 +1,40 @@
#ifndef STATUS_UPDATE
#define STATUS_UPDATE
#include "transport/threadpool.h"
#include "../libtwitcurl/twitcurl.h"
#include "../TwitterResponseParser.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
#include <boost/function.hpp>
#include <string>
#include <iostream>
using namespace Transport;
class StatusUpdateRequest : public Thread
{
twitCurl *twitObj;
std::string data;
std::string user;
std::string replyMsg;
boost::function<void (std::string& user, Error& errMsg)> callBack;
bool success;
public:
StatusUpdateRequest(twitCurl *obj, const std::string &_user, const std::string &_data,
boost::function<void (std::string& user, Error& errMsg)> cb) {
twitObj = obj->clone();
data = _data;
user = _user;
callBack = cb;
}
~StatusUpdateRequest() {
delete twitObj;
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,32 @@
#include "TimelineRequest.h"
DEFINE_LOGGER(logger, "TimelineRequest")
void TimelineRequest::run()
{
LOG4CXX_INFO(logger, "Sending timeline request for user " << userRequested)
if(userRequested != "") success = twitObj->timelineUserGet(false, false, 20, userRequested, false);
else success = twitObj->timelineHomeGet(since_id);
if(!success) return;
replyMsg = "";
twitObj->getLastWebResponse( replyMsg );
//LOG4CXX_INFO(logger, user << " - " << replyMsg.length() << " " << replyMsg << "\n" );
tweets = getTimeline(replyMsg);
}
void TimelineRequest::finalize()
{
Error error;
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - Curl error: " << curlerror)
callBack(user, userRequested, tweets, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
callBack(user, userRequested, tweets, error);
}
}

View file

@ -0,0 +1,43 @@
#ifndef TIMELINE_H
#define TIMELINE_H
#include "transport/threadpool.h"
#include "../libtwitcurl/twitcurl.h"
#include "../TwitterResponseParser.h"
#include "transport/logging.h"
#include <string>
#include <iostream>
#include <boost/function.hpp>
using namespace Transport;
class TimelineRequest : public Thread
{
twitCurl *twitObj;
std::string user;
std::string userRequested;
std::string replyMsg;
std::string since_id;
bool success;
boost::function< void (std::string&, std::string&, std::vector<Status> &, Error&) > callBack;
std::vector<Status> tweets;
public:
TimelineRequest(twitCurl *obj, const std::string &_user, const std::string &_user2, const std::string &_since_id,
boost::function< void (std::string&, std::string&, std::vector<Status> &, Error&) > cb) {
twitObj = obj->clone();
user = _user;
userRequested = _user2;
since_id = _since_id;
callBack = cb;
}
~TimelineRequest() {
//std::cerr << "*****Timeline request: DESTROYING twitObj****" << std::endl;
delete twitObj;
}
void run();
void finalize();
};
#endif

View file

@ -0,0 +1,784 @@
#include "TwitterPlugin.h"
#include "Requests/StatusUpdateRequest.h"
#include "Requests/DirectMessageRequest.h"
#include "Requests/TimelineRequest.h"
#include "Requests/FetchFriends.h"
#include "Requests/HelpMessageRequest.h"
#include "Requests/PINExchangeProcess.h"
#include "Requests/OAuthFlow.h"
#include "Requests/CreateFriendRequest.h"
#include "Requests/DestroyFriendRequest.h"
#include "Requests/RetweetRequest.h"
#include "Requests/ProfileImageRequest.h"
#include "Swiften/StringCodecs/Hexify.h"
DEFINE_LOGGER(logger, "Twitter Backend");
TwitterPlugin *np = NULL;
Swift::SimpleEventLoop *loop_; // Event Loop
const std::string OLD_APP_KEY = "PCWAdQpyyR12ezp2fVwEhw";
const std::string OLD_APP_SECRET = "EveLmCXJIg2R7BTCpm6OWV8YyX49nI0pxnYXh7JMvDg";
#define abs(x) ((x)<0?-(x):(x))
#define SHA(x) (Swift::Hexify::hexify(Swift::SHA1::getHash(Swift::createByteArray((x)))))
//Compares two +ve intergers 'a' and 'b' represented as strings
static int cmp(std::string a, std::string b)
{
int diff = abs((int)a.size() - (int)b.size());
if(a.size() < b.size()) a = std::string(diff,'0') + a;
else b = std::string(diff,'0') + b;
if(a == b) return 0;
if(a < b) return -1;
return 1;
}
TwitterPlugin::TwitterPlugin(Config *config, Swift::SimpleEventLoop *loop, StorageBackend *storagebackend, const std::string &host, int port) : NetworkPlugin()
{
this->config = config;
this->storagebackend = storagebackend;
if (CONFIG_HAS_KEY(config, "twitter.consumer_key") == false) {
consumerKey = "5mFePMiJi0KpeURONkelg";
}
else {
consumerKey = CONFIG_STRING(config, "twitter.consumer_key");
}
if (CONFIG_HAS_KEY(config, "twitter.consumer_secret") == false) {
consumerSecret = "YFZCDJwRhbkccXEnaYr1waCQejTJcOY8F7l5Wim3FA";
}
else {
consumerSecret = CONFIG_STRING(config, "twitter.consumer_secret");
}
if (consumerSecret.empty() || consumerKey.empty()) {
LOG4CXX_ERROR(logger, "Consumer key and Consumer secret can't be empty.");
exit(1);
}
adminLegacyName = "twitter.com";
adminChatRoom = "#twitter";
adminNickName = "twitter";
adminAlias = "twitter";
OAUTH_KEY = "twitter_oauth_token";
OAUTH_SECRET = "twitter_oauth_secret";
MODE = "mode";
m_factories = new Swift::BoostNetworkFactories(loop);
m_conn = m_factories->getConnectionFactory()->createConnection();
m_conn->onDataRead.connect(boost::bind(&TwitterPlugin::_handleDataRead, this, _1));
m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(host), port));
tp = new ThreadPool(loop_, 10);
tweet_timer = m_factories->getTimerFactory()->createTimer(60000);
message_timer = m_factories->getTimerFactory()->createTimer(60000);
tweet_timer->onTick.connect(boost::bind(&TwitterPlugin::pollForTweets, this));
message_timer->onTick.connect(boost::bind(&TwitterPlugin::pollForDirectMessages, this));
tweet_timer->start();
message_timer->start();
LOG4CXX_INFO(logger, "Starting the plugin.");
}
TwitterPlugin::~TwitterPlugin()
{
delete storagebackend;
std::set<std::string>::iterator it;
for(it = onlineUsers.begin() ; it != onlineUsers.end() ; it++) delete userdb[*it].sessions;
delete tp;
}
// Send data to NetworkPlugin server
void TwitterPlugin::sendData(const std::string &string)
{
m_conn->write(Swift::createSafeByteArray(string));
}
// Receive date from the NetworkPlugin server and invoke the appropirate payload handler (implement in the NetworkPlugin class)
void TwitterPlugin::_handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data)
{
std::string d(data->begin(), data->end());
handleDataRead(d);
}
// User trying to login into his twitter account
void TwitterPlugin::handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password)
{
if(userdb.count(user) && (userdb[user].connectionState == NEW ||
userdb[user].connectionState == CONNECTED ||
userdb[user].connectionState == WAITING_FOR_PIN)) {
LOG4CXX_INFO(logger, std::string("A session corresponding to ") + user + std::string(" is already active"))
return;
}
LOG4CXX_INFO(logger, std::string("Received login request for ") + user)
initUserSession(user, legacyName, password);
handleConnected(user);
LOG4CXX_INFO(logger, "SPECTRUM 1 USER? - " << (userdb[user].spectrum1User? "true" : "false"))
LOG4CXX_INFO(logger, user << ": Adding Buddy " << adminLegacyName << " " << adminAlias)
handleBuddyChanged(user, adminLegacyName, adminAlias, std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
userdb[user].nickName = "";
LOG4CXX_INFO(logger, "Querying database for usersettings of " << user)
std::string key, secret;
getUserOAuthKeyAndSecret(user, key, secret);
if(key == "" || secret == "") {
LOG4CXX_INFO(logger, "Intiating OAuth Flow for user " << user)
setTwitterMode(user, 0);
tp->runAsThread(new OAuthFlow(np, userdb[user].sessions, user, userdb[user].sessions->getTwitterUsername()));
} else {
LOG4CXX_INFO(logger, user << " is already registerd. Using the stored oauth key and secret")
LOG4CXX_INFO(logger, key << " " << secret)
pinExchangeComplete(user, key, secret);
}
}
// User logging out
void TwitterPlugin::handleLogoutRequest(const std::string &user, const std::string &legacyName)
{
if(onlineUsers.count(user)) {
delete userdb[user].sessions;
userdb[user].sessions = NULL;
userdb[user].connectionState = DISCONNECTED;
onlineUsers.erase(user);
}
}
// User joining a Chatroom
void TwitterPlugin::handleJoinRoomRequest(const std::string &user, const std::string &room, const std::string &nickname, const std::string &password)
{
if(room == adminChatRoom) {
LOG4CXX_INFO(logger, "Received Join Twitter room request for " << user)
setTwitterMode(user, 2);
handleParticipantChanged(user, adminNickName, room, 0, pbnetwork::STATUS_ONLINE);
userdb[user].nickName = nickname;
handleMessage(user, adminChatRoom, "Connected to Twitter room! Populating your followers list", adminNickName);
tp->runAsThread(new FetchFriends(userdb[user].sessions, user,
boost::bind(&TwitterPlugin::populateRoster, this, _1, _2, _3, _4)));
} else {
setTwitterMode(user, 0);
LOG4CXX_ERROR(logger, "Couldn't connect to chatroom - " << room <<"! Try twitter-chatroom as the chatroom to access Twitter account")
handleMessage(user, adminLegacyName, "Couldn't connect to chatroom! Try twitter-chatroom as the chatroom to access Twitter account");
}
}
// User leaving a Chatroom
void TwitterPlugin::handleLeaveRoomRequest(const std::string &user, const std::string &room)
{
if(room == adminChatRoom && onlineUsers.count(user)) {
LOG4CXX_INFO(logger, "Leaving chatroom! Switching back to default mode 0")
setTwitterMode(user, 0);
handleBuddyChanged(user, adminLegacyName, adminAlias, std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
}
}
// Messages to be sent to Twitter
void TwitterPlugin::handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml)
{
LOG4CXX_INFO(logger, "Received " << user << " --> " << legacyName << " - " << message)
if(legacyName == adminLegacyName || legacyName == adminChatRoom) {
std::string cmd = "", data = "";
/** Parsing the message - Assuming message format to be <cmd>[ ]*<data>**/
int i;
for(i=0 ; i<message.size() && message[i] != ' '; i++) cmd += message[i];
while(i<message.size() && message[i] == ' ') i++;
data = message.substr(i);
/***********************************************************************/
if(cmd == "#pin")
tp->runAsThread(new PINExchangeProcess(np, userdb[user].sessions, user, data));
else if(cmd == "#help")
tp->runAsThread(new HelpMessageRequest(user, boost::bind(&TwitterPlugin::helpMessageResponse, this, _1, _2)));
else if(cmd[0] == '@') {
std::string username = cmd.substr(1);
tp->runAsThread(new DirectMessageRequest(userdb[user].sessions, user, username, data,
boost::bind(&TwitterPlugin::directMessageResponse, this, _1, _2, _3, _4)));
}
else if(cmd == "#status")
tp->runAsThread(new StatusUpdateRequest(userdb[user].sessions, user, data,
boost::bind(&TwitterPlugin::statusUpdateResponse, this, _1, _2)));
else if(cmd == "#timeline")
tp->runAsThread(new TimelineRequest(userdb[user].sessions, user, data, "",
boost::bind(&TwitterPlugin::displayTweets, this, _1, _2, _3, _4)));
else if(cmd == "#friends")
tp->runAsThread(new FetchFriends(userdb[user].sessions, user,
boost::bind(&TwitterPlugin::displayFriendlist, this, _1, _2, _3, _4)));
else if(cmd == "#follow")
tp->runAsThread(new CreateFriendRequest(userdb[user].sessions, user, data.substr(0,data.find('@')),
boost::bind(&TwitterPlugin::createFriendResponse, this, _1, _2, _3, _4)));
else if(cmd == "#unfollow")
tp->runAsThread(new DestroyFriendRequest(userdb[user].sessions, user, data.substr(0,data.find('@')),
boost::bind(&TwitterPlugin::deleteFriendResponse, this, _1, _2, _3)));
else if(cmd == "#retweet")
tp->runAsThread(new RetweetRequest(userdb[user].sessions, user, data,
boost::bind(&TwitterPlugin::RetweetResponse, this, _1, _2)));
else if(cmd == "#mode") {
int m = 0;
m = atoi(data.c_str());
mode prevm = userdb[user].twitterMode;
if((mode)m == userdb[user].twitterMode) return; //If same as current mode return
if(m < 0 || m > 2) { // Invalid modes
handleMessage(user, adminLegacyName, std::string("Error! Unknown mode ") + data + ". Allowed values 0,1,2." );
return;
}
setTwitterMode(user, m);
if((userdb[user].twitterMode == SINGLECONTACT || userdb[user].twitterMode == CHATROOM) && prevm == MULTIPLECONTACT) clearRoster(user);
else if(userdb[user].twitterMode == MULTIPLECONTACT)
tp->runAsThread(new FetchFriends(userdb[user].sessions, user, boost::bind(&TwitterPlugin::populateRoster, this, _1, _2, _3, _4)));
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
std::string("Changed mode to ") + data, userdb[user].twitterMode == CHATROOM ? adminNickName : "");
LOG4CXX_INFO(logger, user << ": Changed mode to " << data << " <" << (userdb[user].twitterMode == CHATROOM ? adminNickName : "") << ">" )
}
else if(userdb[user].twitterMode == CHATROOM) {
std::string buddy = message.substr(0, message.find(":"));
if(userdb[user].buddies.count(buddy) == 0) {
tp->runAsThread(new StatusUpdateRequest(userdb[user].sessions, user, message,
boost::bind(&TwitterPlugin::statusUpdateResponse, this, _1, _2)));
} else {
data = message.substr(message.find(":")+1); //Can parse better??:P
tp->runAsThread(new DirectMessageRequest(userdb[user].sessions, user, buddy, data,
boost::bind(&TwitterPlugin::directMessageResponse, this, _1, _2, _3, _4)));
}
}
else handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
"Unknown command! Type #help for a list of available commands.", userdb[user].twitterMode == CHATROOM ? adminNickName : "");
}
else {
std::string buddy;
if(userdb[user].twitterMode == CHATROOM) buddy = legacyName.substr(legacyName.find("/") + 1);
if(legacyName != "twitter") {
tp->runAsThread(new DirectMessageRequest(userdb[user].sessions, user, buddy, message,
boost::bind(&TwitterPlugin::directMessageResponse, this, _1, _2, _3, _4)));
}
}
}
void TwitterPlugin::handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups)
{
if(userdb[user].connectionState != CONNECTED) {
LOG4CXX_ERROR(logger, user << " is not connected to twitter!")
return;
}
LOG4CXX_INFO(logger, user << " - Adding Twitter contact " << buddyName)
tp->runAsThread(new CreateFriendRequest(userdb[user].sessions, user, buddyName,
boost::bind(&TwitterPlugin::createFriendResponse, this, _1, _2, _3, _4)));
}
void TwitterPlugin::handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups)
{
if(userdb[user].connectionState != CONNECTED) {
LOG4CXX_ERROR(logger, user << " is not connected to twitter!")
return;
}
LOG4CXX_INFO(logger, user << " - Removing Twitter contact " << buddyName)
tp->runAsThread(new DestroyFriendRequest(userdb[user].sessions, user, buddyName,
boost::bind(&TwitterPlugin::deleteFriendResponse, this, _1, _2, _3)));
}
void TwitterPlugin::handleVCardRequest(const std::string &user, const std::string &legacyName, unsigned int id)
{
if(userdb[user].connectionState != CONNECTED) {
LOG4CXX_ERROR(logger, user << " is not connected to twitter!")
return;
}
LOG4CXX_INFO(logger, user << " - VCardRequest for " << legacyName << ", " << userdb[user].buddiesInfo[legacyName].getProfileImgURL())
if(getTwitterMode(user) != SINGLECONTACT && userdb[user].buddies.count(legacyName)
&& userdb[user].buddiesInfo[legacyName].getProfileImgURL().length()) {
if(userdb[user].buddiesImgs.count(legacyName) == 0) {
tp->runAsThread(new ProfileImageRequest(config, user, legacyName, userdb[user].buddiesInfo[legacyName].getProfileImgURL(), id,
boost::bind(&TwitterPlugin::profileImageResponse, this, _1, _2, _3, _4, _5)));
}
handleVCard(user, id, legacyName, legacyName, "", userdb[user].buddiesImgs[legacyName]);
}
}
void TwitterPlugin::pollForTweets()
{
boost::mutex::scoped_lock lock(userlock);
std::set<std::string>::iterator it = onlineUsers.begin();
while(it != onlineUsers.end()) {
std::string user = *it;
tp->runAsThread(new TimelineRequest(userdb[user].sessions, user, "", userdb[user].mostRecentTweetID,
boost::bind(&TwitterPlugin::displayTweets, this, _1, _2, _3, _4)));
it++;
}
tweet_timer->start();
}
void TwitterPlugin::pollForDirectMessages()
{
boost::mutex::scoped_lock lock(userlock);
std::set<std::string>::iterator it = onlineUsers.begin();
while(it != onlineUsers.end()) {
std::string user = *it;
tp->runAsThread(new DirectMessageRequest(userdb[user].sessions, user, "", userdb[user].mostRecentDirectMessageID,
boost::bind(&TwitterPlugin::directMessageResponse, this, _1, _2, _3, _4)));
it++;
}
message_timer->start();
}
bool TwitterPlugin::getUserOAuthKeyAndSecret(const std::string user, std::string &key, std::string &secret)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
return false;
}
key="", secret=""; int type;
storagebackend->getUserSetting((long)info.id, OAUTH_KEY, type, key);
storagebackend->getUserSetting((long)info.id, OAUTH_SECRET, type, secret);
return true;
}
bool TwitterPlugin::checkSpectrum1User(const std::string user)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
return false;
}
std::string first_synchronization_done = "";
int type;
storagebackend->getUserSetting((long)info.id, "first_synchronization_done", type, first_synchronization_done);
LOG4CXX_INFO(logger, "first_synchronization_done: " << first_synchronization_done)
if(first_synchronization_done.length()) return true;
return false;
}
int TwitterPlugin::getTwitterMode(const std::string user)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
return -1;
}
int type; int m;
std::string s_m;
storagebackend->getUserSetting((long)info.id, MODE, type, s_m);
if(s_m == "") {
s_m = "0";
storagebackend->updateUserSetting((long)info.id, MODE, s_m);
}
m = atoi(s_m.c_str());
return m;
}
bool TwitterPlugin::setTwitterMode(const std::string user, int m)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
return false;
}
if(m < 0 || m > 2) {
LOG4CXX_ERROR(logger, "Unknown mode " << m <<". Using default mode 0")
m = 0;
}
userdb[user].twitterMode = (mode)m;
//int type;
std::string s_m = std::string(1,m+'0');
LOG4CXX_ERROR(logger, "Storing mode " << m <<" for user " << user)
storagebackend->updateUserSetting((long)info.id, MODE, s_m);
return true;
}
bool TwitterPlugin::storeUserOAuthKeyAndSecret(const std::string user, const std::string OAuthKey, const std::string OAuthSecret)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
return false;
}
storagebackend->updateUserSetting((long)info.id, OAUTH_KEY, OAuthKey);
storagebackend->updateUserSetting((long)info.id, OAUTH_SECRET, OAuthSecret);
return true;
}
void TwitterPlugin::initUserSession(const std::string user, const std::string legacyName, const std::string password)
{
boost::mutex::scoped_lock lock(userlock);
std::string username = legacyName;
std::string passwd = password;
LOG4CXX_INFO(logger, username + " " + passwd)
userdb[user].sessions = new twitCurl();
if(CONFIG_HAS_KEY(config,"proxy.server")) {
std::string ip = CONFIG_STRING(config,"proxy.server");
std::ostringstream out;
out << CONFIG_INT(config,"proxy.port");
std::string port = out.str();
std::string puser = CONFIG_STRING(config,"proxy.user");
std::string ppasswd = CONFIG_STRING(config,"proxy.password");
LOG4CXX_INFO(logger, ip << " " << port << " " << puser << " " << ppasswd)
if(ip != "localhost" && port != "0") {
userdb[user].sessions->setProxyServerIp(ip);
userdb[user].sessions->setProxyServerPort(port);
userdb[user].sessions->setProxyUserName(puser);
userdb[user].sessions->setProxyPassword(ppasswd);
}
}
//Check if the user is spectrum1 user
userdb[user].spectrum1User = checkSpectrum1User(user);
userdb[user].connectionState = NEW;
userdb[user].legacyName = username;
userdb[user].sessions->setTwitterUsername(username);
userdb[user].sessions->setTwitterPassword(passwd);
if(!userdb[user].spectrum1User) {
userdb[user].sessions->getOAuth().setConsumerKey(consumerKey);
userdb[user].sessions->getOAuth().setConsumerSecret(consumerSecret);
} else {
userdb[user].sessions->getOAuth().setConsumerKey(OLD_APP_KEY);
userdb[user].sessions->getOAuth().setConsumerSecret(OLD_APP_SECRET);
}
}
void TwitterPlugin::OAuthFlowComplete(const std::string user, twitCurl *obj)
{
boost::mutex::scoped_lock lock(userlock);
delete userdb[user].sessions;
userdb[user].sessions = obj->clone();
userdb[user].connectionState = WAITING_FOR_PIN;
}
void TwitterPlugin::pinExchangeComplete(const std::string user, const std::string OAuthAccessTokenKey, const std::string OAuthAccessTokenSecret)
{
boost::mutex::scoped_lock lock(userlock);
userdb[user].sessions->getOAuth().setOAuthTokenKey( OAuthAccessTokenKey );
userdb[user].sessions->getOAuth().setOAuthTokenSecret( OAuthAccessTokenSecret );
userdb[user].connectionState = CONNECTED;
userdb[user].twitterMode = (mode)getTwitterMode(user);
if(userdb[user].twitterMode == MULTIPLECONTACT) {
tp->runAsThread(new FetchFriends(userdb[user].sessions, user, boost::bind(&TwitterPlugin::populateRoster, this, _1, _2, _3, _4)));
}
onlineUsers.insert(user);
userdb[user].mostRecentTweetID = "";
userdb[user].mostRecentDirectMessageID = "";
}
void TwitterPlugin::updateLastTweetID(const std::string user, const std::string ID)
{
boost::mutex::scoped_lock lock(userlock);
userdb[user].mostRecentTweetID = ID;
}
std::string TwitterPlugin::getMostRecentTweetID(const std::string user)
{
boost::mutex::scoped_lock lock(userlock);
std::string ID = "-1";
if(onlineUsers.count(user)) ID = userdb[user].mostRecentTweetID;
return ID;
}
void TwitterPlugin::updateLastDMID(const std::string user, const std::string ID)
{
boost::mutex::scoped_lock lock(userlock);
userdb[user].mostRecentDirectMessageID = ID;
}
std::string TwitterPlugin::getMostRecentDMID(const std::string user)
{
boost::mutex::scoped_lock lock(userlock);
std::string ID = "";
if(onlineUsers.count(user)) ID = userdb[user].mostRecentDirectMessageID;
return ID;
}
/************************************** Twitter response functions **********************************/
void TwitterPlugin::statusUpdateResponse(std::string &user, Error &errMsg)
{
if(errMsg.getMessage().length()) {
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
} else {
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
"Status Update successful", userdb[user].twitterMode == CHATROOM ? adminNickName : "");
}
}
void TwitterPlugin::helpMessageResponse(std::string &user, std::string &msg)
{
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
msg, userdb[user].twitterMode == CHATROOM ? adminNickName : "");
}
void TwitterPlugin::clearRoster(const std::string user)
{
if(userdb[user].buddies.size() == 0) return;
std::set<std::string>::iterator it = userdb[user].buddies.begin();
while(it != userdb[user].buddies.end()) {
handleBuddyRemoved(user, *it);
it++;
}
userdb[user].buddies.clear();
}
void TwitterPlugin::populateRoster(std::string &user, std::vector<User> &friends, std::vector<std::string> &friendAvatars, Error &errMsg)
{
if(errMsg.getMessage().length() == 0)
{
for(int i=0 ; i<friends.size() ; i++) {
userdb[user].buddies.insert(friends[i].getScreenName());
userdb[user].buddiesInfo[friends[i].getScreenName()] = friends[i];
userdb[user].buddiesImgs[friends[i].getScreenName()] = friendAvatars[i];
if(userdb[user].twitterMode == MULTIPLECONTACT) {
std::string lastTweet = friends[i].getLastStatus().getTweet();
//LOG4CXX_INFO(logger, user << " - " << SHA(friendAvatars[i]))
handleBuddyChanged(user, friends[i].getScreenName(), friends[i].getUserName(), std::vector<std::string>(),
pbnetwork::STATUS_ONLINE, lastTweet, SHA(friendAvatars[i]));
}
else if(userdb[user].twitterMode == CHATROOM)
handleParticipantChanged(user, friends[i].getScreenName(), adminChatRoom, 0, pbnetwork::STATUS_ONLINE);
/*handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
friends[i].getScreenName() + " - " + friends[i].getLastStatus().getTweet(),
userdb[user].twitterMode == CHATROOM ? adminNickName : "");*/
}
} else handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
std::string("Error populating roster - ") + errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
if(userdb[user].twitterMode == CHATROOM) handleParticipantChanged(user, userdb[user].nickName, adminChatRoom, 0, pbnetwork::STATUS_ONLINE);
}
void TwitterPlugin::displayFriendlist(std::string &user, std::vector<User> &friends, std::vector<std::string> &friendAvatars, Error &errMsg)
{
if(errMsg.getMessage().length() == 0)
{
std::string userlist = "\n***************USER LIST****************\n";
for(int i=0 ; i < friends.size() ; i++) {
userlist += " - " + friends[i].getUserName() + " (" + friends[i].getScreenName() + ")\n";
}
userlist += "***************************************\n";
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
userlist, userdb[user].twitterMode == CHATROOM ? adminNickName : "");
} else handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
}
void TwitterPlugin::displayTweets(std::string &user, std::string &userRequested, std::vector<Status> &tweets , Error &errMsg)
{
if(errMsg.getMessage().length() == 0) {
std::string timeline = "";
std::map<std::string, int> lastTweet;
std::map<std::string, int>::iterator it;
for(int i=0 ; i<tweets.size() ; i++) {
if(userdb[user].twitterMode != CHATROOM) {
timeline += " - " + tweets[i].getUserData().getScreenName() + ": " + tweets[i].getTweet() + " (MsgId: " + tweets[i].getID() + ")\n";
std::string scrname = tweets[i].getUserData().getScreenName();
if(lastTweet.count(scrname) == 0 || cmp(tweets[lastTweet[scrname]].getID(), tweets[i].getID()) <= 0) lastTweet[scrname] = i;
} else {
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
tweets[i].getTweet() + " (MsgId: " + tweets[i].getID() + ")", tweets[i].getUserData().getScreenName());
}
}
if(userdb[user].twitterMode == MULTIPLECONTACT) {
//Set as status user's last tweet
for(it=lastTweet.begin() ; it!=lastTweet.end() ; it++) {
int t = it->second;
handleBuddyChanged(user, tweets[t].getUserData().getScreenName(), tweets[t].getUserData().getUserName(),
std::vector<std::string>(), pbnetwork::STATUS_ONLINE, tweets[t].getTweet());
}
}
if((userRequested == "" || userRequested == user) && tweets.size()) {
std::string tweetID = getMostRecentTweetID(user);
if(tweetID != tweets[0].getID()) updateLastTweetID(user, tweets[0].getID());
}
if(timeline.length()) handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
timeline, userdb[user].twitterMode == CHATROOM ? adminNickName : "");
} else handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
}
void TwitterPlugin::directMessageResponse(std::string &user, std::string &username, std::vector<DirectMessage> &messages, Error &errMsg)
{
if(errMsg.getCode() == "93") //Permission Denied
return;
if(errMsg.getMessage().length()) {
if(username != "")
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
std::string("Error while sending direct message! - ") + errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
else
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
std::string("Error while fetching direct messages! - ") + errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
return;
}
if(username != "") {
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
"Message delivered!", userdb[user].twitterMode == CHATROOM ? adminNickName : "");
return;
}
if(!messages.size()) return;
if(userdb[user].twitterMode == SINGLECONTACT) {
std::string msglist = "";
std::string msgID = getMostRecentDMID(user);
std::string maxID = msgID;
for(int i=0 ; i < messages.size() ; i++) {
if(cmp(msgID, messages[i].getID()) == -1) {
msglist += " - " + messages[i].getSenderData().getScreenName() + ": " + messages[i].getMessage() + "\n";
if(cmp(maxID, messages[i].getID()) == -1) maxID = messages[i].getID();
}
}
if(msglist.length()) handleMessage(user, adminLegacyName, msglist, "");
updateLastDMID(user, maxID);
} else {
std::string msgID = getMostRecentDMID(user);
std::string maxID = msgID;
for(int i=0 ; i < messages.size() ; i++) {
if(cmp(msgID, messages[i].getID()) == -1) {
if(userdb[user].twitterMode == MULTIPLECONTACT)
handleMessage(user, messages[i].getSenderData().getScreenName(), messages[i].getMessage(), "");
else
handleMessage(user, adminChatRoom, messages[i].getMessage() + " - <Direct Message>", messages[i].getSenderData().getScreenName());
if(cmp(maxID, messages[i].getID()) == -1) maxID = messages[i].getID();
}
}
if(maxID == getMostRecentDMID(user)) LOG4CXX_INFO(logger, "No new direct messages for " << user)
updateLastDMID(user, maxID);
}
}
void TwitterPlugin::createFriendResponse(std::string &user, User &frnd, std::string &img, Error &errMsg)
{
if(errMsg.getMessage().length()) {
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
return;
}
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
std::string("You are now following ") + frnd.getScreenName(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
userdb[user].buddies.insert(frnd.getScreenName());
userdb[user].buddiesInfo[frnd.getScreenName()] = frnd;
userdb[user].buddiesImgs[frnd.getScreenName()] = img;
LOG4CXX_INFO(logger, user << " - " << frnd.getScreenName() << ", " << frnd.getProfileImgURL())
if(userdb[user].twitterMode == MULTIPLECONTACT) {
handleBuddyChanged(user, frnd.getScreenName(), frnd.getUserName(), std::vector<std::string>(), pbnetwork::STATUS_ONLINE, "", SHA(img));
} else if(userdb[user].twitterMode == CHATROOM) {
handleParticipantChanged(user, frnd.getScreenName(), adminChatRoom, 0, pbnetwork::STATUS_ONLINE);
}
}
void TwitterPlugin::deleteFriendResponse(std::string &user, User &frnd, Error &errMsg)
{
if(errMsg.getMessage().length()) {
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
return;
}
LOG4CXX_INFO(logger, user << " - " << frnd.getScreenName() << ", " << frnd.getProfileImgURL())
userdb[user].buddies.erase(frnd.getScreenName());
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
std::string("You are not following ") + frnd.getScreenName() + " anymore", userdb[user].twitterMode == CHATROOM ? adminNickName : "");
if (userdb[user].twitterMode == CHATROOM) {
handleParticipantChanged(user, frnd.getScreenName(), adminLegacyName, 0, pbnetwork::STATUS_NONE);
}
if(userdb[user].twitterMode == MULTIPLECONTACT) {
handleBuddyRemoved(user, frnd.getScreenName());
}
}
void TwitterPlugin::RetweetResponse(std::string &user, Error &errMsg)
{
if(errMsg.getMessage().length()) {
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
} else {
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
"Retweet successful", userdb[user].twitterMode == CHATROOM ? adminNickName : "");
}
}
void TwitterPlugin::profileImageResponse(std::string &user, std::string &buddy, std::string &img, unsigned int reqID, Error &errMsg)
{
if(errMsg.getMessage().length()) {
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
} else {
LOG4CXX_INFO(logger, user << " - Sending VCard for " << buddy)
handleVCard(user, reqID, buddy, buddy, "", img);
}
}

View file

@ -0,0 +1,176 @@
#ifndef TWITTER_PLUGIN
#define TWITTER_PLUGIN
#include "transport/config.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
#include "transport/sqlite3backend.h"
#include "transport/mysqlbackend.h"
#include "transport/pqxxbackend.h"
#include "transport/storagebackend.h"
#include "transport/threadpool.h"
#include "Swiften/Swiften.h"
#include "unistd.h"
#include "signal.h"
#include "sys/wait.h"
#include "sys/signal.h"
#include <boost/algorithm/string.hpp>
#include <boost/signal.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include "twitcurl.h"
#include "TwitterResponseParser.h"
#include <iostream>
#include <sstream>
#include <map>
#include <vector>
#include <queue>
#include <set>
#include <cstdio>
#include "Swiften/StringCodecs/SHA1.h"
using namespace boost::filesystem;
using namespace boost::program_options;
using namespace Transport;
#define STR(x) (std::string("(") + x.from + ", " + x.to + ", " + x.message + ")")
class TwitterPlugin;
extern TwitterPlugin *np;
extern Swift::SimpleEventLoop *loop_; // Event Loop
class TwitterPlugin : public NetworkPlugin {
public:
Swift::BoostNetworkFactories *m_factories;
Swift::BoostIOServiceThread m_boostIOServiceThread;
boost::shared_ptr<Swift::Connection> m_conn;
Swift::Timer::ref tweet_timer;
Swift::Timer::ref message_timer;
StorageBackend *storagebackend;
TwitterPlugin(Config *config, Swift::SimpleEventLoop *loop, StorageBackend *storagebackend, const std::string &host, int port);
~TwitterPlugin();
// Send data to NetworkPlugin server
void sendData(const std::string &string);
// Receive date from the NetworkPlugin server and invoke the appropirate payload handler (implement in the NetworkPlugin class)
void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data);
// User trying to login into his twitter account
void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password);
// User logging out
void handleLogoutRequest(const std::string &user, const std::string &legacyName);
void handleJoinRoomRequest(const std::string &/*user*/, const std::string &/*room*/, const std::string &/*nickname*/, const std::string &/*pasword*/);
void handleLeaveRoomRequest(const std::string &/*user*/, const std::string &/*room*/);
void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml = "");
void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups);
void handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups);
void handleVCardRequest(const std::string &/*user*/, const std::string &/*legacyName*/, unsigned int /*id*/);
void pollForTweets();
void pollForDirectMessages();
bool getUserOAuthKeyAndSecret(const std::string user, std::string &key, std::string &secret);
bool checkSpectrum1User(const std::string user);
bool storeUserOAuthKeyAndSecret(const std::string user, const std::string OAuthKey, const std::string OAuthSecret);
void initUserSession(const std::string user, const std::string legacyName, const std::string password);
void OAuthFlowComplete(const std::string user, twitCurl *obj);
void pinExchangeComplete(const std::string user, const std::string OAuthAccessTokenKey, const std::string OAuthAccessTokenSecret);
void updateLastTweetID(const std::string user, const std::string ID);
std::string getMostRecentTweetID(const std::string user);
void updateLastDMID(const std::string user, const std::string ID);
std::string getMostRecentDMID(const std::string user);
void clearRoster(const std::string user);
int getTwitterMode(const std::string user);
bool setTwitterMode(const std::string user, int m);
/****************** Twitter response handlers **************************************/
void statusUpdateResponse(std::string &user, Error &errMsg);
void helpMessageResponse(std::string &user, std::string &msg);
void populateRoster(std::string &user, std::vector<User> &friends, std::vector<std::string> &friendAvatars, Error &errMsg);
void displayFriendlist(std::string &user, std::vector<User> &friends, std::vector<std::string> &friendAvatars, Error &errMsg);
void displayTweets(std::string &user, std::string &userRequested, std::vector<Status> &tweets , Error &errMsg);
void directMessageResponse(std::string &user, std::string &username, std::vector<DirectMessage> &messages, Error &errMsg);
void createFriendResponse(std::string &user, User &frnd, std::string &img, Error &errMsg);
void deleteFriendResponse(std::string &user, User &frnd, Error &errMsg);
void RetweetResponse(std::string &user, Error &errMsg);
void profileImageResponse(std::string &user, std::string &buddy, std::string &img, unsigned int reqID, Error &errMsg);
/***********************************************************************************/
private:
enum status {NEW, WAITING_FOR_PIN, CONNECTED, DISCONNECTED};
enum mode {SINGLECONTACT, MULTIPLECONTACT, CHATROOM};
Config *config;
std::string adminLegacyName;
std::string adminChatRoom;
std::string adminNickName;
std::string adminAlias;
std::string consumerKey;
std::string consumerSecret;
std::string OAUTH_KEY;
std::string OAUTH_SECRET;
std::string MODE;
boost::mutex dblock, userlock;
ThreadPool *tp;
std::set<std::string> onlineUsers;
struct UserData
{
std::string legacyName;
bool spectrum1User; //Legacy support
User userTwitterObj;
std::string userImg;
twitCurl* sessions;
status connectionState;
std::string mostRecentTweetID;
std::string mostRecentDirectMessageID;
std::string nickName;
std::set<std::string> buddies;
std::map<std::string, User> buddiesInfo;
std::map<std::string, std::string> buddiesImgs;
mode twitterMode;
UserData() { sessions = NULL; }
};
std::map<std::string, UserData> userdb;
};
#endif

View file

@ -0,0 +1,241 @@
#include "TwitterResponseParser.h"
#include "transport/logging.h"
#include <cctype>
DEFINE_LOGGER(logger, "TwitterResponseParser")
static std::string tolowercase(std::string inp)
{
std::string out = inp;
for(int i=0 ; i<out.size() ; i++) out[i] = tolower(out[i]);
return out;
}
EmbeddedStatus getEmbeddedStatus(const Swift::ParserElement::ref &element, const std::string xmlns)
{
EmbeddedStatus status;
if(element->getName() != TwitterReponseTypes::status) {
LOG4CXX_ERROR(logger, "Not a status element!")
return status;
}
status.setCreationTime( std::string( element->getChild(TwitterReponseTypes::created_at, xmlns)->getText() ) );
status.setID( std::string( element->getChild(TwitterReponseTypes::id, xmlns)->getText() ) );
status.setTweet( std::string( element->getChild(TwitterReponseTypes::text, xmlns)->getText() ) );
status.setTruncated( std::string( element->getChild(TwitterReponseTypes::truncated, xmlns)->getText() )=="true" );
status.setReplyToStatusID( std::string( element->getChild(TwitterReponseTypes::in_reply_to_status_id, xmlns)->getText() ) );
status.setReplyToUserID( std::string( element->getChild(TwitterReponseTypes::in_reply_to_user_id, xmlns)->getText() ) );
status.setReplyToScreenName( std::string( element->getChild(TwitterReponseTypes::in_reply_to_screen_name, xmlns)->getText() ) );
status.setRetweetCount( atoi( element->getChild(TwitterReponseTypes::retweet_count, xmlns)->getText().c_str() ) );
status.setFavorited( std::string( element->getChild(TwitterReponseTypes::favorited, xmlns)->getText() )=="true" );
status.setRetweeted( std::string( element->getChild(TwitterReponseTypes::retweeted, xmlns)->getText() )=="true" );
return status;
}
User getUser(const Swift::ParserElement::ref &element, const std::string xmlns)
{
User user;
if(element->getName() != TwitterReponseTypes::user
&& element->getName() != TwitterReponseTypes::sender
&& element->getName() != TwitterReponseTypes::recipient) {
LOG4CXX_ERROR(logger, "Not a user element!")
return user;
}
user.setUserID( std::string( element->getChild(TwitterReponseTypes::id, xmlns)->getText() ) );
user.setScreenName( tolowercase( std::string( element->getChild(TwitterReponseTypes::screen_name, xmlns)->getText() ) ) );
user.setUserName( std::string( element->getChild(TwitterReponseTypes::name, xmlns)->getText() ) );
user.setProfileImgURL( std::string( element->getChild(TwitterReponseTypes::profile_image_url, xmlns)->getText() ) );
user.setNumberOfTweets( atoi(element->getChild(TwitterReponseTypes::statuses_count, xmlns)->getText().c_str()) );
if(element->getChild(TwitterReponseTypes::status, xmlns))
user.setLastStatus(getEmbeddedStatus(element->getChild(TwitterReponseTypes::status, xmlns), xmlns));
return user;
}
Status getStatus(const Swift::ParserElement::ref &element, const std::string xmlns)
{
Status status;
if(element->getName() != "status") {
LOG4CXX_ERROR(logger, "Not a status element!")
return status;
}
status.setCreationTime( std::string( element->getChild(TwitterReponseTypes::created_at, xmlns)->getText() ) );
status.setID( std::string( element->getChild(TwitterReponseTypes::id, xmlns)->getText() ) );
status.setTweet( std::string( element->getChild(TwitterReponseTypes::text, xmlns)->getText() ) );
status.setTruncated( std::string( element->getChild(TwitterReponseTypes::truncated, xmlns)->getText() )=="true" );
status.setReplyToStatusID( std::string( element->getChild(TwitterReponseTypes::in_reply_to_status_id, xmlns)->getText() ) );
status.setReplyToUserID( std::string( element->getChild(TwitterReponseTypes::in_reply_to_user_id, xmlns)->getText() ) );
status.setReplyToScreenName( std::string( element->getChild(TwitterReponseTypes::in_reply_to_screen_name, xmlns)->getText() ) );
status.setUserData( getUser(element->getChild(TwitterReponseTypes::user, xmlns), xmlns) );
status.setRetweetCount( atoi( element->getChild(TwitterReponseTypes::retweet_count, xmlns)->getText().c_str() ) );
status.setFavorited( std::string( element->getChild(TwitterReponseTypes::favorited, xmlns)->getText() )=="true" );
status.setRetweeted( std::string( element->getChild(TwitterReponseTypes::retweeted, xmlns)->getText() )=="true" );
return status;
}
DirectMessage getDirectMessage(const Swift::ParserElement::ref &element, const std::string xmlns)
{
DirectMessage DM;
if(element->getName() != TwitterReponseTypes::direct_message) {
LOG4CXX_ERROR(logger, "Not a direct_message element!")
return DM;
}
DM.setCreationTime( std::string( element->getChild(TwitterReponseTypes::created_at, xmlns)->getText() ) );
DM.setID( std::string( element->getChild(TwitterReponseTypes::id, xmlns)->getText() ) );
DM.setMessage( std::string( element->getChild(TwitterReponseTypes::text, xmlns)->getText() ) );
DM.setSenderID( std::string( element->getChild(TwitterReponseTypes::sender_id, xmlns)->getText() ) );
DM.setRecipientID( std::string( element->getChild(TwitterReponseTypes::recipient_id, xmlns)->getText() ) );
DM.setSenderScreenName( std::string( element->getChild(TwitterReponseTypes::sender_screen_name, xmlns)->getText() ) );
DM.setRecipientScreenName( std::string( element->getChild(TwitterReponseTypes::recipient_screen_name, xmlns)->getText() ) );
DM.setSenderData( getUser(element->getChild(TwitterReponseTypes::sender, xmlns), xmlns) );
DM.setRecipientData( getUser(element->getChild(TwitterReponseTypes::recipient, xmlns), xmlns) );
return DM;
}
std::vector<Status> getTimeline(std::string &xml)
{
std::vector<Status> statuses;
Swift::ParserElement::ref rootElement = Swift::StringTreeParser::parse(xml);
if(rootElement == NULL) {
LOG4CXX_ERROR(logger, "Error while parsing XML")
return statuses;
}
if(rootElement->getName() != "statuses") {
LOG4CXX_ERROR(logger, "XML doesn't correspond to timeline")
return statuses;
}
const std::string xmlns = rootElement->getNamespace();
const std::vector<Swift::ParserElement::ref> children = rootElement->getChildren(TwitterReponseTypes::status, xmlns);
for(int i = 0; i < children.size() ; i++) {
const Swift::ParserElement::ref status = children[i];
statuses.push_back(getStatus(status, xmlns));
}
return statuses;
}
std::vector<DirectMessage> getDirectMessages(std::string &xml)
{
std::vector<DirectMessage> DMs;
Swift::ParserElement::ref rootElement = Swift::StringTreeParser::parse(xml);
if(rootElement == NULL) {
LOG4CXX_ERROR(logger, "Error while parsing XML")
return DMs;
}
if(rootElement->getName() != TwitterReponseTypes::directmessages) {
LOG4CXX_ERROR(logger, "XML doesn't correspond to direct-messages")
return DMs;
}
const std::string xmlns = rootElement->getNamespace();
const std::vector<Swift::ParserElement::ref> children = rootElement->getChildren(TwitterReponseTypes::direct_message, xmlns);
for(int i = 0; i < children.size() ; i++) {
const Swift::ParserElement::ref dm = children[i];
DMs.push_back(getDirectMessage(dm, xmlns));
}
return DMs;
}
std::vector<User> getUsers(std::string &xml)
{
std::vector<User> users;
Swift::ParserElement::ref rootElement = Swift::StringTreeParser::parse(xml);
if(rootElement == NULL) {
LOG4CXX_ERROR(logger, "Error while parsing XML")
return users;
}
if(rootElement->getName() != TwitterReponseTypes::users) {
LOG4CXX_ERROR(logger, "XML doesn't correspond to user list")
return users;
}
const std::string xmlns = rootElement->getNamespace();
const std::vector<Swift::ParserElement::ref> children = rootElement->getChildren(TwitterReponseTypes::user, xmlns);
for(int i = 0 ; i < children.size() ; i++) {
const Swift::ParserElement::ref user = children[i];
users.push_back(getUser(user, xmlns));
}
return users;
}
User getUser(std::string &xml)
{
User user;
Swift::ParserElement::ref rootElement = Swift::StringTreeParser::parse(xml);
if(rootElement == NULL) {
LOG4CXX_ERROR(logger, "Error while parsing XML")
return user;
}
if(rootElement->getName() != TwitterReponseTypes::user) {
LOG4CXX_ERROR(logger, "XML doesn't correspond to user object")
return user;
}
const std::string xmlns = rootElement->getNamespace();
return user = getUser(rootElement, xmlns);
}
std::vector<std::string> getIDs(std::string &xml)
{
std::vector<std::string> IDs;
Swift::ParserElement::ref rootElement = Swift::StringTreeParser::parse(xml);
if(rootElement == NULL) {
LOG4CXX_ERROR(logger, "Error while parsing XML")
return IDs;
}
if(rootElement->getName() != TwitterReponseTypes::id_list) {
LOG4CXX_ERROR(logger, "XML doesn't correspond to id_list");
return IDs;
}
const std::string xmlns = rootElement->getNamespace();
const std::vector<Swift::ParserElement::ref> ids = rootElement->getChild(TwitterReponseTypes::ids, xmlns)->getChildren(TwitterReponseTypes::id, xmlns);
for(int i=0 ; i<ids.size() ; i++) {
IDs.push_back(std::string( ids[i]->getText() ));
}
return IDs;
}
Error getErrorMessage(std::string &xml)
{
std::string error = "";
std::string code = "";
Error resp;
Swift::ParserElement::ref rootElement = Swift::StringTreeParser::parse(xml);
if(rootElement == NULL) {
LOG4CXX_ERROR(logger, "Error while parsing XML");
return resp;
}
const std::string xmlns = rootElement->getNamespace();
const Swift::ParserElement::ref errorElement = rootElement->getChild(TwitterReponseTypes::error, xmlns);
Swift::AttributeMap attributes = errorElement->getAttributes();
if(errorElement != NULL) {
error = errorElement->getText();
code = (errorElement->getAttributes()).getAttribute("code");
}
resp.setCode(code);
resp.setMessage(error);
return resp;
}

View file

@ -0,0 +1,218 @@
#ifndef TWITTERRESPOSNSEPARSER_H
#define TWITTERRESPOSNSEPARSER_H
#include "Swiften/Parser/StringTreeParser.h"
#include <iostream>
#include <vector>
namespace TwitterReponseTypes
{
const std::string id = "id";
const std::string id_list = "id_list";
const std::string ids = "ids";
const std::string name = "name";
const std::string screen_name = "screen_name";
const std::string statuses_count = "statuses_count";
const std::string created_at = "created_at";
const std::string text = "text";
const std::string truncated = "truncated";
const std::string in_reply_to_status_id = "in_reply_to_user_id";
const std::string in_reply_to_user_id = "in_reply_to_user_id";
const std::string in_reply_to_screen_name = "in_reply_to_screen_name";
const std::string retweet_count = "retweet_count";
const std::string favorited = "favorited";
const std::string retweeted = "retweeted";
const std::string user = "user";
const std::string users = "users";
const std::string status = "status";
const std::string error = "error";
const std::string direct_message = "direct_message";
const std::string directmessages = "direct-messages";
const std::string sender_id = "sender_id";
const std::string recipient_id = "recipient_id";
const std::string sender_screen_name = "sender_screen_name";
const std::string recipient_screen_name = "recipient_screen_name";
const std::string sender = "sender";
const std::string recipient = "recipient";
const std::string profile_image_url = "profile_image_url";
};
//Class representing an embedded status object within other objects such as the User object.
//Note: Not possible to user Status due to circular dependency
class EmbeddedStatus
{
std::string created_at;
std::string ID;
std::string text;
bool truncated;
std::string in_reply_to_status_id;
std::string in_reply_to_user_id;
std::string in_reply_to_screen_name;
unsigned int retweet_count;
bool favorited;
bool retweeted;
public:
EmbeddedStatus():created_at(""),ID(""),text(""),truncated(false),in_reply_to_status_id(""),
in_reply_to_user_id(""),in_reply_to_screen_name(""),retweet_count(0),
favorited(false),retweeted(0){}
std::string getCreationTime() {return created_at;}
std::string getID() {return ID;}
std::string getTweet() {return text;}
bool isTruncated() {return truncated;}
std::string getReplyToStatusID() {return in_reply_to_status_id;}
std::string getReplyToUserID() {return in_reply_to_user_id;}
std::string getReplyToScreenName() {return in_reply_to_screen_name;}
unsigned int getRetweetCount() {return retweet_count;}
bool isFavorited() {return favorited;}
bool isRetweeted() {return retweeted;}
void setCreationTime(std::string _created) {created_at = _created;}
void setID(std::string _id) {ID = _id;}
void setTweet(std::string _text) {text = _text;}
void setTruncated(bool val) {truncated = val;}
void setReplyToStatusID(std::string _id) {in_reply_to_status_id = _id;}
void setReplyToUserID(std::string _id) {in_reply_to_user_id = _id;}
void setReplyToScreenName(std::string _name) {in_reply_to_screen_name = _name;}
void setRetweetCount(unsigned int rc) {retweet_count = rc;}
void setFavorited(bool val) {favorited = val;}
void setRetweeted(bool val) {retweeted = val;}
};
//Class holding user data
class User
{
std::string ID;
std::string name;
std::string screen_name;
std::string profile_image_url;
unsigned int statuses_count;
EmbeddedStatus last_status;
public:
User():ID(""),name(""),screen_name(""),statuses_count(0){}
std::string getUserID() {return ID;}
std::string getUserName() {return name;}
std::string getScreenName() {return screen_name;}
std::string getProfileImgURL() {return profile_image_url;}
unsigned int getNumberOfTweets() {return statuses_count;}
EmbeddedStatus getLastStatus() {return last_status;}
void setUserID(std::string _id) {ID = _id;}
void setUserName(std::string _name) {name = _name;}
void setScreenName(std::string _screen) {screen_name = _screen;}
void setProfileImgURL(std::string _url) {profile_image_url = _url;}
void setNumberOfTweets(unsigned int sc) {statuses_count = sc;}
void setLastStatus(EmbeddedStatus _last_status) {last_status = _last_status;}
};
//Class representing a status (tweet)
class Status
{
std::string created_at;
std::string ID;
std::string text;
bool truncated;
std::string in_reply_to_status_id;
std::string in_reply_to_user_id;
std::string in_reply_to_screen_name;
User user;
unsigned int retweet_count;
bool favorited;
bool retweeted;
public:
Status():created_at(""),ID(""),text(""),truncated(false),in_reply_to_status_id(""),
in_reply_to_user_id(""),in_reply_to_screen_name(""),user(User()),retweet_count(0),
favorited(false),retweeted(0){}
std::string getCreationTime() {return created_at;}
std::string getID() {return ID;}
std::string getTweet() {return text;}
bool isTruncated() {return truncated;}
std::string getReplyToStatusID() {return in_reply_to_status_id;}
std::string getReplyToUserID() {return in_reply_to_user_id;}
std::string getReplyToScreenName() {return in_reply_to_screen_name;}
User getUserData() {return user;}
unsigned int getRetweetCount() {return retweet_count;}
bool isFavorited() {return favorited;}
bool isRetweeted() {return retweeted;}
void setCreationTime(std::string _created) {created_at = _created;}
void setID(std::string _id) {ID = _id;}
void setTweet(std::string _text) {text = _text;}
void setTruncated(bool val) {truncated = val;}
void setReplyToStatusID(std::string _id) {in_reply_to_status_id = _id;}
void setReplyToUserID(std::string _id) {in_reply_to_user_id = _id;}
void setReplyToScreenName(std::string _name) {in_reply_to_screen_name = _name;}
void setUserData(User u) {user = u;}
void setRetweetCount(unsigned int rc) {retweet_count = rc;}
void setFavorited(bool val) {favorited = val;}
void setRetweeted(bool val) {retweeted = val;}
};
//Class representing a Direct Message
class DirectMessage
{
std::string created_at;
std::string ID;
std::string text;
std::string sender_id;
std::string recipient_id;
std::string sender_screen_name;
std::string recipient_screen_name;
User sender, recipient;
public:
DirectMessage():created_at(""),ID(""),text(""),sender_id(""),recipient_id(""),
sender_screen_name(""),recipient_screen_name(""),sender(User()),recipient(User()){}
std::string getCreationTime() {return created_at;}
std::string getID() {return ID;}
std::string getMessage() {return text;}
std::string getSenderID() {return sender_id;}
std::string getRecipientID() {return recipient_id;}
std::string getSenderScreenName() {return sender_screen_name;}
std::string getRecipientScreenName() {return recipient_screen_name;}
User getSenderData() {return sender;}
User getRecipientData() {return recipient;}
void setCreationTime(std::string _created) {created_at = _created;}
void setID(std::string _id) {ID = _id;}
void setMessage(std::string _text) {text = _text;}
void setSenderID(std::string _id) {sender_id = _id;}
void setRecipientID(std::string _id) {recipient_id = _id;}
void setSenderScreenName(std::string _name) {sender_screen_name = _name;}
void setRecipientScreenName(std::string _name) {recipient_screen_name = _name;}
void setSenderData(User u) {sender = u;}
void setRecipientData(User u) {recipient = u;}
};
class Error
{
std::string code;
std::string message;
public:
Error():code(""),message(""){}
std::string getCode() {return code;}
std::string getMessage() {return message;}
void setCode(std::string &_code) {code = _code;}
void setMessage(std::string &_message) {message = _message;}
};
std::vector<Status> getTimeline(std::string &xml);
std::vector<DirectMessage> getDirectMessages(std::string &xml);
std::vector<std::string> getIDs(std::string &xml);
std::vector<User> getUsers(std::string &xml);
User getUser(std::string &xml);
Error getErrorMessage(std::string &xml);
Status getStatus(const Swift::ParserElement::ref &element, const std::string xmlns);
DirectMessage getDirectMessage(const Swift::ParserElement::ref &element, const std::string xmlns);
User getUser(const Swift::ParserElement::ref &element, const std::string xmlns);
#endif

View file

@ -0,0 +1,4 @@
set(twitSrcs base64.cpp HMAC_SHA1.cpp oauthlib.cpp SHA1.cpp urlencode.cpp twitcurl.cpp)
FIND_PACKAGE(PkgConfig)
include_directories (${PKGS_INCLUDE_DIRS})
add_library(twitcurl STATIC ${twitSrcs})

View file

@ -0,0 +1,19 @@
Copyright (C) 2011 by swatkat (swatkat.thinkdigitATgmailDOTcom)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
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
THE SOFTWARE.

View file

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

View file

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

View file

@ -0,0 +1,274 @@
/*
100% free public domain implementation of the SHA-1 algorithm
by Dominik Reichl <dominik.reichl@t-online.de>
Web: http://www.dominik-reichl.de/
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
header file of the CSHA1 class any more
- Aligned data support
- Made support/compilation of the utility functions (ReportHash
and HashFile) optional (useful, if bytes count, for example in
embedded environments)
Version 1.5 - 2005-01-01
- 64-bit compiler compatibility added
- Made variable wiping optional (define SHA1_WIPE_VARIABLES)
- Removed unnecessary variable initializations
- ROL32 improvement for the Microsoft compiler (using _rotl)
======== Test Vectors (from FIPS PUB 180-1) ========
SHA1("abc") =
A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") =
84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
SHA1(A million repetitions of "a") =
34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
*/
#include "SHA1.h"
#ifdef SHA1_UTILITY_FUNCTIONS
#define SHA1_MAX_FILE_BUFFER 8000
#endif
// Rotate x bits to the left
#ifndef ROL32
#ifdef _MSC_VER
#define ROL32(_val32, _nBits) _rotl(_val32, _nBits)
#else
#define ROL32(_val32, _nBits) (((_val32)<<(_nBits))|((_val32)>>(32-(_nBits))))
#endif
#endif
#ifdef SHA1_LITTLE_ENDIAN
#define SHABLK0(i) (m_block->l[i] = \
(ROL32(m_block->l[i],24) & 0xFF00FF00) | (ROL32(m_block->l[i],8) & 0x00FF00FF))
#else
#define SHABLK0(i) (m_block->l[i])
#endif
#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))
// 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 _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 _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); }
CSHA1::CSHA1()
{
m_block = (SHA1_WORKSPACE_BLOCK *)m_workspace;
Reset();
}
CSHA1::~CSHA1()
{
Reset();
}
void CSHA1::Reset()
{
// SHA1 initialization constants
m_state[0] = 0x67452301;
m_state[1] = 0xEFCDAB89;
m_state[2] = 0x98BADCFE;
m_state[3] = 0x10325476;
m_state[4] = 0xC3D2E1F0;
m_count[0] = 0;
m_count[1] = 0;
}
void CSHA1::Transform(UINT_32 *state, UINT_8 *buffer)
{
// Copy state[] to working vars
UINT_32 a = state[0], b = state[1], c = state[2], d = state[3], e = state[4];
memcpy(m_block, buffer, 64);
// 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(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(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);
_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(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(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(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(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);
_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(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(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
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
// Wipe variables
#ifdef SHA1_WIPE_VARIABLES
a = b = c = d = e = 0;
#endif
}
// Use this function to hash in binary data and strings
void CSHA1::Update(UINT_8 *data, UINT_32 len)
{
UINT_32 i, j;
j = (m_count[0] >> 3) & 63;
if((m_count[0] += len << 3) < (len << 3)) m_count[1]++;
m_count[1] += (len >> 29);
if((j + len) > 63)
{
i = 64 - j;
memcpy(&m_buffer[j], data, i);
Transform(m_state, m_buffer);
for(; i + 63 < len; i += 64) Transform(m_state, &data[i]);
j = 0;
}
else i = 0;
memcpy(&m_buffer[j], &data[i], len - i);
}
#ifdef SHA1_UTILITY_FUNCTIONS
// Hash in file contents
bool CSHA1::HashFile(char *szFileName)
{
unsigned long ulFileSize, ulRest, ulBlocks;
unsigned long i;
UINT_8 uData[SHA1_MAX_FILE_BUFFER];
FILE *fIn;
if(szFileName == NULL) return false;
fIn = fopen(szFileName, "rb");
if(fIn == NULL) return false;
fseek(fIn, 0, SEEK_END);
ulFileSize = (unsigned long)ftell(fIn);
fseek(fIn, 0, SEEK_SET);
if(ulFileSize != 0)
{
ulBlocks = ulFileSize / SHA1_MAX_FILE_BUFFER;
ulRest = ulFileSize % SHA1_MAX_FILE_BUFFER;
}
else
{
ulBlocks = 0;
ulRest = 0;
}
for(i = 0; i < ulBlocks; i++)
{
fread(uData, 1, SHA1_MAX_FILE_BUFFER, fIn);
Update((UINT_8 *)uData, SHA1_MAX_FILE_BUFFER);
}
if(ulRest != 0)
{
fread(uData, 1, ulRest, fIn);
Update((UINT_8 *)uData, ulRest);
}
fclose(fIn); fIn = NULL;
return true;
}
#endif
void CSHA1::Final()
{
UINT_32 i;
UINT_8 finalcount[8];
for(i = 0; i < 8; i++)
finalcount[i] = (UINT_8)((m_count[((i >= 4) ? 0 : 1)]
>> ((3 - (i & 3)) * 8) ) & 255); // Endian independent
Update((UINT_8 *)"\200", 1);
while ((m_count[0] & 504) != 448)
Update((UINT_8 *)"\0", 1);
Update(finalcount, 8); // Cause a SHA1Transform()
for(i = 0; i < 20; i++)
{
m_digest[i] = (UINT_8)((m_state[i >> 2] >> ((3 - (i & 3)) * 8) ) & 255);
}
// Wipe variables for security reasons
#ifdef SHA1_WIPE_VARIABLES
i = 0;
memset(m_buffer, 0, 64);
memset(m_state, 0, 20);
memset(m_count, 0, 8);
memset(finalcount, 0, 8);
Transform(m_state, m_buffer);
#endif
}
#ifdef SHA1_UTILITY_FUNCTIONS
// Get the final hash as a pre-formatted string
void CSHA1::ReportHash(char *szReport, unsigned char uReportType)
{
unsigned char i;
char szTemp[16];
if(szReport == NULL) return;
if(uReportType == REPORT_HEX)
{
sprintf(szTemp, "%02X", m_digest[0]);
strcat(szReport, szTemp);
for(i = 1; i < 20; i++)
{
sprintf(szTemp, " %02X", m_digest[i]);
strcat(szReport, szTemp);
}
}
else if(uReportType == REPORT_DIGIT)
{
sprintf(szTemp, "%u", m_digest[0]);
strcat(szReport, szTemp);
for(i = 1; i < 20; i++)
{
sprintf(szTemp, " %u", m_digest[i]);
strcat(szReport, szTemp);
}
}
else strcpy(szReport, "Error: Unknown report type!");
}
#endif
// Get the raw message digest
void CSHA1::GetHash(UINT_8 *puDest)
{
memcpy(puDest, m_digest, 20);
}

View file

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

View file

@ -0,0 +1,123 @@
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
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
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
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
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
#include "base64.h"
#include <iostream>
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
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[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
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[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <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[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];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <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[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];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}

View file

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

View file

@ -0,0 +1,21 @@
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 1996 - 2011, Daniel Stenberg, <daniel@haxx.se>.
All rights reserved.
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER 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 THE SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization of the copyright holder.

View file

@ -0,0 +1,53 @@
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://curl.haxx.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
pkginclude_HEADERS = \
curl.h curlver.h easy.h mprintf.h stdcheaders.h multi.h \
typecheck-gcc.h curlbuild.h curlrules.h
pkgincludedir= $(includedir)/curl
# curlbuild.h does not exist in the git tree. When the original libcurl
# source code distribution archive file is created, curlbuild.h.dist is
# renamed to curlbuild.h and included in the tarball so that it can be
# used directly on non-configure systems.
#
# The distributed curlbuild.h will be overwritten on configure systems
# when the configure script runs, with one that is suitable and specific
# to the library being configured and built.
#
# curlbuild.h.in is the distributed template file from which the configure
# script creates curlbuild.h at library configuration time, overwiting the
# one included in the distribution archive.
#
# curlbuild.h.dist is not included in the source code distribution archive.
EXTRA_DIST = curlbuild.h.in
DISTCLEANFILES = curlbuild.h
checksrc:
@@PERL@ $(top_srcdir)/lib/checksrc.pl -Wcurlbuild.h -D$(top_srcdir)/include/curl $(pkginclude_HEADERS) $(EXTRA_DIST)
if CURLDEBUG
# for debug builds, we scan the sources on all regular make invokes
all-local: checksrc
endif

View file

@ -0,0 +1,560 @@
# Makefile.in generated by automake 1.9.6 from Makefile.am.
# @configure_input@
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
@SET_MAKE@
srcdir = @srcdir@
top_srcdir = @top_srcdir@
VPATH = @srcdir@
pkgdatadir = $(datadir)/@PACKAGE@
pkglibdir = $(libdir)/@PACKAGE@
top_builddir = ../..
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
INSTALL = @INSTALL@
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = @build@
host_triplet = @host@
subdir = include/curl
DIST_COMMON = $(pkginclude_HEADERS) $(srcdir)/Makefile.am \
$(srcdir)/Makefile.in $(srcdir)/curlbuild.h.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/curl-compilers.m4 \
$(top_srcdir)/m4/curl-confopts.m4 \
$(top_srcdir)/m4/curl-functions.m4 \
$(top_srcdir)/m4/curl-openssl.m4 \
$(top_srcdir)/m4/curl-override.m4 \
$(top_srcdir)/m4/curl-reentrant.m4 \
$(top_srcdir)/m4/curl-system.m4 $(top_srcdir)/m4/libtool.m4 \
$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
$(top_srcdir)/m4/xc-translit.m4 $(top_srcdir)/acinclude.m4 \
$(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs
CONFIG_HEADER = $(top_builddir)/lib/curl_config.h \
$(top_builddir)/src/curl_config.h curlbuild.h
CONFIG_CLEAN_FILES =
SOURCES =
DIST_SOURCES =
am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
am__vpath_adj = case $$p in \
$(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
*) f=$$p;; \
esac;
am__strip_dir = `echo $$p | sed -e 's|^.*/||'`;
am__installdirs = "$(DESTDIR)$(pkgincludedir)"
pkgincludeHEADERS_INSTALL = $(INSTALL_HEADER)
HEADERS = $(pkginclude_HEADERS)
ETAGS = etags
CTAGS = ctags
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
pkgincludedir = $(includedir)/curl
ACLOCAL = @ACLOCAL@
AMDEP_FALSE = @AMDEP_FALSE@
AMDEP_TRUE = @AMDEP_TRUE@
AMTAR = @AMTAR@
AR = @AR@
AS = @AS@
AUTOCONF = @AUTOCONF@
AUTOHEADER = @AUTOHEADER@
AUTOMAKE = @AUTOMAKE@
AWK = @AWK@
BUILD_LIBHOSTNAME_FALSE = @BUILD_LIBHOSTNAME_FALSE@
BUILD_LIBHOSTNAME_TRUE = @BUILD_LIBHOSTNAME_TRUE@
BUILD_UNITTESTS_FALSE = @BUILD_UNITTESTS_FALSE@
BUILD_UNITTESTS_TRUE = @BUILD_UNITTESTS_TRUE@
CC = @CC@
CCDEPMODE = @CCDEPMODE@
CFLAGS = @CFLAGS@
CONFIGURE_OPTIONS = @CONFIGURE_OPTIONS@
CPP = @CPP@
CPPFLAGS = @CPPFLAGS@
CROSSCOMPILING_FALSE = @CROSSCOMPILING_FALSE@
CROSSCOMPILING_TRUE = @CROSSCOMPILING_TRUE@
CURLDEBUG_FALSE = @CURLDEBUG_FALSE@
CURLDEBUG_TRUE = @CURLDEBUG_TRUE@
CURLVERSION = @CURLVERSION@
CURL_CA_BUNDLE = @CURL_CA_BUNDLE@
CURL_CFLAG_EXTRAS = @CURL_CFLAG_EXTRAS@
CURL_DISABLE_DICT = @CURL_DISABLE_DICT@
CURL_DISABLE_FILE = @CURL_DISABLE_FILE@
CURL_DISABLE_FTP = @CURL_DISABLE_FTP@
CURL_DISABLE_GOPHER = @CURL_DISABLE_GOPHER@
CURL_DISABLE_HTTP = @CURL_DISABLE_HTTP@
CURL_DISABLE_IMAP = @CURL_DISABLE_IMAP@
CURL_DISABLE_LDAP = @CURL_DISABLE_LDAP@
CURL_DISABLE_LDAPS = @CURL_DISABLE_LDAPS@
CURL_DISABLE_POP3 = @CURL_DISABLE_POP3@
CURL_DISABLE_PROXY = @CURL_DISABLE_PROXY@
CURL_DISABLE_RTSP = @CURL_DISABLE_RTSP@
CURL_DISABLE_SMTP = @CURL_DISABLE_SMTP@
CURL_DISABLE_TELNET = @CURL_DISABLE_TELNET@
CURL_DISABLE_TFTP = @CURL_DISABLE_TFTP@
CURL_LIBS = @CURL_LIBS@
CURL_NETWORK_LIBS = @CURL_NETWORK_LIBS@
CYGPATH_W = @CYGPATH_W@
DEFS = @DEFS@
DEPDIR = @DEPDIR@
DLLTOOL = @DLLTOOL@
DSYMUTIL = @DSYMUTIL@
DUMPBIN = @DUMPBIN@
ECHO_C = @ECHO_C@
ECHO_N = @ECHO_N@
ECHO_T = @ECHO_T@
EGREP = @EGREP@
ENABLE_SHARED = @ENABLE_SHARED@
EXEEXT = @EXEEXT@
FGREP = @FGREP@
GREP = @GREP@
HAVE_GNUTLS_SRP = @HAVE_GNUTLS_SRP@
HAVE_LDAP_SSL = @HAVE_LDAP_SSL@
HAVE_LIBZ = @HAVE_LIBZ@
HAVE_LIBZ_FALSE = @HAVE_LIBZ_FALSE@
HAVE_LIBZ_TRUE = @HAVE_LIBZ_TRUE@
HAVE_PK11_CREATEGENERICOBJECT = @HAVE_PK11_CREATEGENERICOBJECT@
HAVE_SSLEAY_SRP = @HAVE_SSLEAY_SRP@
IDN_ENABLED = @IDN_ENABLED@
INSTALL_DATA = @INSTALL_DATA@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_SCRIPT = @INSTALL_SCRIPT@
INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
IPV6_ENABLED = @IPV6_ENABLED@
KRB4_ENABLED = @KRB4_ENABLED@
LD = @LD@
LDFLAGS = @LDFLAGS@
LIBCURL_LIBS = @LIBCURL_LIBS@
LIBOBJS = @LIBOBJS@
LIBS = @LIBS@
LIBTOOL = @LIBTOOL@
LIPO = @LIPO@
LN_S = @LN_S@
LTLIBOBJS = @LTLIBOBJS@
MAINT = @MAINT@
MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@
MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@
MAKEINFO = @MAKEINFO@
MANIFEST_TOOL = @MANIFEST_TOOL@
MANOPT = @MANOPT@
MIMPURE_FALSE = @MIMPURE_FALSE@
MIMPURE_TRUE = @MIMPURE_TRUE@
NM = @NM@
NMEDIT = @NMEDIT@
NO_UNDEFINED_FALSE = @NO_UNDEFINED_FALSE@
NO_UNDEFINED_TRUE = @NO_UNDEFINED_TRUE@
NROFF = @NROFF@
OBJDUMP = @OBJDUMP@
OBJEXT = @OBJEXT@
OTOOL = @OTOOL@
OTOOL64 = @OTOOL64@
PACKAGE = @PACKAGE@
PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
PACKAGE_NAME = @PACKAGE_NAME@
PACKAGE_STRING = @PACKAGE_STRING@
PACKAGE_TARNAME = @PACKAGE_TARNAME@
PACKAGE_URL = @PACKAGE_URL@
PACKAGE_VERSION = @PACKAGE_VERSION@
PATH = @PATH@
PATH_SEPARATOR = @PATH_SEPARATOR@
PERL = @PERL@
PKGADD_NAME = @PKGADD_NAME@
PKGADD_PKG = @PKGADD_PKG@
PKGADD_VENDOR = @PKGADD_VENDOR@
PKGCONFIG = @PKGCONFIG@
RANDOM_FILE = @RANDOM_FILE@
RANLIB = @RANLIB@
REQUIRE_LIB_DEPS = @REQUIRE_LIB_DEPS@
SED = @SED@
SET_MAKE = @SET_MAKE@
SHELL = @SHELL@
SONAME_BUMP_FALSE = @SONAME_BUMP_FALSE@
SONAME_BUMP_TRUE = @SONAME_BUMP_TRUE@
SSL_ENABLED = @SSL_ENABLED@
STATICLIB_FALSE = @STATICLIB_FALSE@
STATICLIB_TRUE = @STATICLIB_TRUE@
STRIP = @STRIP@
SUPPORT_FEATURES = @SUPPORT_FEATURES@
SUPPORT_PROTOCOLS = @SUPPORT_PROTOCOLS@
TEST_SERVER_LIBS = @TEST_SERVER_LIBS@
USE_ARES = @USE_ARES@
USE_AXTLS = @USE_AXTLS@
USE_CYASSL = @USE_CYASSL@
USE_EMBEDDED_ARES_FALSE = @USE_EMBEDDED_ARES_FALSE@
USE_EMBEDDED_ARES_TRUE = @USE_EMBEDDED_ARES_TRUE@
USE_GNUTLS = @USE_GNUTLS@
USE_LIBRTMP = @USE_LIBRTMP@
USE_LIBSSH2 = @USE_LIBSSH2@
USE_MANUAL_FALSE = @USE_MANUAL_FALSE@
USE_MANUAL_TRUE = @USE_MANUAL_TRUE@
USE_NSS = @USE_NSS@
USE_OPENLDAP = @USE_OPENLDAP@
USE_POLARSSL = @USE_POLARSSL@
USE_SSLEAY = @USE_SSLEAY@
USE_WINDOWS_SSPI = @USE_WINDOWS_SSPI@
VERSION = @VERSION@
VERSIONNUM = @VERSIONNUM@
ac_ct_AR = @ac_ct_AR@
ac_ct_CC = @ac_ct_CC@
ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
am__include = @am__include@
am__leading_dot = @am__leading_dot@
am__quote = @am__quote@
am__tar = @am__tar@
am__untar = @am__untar@
bindir = @bindir@
build = @build@
build_alias = @build_alias@
build_cpu = @build_cpu@
build_os = @build_os@
build_vendor = @build_vendor@
datadir = @datadir@
datarootdir = @datarootdir@
docdir = @docdir@
dvidir = @dvidir@
exec_prefix = @exec_prefix@
host = @host@
host_alias = @host_alias@
host_cpu = @host_cpu@
host_os = @host_os@
host_vendor = @host_vendor@
htmldir = @htmldir@
includedir = @includedir@
infodir = @infodir@
install_sh = @install_sh@
libdir = @libdir@
libexecdir = @libexecdir@
libext = @libext@
localedir = @localedir@
localstatedir = @localstatedir@
mandir = @mandir@
mkdir_p = @mkdir_p@
oldincludedir = @oldincludedir@
pdfdir = @pdfdir@
prefix = @prefix@
program_transform_name = @program_transform_name@
psdir = @psdir@
sbindir = @sbindir@
sharedstatedir = @sharedstatedir@
subdirs = @subdirs@
sysconfdir = @sysconfdir@
target_alias = @target_alias@
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://curl.haxx.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
pkginclude_HEADERS = \
curl.h curlver.h easy.h mprintf.h stdcheaders.h multi.h \
typecheck-gcc.h curlbuild.h curlrules.h
# curlbuild.h does not exist in the git tree. When the original libcurl
# source code distribution archive file is created, curlbuild.h.dist is
# renamed to curlbuild.h and included in the tarball so that it can be
# used directly on non-configure systems.
#
# The distributed curlbuild.h will be overwritten on configure systems
# when the configure script runs, with one that is suitable and specific
# to the library being configured and built.
#
# curlbuild.h.in is the distributed template file from which the configure
# script creates curlbuild.h at library configuration time, overwiting the
# one included in the distribution archive.
#
# curlbuild.h.dist is not included in the source code distribution archive.
EXTRA_DIST = curlbuild.h.in
DISTCLEANFILES = curlbuild.h
all: curlbuild.h
$(MAKE) $(AM_MAKEFLAGS) all-am
.SUFFIXES:
$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
&& exit 0; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign include/curl/Makefile'; \
cd $(top_srcdir) && \
$(AUTOMAKE) --foreign include/curl/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
curlbuild.h: stamp-h3
@if test ! -f $@; then \
rm -f stamp-h3; \
$(MAKE) stamp-h3; \
else :; fi
stamp-h3: $(srcdir)/curlbuild.h.in $(top_builddir)/config.status
@rm -f stamp-h3
cd $(top_builddir) && $(SHELL) ./config.status include/curl/curlbuild.h
$(srcdir)/curlbuild.h.in: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)
cd $(top_srcdir) && $(AUTOHEADER)
rm -f stamp-h3
touch $@
distclean-hdr:
-rm -f curlbuild.h stamp-h3
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
distclean-libtool:
-rm -f libtool
uninstall-info-am:
install-pkgincludeHEADERS: $(pkginclude_HEADERS)
@$(NORMAL_INSTALL)
test -z "$(pkgincludedir)" || $(mkdir_p) "$(DESTDIR)$(pkgincludedir)"
@list='$(pkginclude_HEADERS)'; for p in $$list; do \
if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
f=$(am__strip_dir) \
echo " $(pkgincludeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(pkgincludedir)/$$f'"; \
$(pkgincludeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(pkgincludedir)/$$f"; \
done
uninstall-pkgincludeHEADERS:
@$(NORMAL_UNINSTALL)
@list='$(pkginclude_HEADERS)'; for p in $$list; do \
f=$(am__strip_dir) \
echo " rm -f '$(DESTDIR)$(pkgincludedir)/$$f'"; \
rm -f "$(DESTDIR)$(pkgincludedir)/$$f"; \
done
ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) ' { files[$$0] = 1; } \
END { for (i in files) print i; }'`; \
mkid -fID $$unique
tags: TAGS
TAGS: $(HEADERS) $(SOURCES) curlbuild.h.in $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
tags=; \
here=`pwd`; \
list='$(SOURCES) $(HEADERS) curlbuild.h.in $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) ' { files[$$0] = 1; } \
END { for (i in files) print i; }'`; \
if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$tags $$unique; \
fi
ctags: CTAGS
CTAGS: $(HEADERS) $(SOURCES) curlbuild.h.in $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
tags=; \
here=`pwd`; \
list='$(SOURCES) $(HEADERS) curlbuild.h.in $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) ' { files[$$0] = 1; } \
END { for (i in files) print i; }'`; \
test -z "$(CTAGS_ARGS)$$tags$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$tags $$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& cd $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) $$here
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
list='$(DISTFILES)'; for file in $$list; do \
case $$file in \
$(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
$(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
esac; \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
if test "$$dir" != "$$file" && test "$$dir" != "."; then \
dir="/$$dir"; \
$(mkdir_p) "$(distdir)$$dir"; \
else \
dir=''; \
fi; \
if test -d $$d/$$file; then \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
fi; \
cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
else \
test -f $(distdir)/$$file \
|| cp -p $$d/$$file $(distdir)/$$file \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
@CURLDEBUG_FALSE@all-local:
all-am: Makefile $(HEADERS) curlbuild.h all-local
installdirs:
for dir in "$(DESTDIR)$(pkgincludedir)"; do \
test -z "$$dir" || $(mkdir_p) "$$dir"; \
done
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
`test -z '$(STRIP)' || \
echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libtool mostlyclean-am
distclean: distclean-am
-rm -f Makefile
distclean-am: clean-am distclean-generic distclean-hdr \
distclean-libtool distclean-tags
dvi: dvi-am
dvi-am:
html: html-am
info: info-am
info-am:
install-data-am: install-pkgincludeHEADERS
install-exec-am:
install-info: install-info-am
install-man:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: uninstall-info-am uninstall-pkgincludeHEADERS
.PHONY: CTAGS GTAGS all all-am all-local check check-am clean \
clean-generic clean-libtool ctags distclean distclean-generic \
distclean-hdr distclean-libtool distclean-tags distdir dvi \
dvi-am html html-am info info-am install install-am \
install-data install-data-am install-exec install-exec-am \
install-info install-info-am install-man \
install-pkgincludeHEADERS install-strip installcheck \
installcheck-am installdirs maintainer-clean \
maintainer-clean-generic mostlyclean mostlyclean-generic \
mostlyclean-libtool pdf pdf-am ps ps-am tags uninstall \
uninstall-am uninstall-info-am uninstall-pkgincludeHEADERS
checksrc:
@@PERL@ $(top_srcdir)/lib/checksrc.pl -Wcurlbuild.h -D$(top_srcdir)/include/curl $(pkginclude_HEADERS) $(EXTRA_DIST)
# for debug builds, we scan the sources on all regular make invokes
@CURLDEBUG_TRUE@all-local: checksrc
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,583 @@
#ifndef __CURL_CURLBUILD_H
#define __CURL_CURLBUILD_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* ================================================================ */
/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* See file include/curl/curlbuild.h.in, run configure, and forget
* that this file exists it is only used for non-configure systems.
* But you can keep reading if you want ;-)
*
*/
/* ================================================================ */
/* NOTES FOR NON-CONFIGURE SYSTEMS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* Nothing in this file is intended to be modified or adjusted by the
* curl library user nor by the curl library builder.
*
* If you think that something actually needs to be changed, adjusted
* or fixed in this file, then, report it on the libcurl development
* mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/
*
* Try to keep one section per platform, compiler and architecture,
* otherwise, if an existing section is reused for a different one and
* later on the original is adjusted, probably the piggybacking one can
* be adversely changed.
*
* In order to differentiate between platforms/compilers/architectures
* use only compiler built in predefined preprocessor symbols.
*
* This header file shall only export symbols which are 'curl' or 'CURL'
* prefixed, otherwise public name space would be polluted.
*
* NOTE 2:
* -------
*
* For any given platform/compiler curl_off_t must be typedef'ed to a
* 64-bit wide signed integral data type. The width of this data type
* must remain constant and independent of any possible large file
* support settings.
*
* As an exception to the above, curl_off_t shall be typedef'ed to a
* 32-bit wide signed integral data type if there is no 64-bit type.
*
* As a general rule, curl_off_t shall not be mapped to off_t. This
* rule shall only be violated if off_t is the only 64-bit data type
* available and the size of off_t is independent of large file support
* settings. Keep your build on the safe side avoiding an off_t gating.
* If you have a 64-bit off_t then take for sure that another 64-bit
* data type exists, dig deeper and you will find it.
*
* NOTE 3:
* -------
*
* Right now you might be staring at file include/curl/curlbuild.h.dist or
* at file include/curl/curlbuild.h, this is due to the following reason:
* file include/curl/curlbuild.h.dist is renamed to include/curl/curlbuild.h
* when the libcurl source code distribution archive file is created.
*
* File include/curl/curlbuild.h.dist is not included in the distribution
* archive. File include/curl/curlbuild.h is not present in the git tree.
*
* The distributed include/curl/curlbuild.h file is only intended to be used
* on systems which can not run the also distributed configure script.
*
* On systems capable of running the configure script, the configure process
* will overwrite the distributed include/curl/curlbuild.h file with one that
* is suitable and specific to the library being configured and built, which
* is generated from the include/curl/curlbuild.h.in template file.
*
* If you check out from git on a non-configure platform, you must run the
* appropriate buildconf* script to set up curlbuild.h and other local files.
*
*/
/* ================================================================ */
/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */
/* ================================================================ */
#ifdef CURL_SIZEOF_LONG
# error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined
#endif
#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
# error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined
#endif
#ifdef CURL_SIZEOF_CURL_SOCKLEN_T
# error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined
#endif
#ifdef CURL_TYPEOF_CURL_OFF_T
# error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined
#endif
#ifdef CURL_FORMAT_CURL_OFF_T
# error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined
#endif
#ifdef CURL_FORMAT_CURL_OFF_TU
# error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined
#endif
#ifdef CURL_FORMAT_OFF_T
# error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined
#endif
#ifdef CURL_SIZEOF_CURL_OFF_T
# error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined
#endif
#ifdef CURL_SUFFIX_CURL_OFF_T
# error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined
#endif
#ifdef CURL_SUFFIX_CURL_OFF_TU
# error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined
#endif
/* ================================================================ */
/* EXTERNAL INTERFACE SETTINGS FOR NON-CONFIGURE SYSTEMS ONLY */
/* ================================================================ */
#if defined(__DJGPP__) || defined(__GO32__)
# if defined(__DJGPP__) && (__DJGPP__ > 1)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__SALFORDC__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__BORLANDC__)
# if (__BORLANDC__ < 0x520)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__TURBOC__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__WATCOMC__)
# if defined(__386__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__POCC__)
# if (__POCC__ < 280)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# elif defined(_MSC_VER)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__LCC__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__SYMBIAN32__)
# if defined(__EABI__) /* Treat all ARM compilers equally */
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(__CW32__)
# pragma longlong on
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(__VC32__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__MWERKS__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(_WIN32_WCE)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__MINGW32__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__VMS)
# if defined(__VAX)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__OS400__)
# if defined(__ILEC400__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
# endif
#elif defined(__MVS__)
# if defined(__IBMC__) || defined(__IBMCPP__)
# if defined(_ILP32)
# define CURL_SIZEOF_LONG 4
# elif defined(_LP64)
# define CURL_SIZEOF_LONG 8
# endif
# if defined(_LONG_LONG)
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(_LP64)
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# else
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
# endif
#elif defined(__370__)
# if defined(__IBMC__) || defined(__IBMCPP__)
# if defined(_ILP32)
# define CURL_SIZEOF_LONG 4
# elif defined(_LP64)
# define CURL_SIZEOF_LONG 8
# endif
# if defined(_LONG_LONG)
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(_LP64)
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# else
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
# endif
#elif defined(TPF)
# define CURL_SIZEOF_LONG 8
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
/* ===================================== */
/* KEEP MSVC THE PENULTIMATE ENTRY */
/* ===================================== */
#elif defined(_MSC_VER)
# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
/* ===================================== */
/* KEEP GENERIC GCC THE LAST ENTRY */
/* ===================================== */
#elif defined(__GNUC__)
# if defined(__i386__) || defined(__ppc__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(__x86_64__) || defined(__ppc64__)
# define CURL_SIZEOF_LONG 8
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
#else
# error "Unknown non-configure build target!"
Error Compilation_aborted_Unknown_non_configure_build_target
#endif
/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */
/* sys/types.h is required here to properly make type definitions below. */
#ifdef CURL_PULL_SYS_TYPES_H
# include <sys/types.h>
#endif
/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file */
/* sys/socket.h is required here to properly make type definitions below. */
#ifdef CURL_PULL_SYS_SOCKET_H
# include <sys/socket.h>
#endif
/* Data type definition of curl_socklen_t. */
#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t;
#endif
/* Data type definition of curl_off_t. */
#ifdef CURL_TYPEOF_CURL_OFF_T
typedef CURL_TYPEOF_CURL_OFF_T curl_off_t;
#endif
#endif /* __CURL_CURLBUILD_H */

View file

@ -0,0 +1,180 @@
#ifndef __CURL_CURLBUILD_H
#define __CURL_CURLBUILD_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2008, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* ================================================================ */
/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* Nothing in this file is intended to be modified or adjusted by the
* curl library user nor by the curl library builder.
*
* If you think that something actually needs to be changed, adjusted
* or fixed in this file, then, report it on the libcurl development
* mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/
*
* This header file shall only export symbols which are 'curl' or 'CURL'
* prefixed, otherwise public name space would be polluted.
*
* NOTE 2:
* -------
*
* Right now you might be staring at file include/curl/curlbuild.h.in or
* at file include/curl/curlbuild.h, this is due to the following reason:
*
* On systems capable of running the configure script, the configure process
* will overwrite the distributed include/curl/curlbuild.h file with one that
* is suitable and specific to the library being configured and built, which
* is generated from the include/curl/curlbuild.h.in template file.
*
*/
/* ================================================================ */
/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */
/* ================================================================ */
#ifdef CURL_SIZEOF_LONG
# error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined
#endif
#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
# error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined
#endif
#ifdef CURL_SIZEOF_CURL_SOCKLEN_T
# error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined
#endif
#ifdef CURL_TYPEOF_CURL_OFF_T
# error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined
#endif
#ifdef CURL_FORMAT_CURL_OFF_T
# error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined
#endif
#ifdef CURL_FORMAT_CURL_OFF_TU
# error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined
#endif
#ifdef CURL_FORMAT_OFF_T
# error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined
#endif
#ifdef CURL_SIZEOF_CURL_OFF_T
# error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined
#endif
#ifdef CURL_SUFFIX_CURL_OFF_T
# error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined
#endif
#ifdef CURL_SUFFIX_CURL_OFF_TU
# error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined
#endif
/* ================================================================ */
/* EXTERNAL INTERFACE SETTINGS FOR CONFIGURE CAPABLE SYSTEMS ONLY */
/* ================================================================ */
/* Configure process defines this to 1 when it finds out that system */
/* header file sys/types.h must be included by the external interface. */
#cmakedefine CURL_PULL_SYS_TYPES_H ${CURL_PULL_SYS_TYPES_H}
#ifdef CURL_PULL_SYS_TYPES_H
# include <sys/types.h>
#endif
/* Configure process defines this to 1 when it finds out that system */
/* header file stdint.h must be included by the external interface. */
#cmakedefine CURL_PULL_STDINT_H ${CURL_PULL_STDINT_H}
#ifdef CURL_PULL_STDINT_H
# include <stdint.h>
#endif
/* Configure process defines this to 1 when it finds out that system */
/* header file inttypes.h must be included by the external interface. */
#cmakedefine CURL_PULL_INTTYPES_H ${CURL_PULL_INTTYPES_H}
#ifdef CURL_PULL_INTTYPES_H
# include <inttypes.h>
#endif
/* The size of `long', as computed by sizeof. */
#cmakedefine CURL_SIZEOF_LONG ${CURL_SIZEOF_LONG}
/* Integral data type used for curl_socklen_t. */
#cmakedefine CURL_TYPEOF_CURL_SOCKLEN_T ${CURL_TYPEOF_CURL_SOCKLEN_T}
/* on windows socklen_t is in here */
#ifdef _WIN32
# include <winsock2.h>
# include <ws2tcpip.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
/* Data type definition of curl_socklen_t. */
typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t;
/* The size of `curl_socklen_t', as computed by sizeof. */
#cmakedefine CURL_SIZEOF_CURL_SOCKLEN_T ${CURL_SIZEOF_CURL_SOCKLEN_T}
/* Signed integral data type used for curl_off_t. */
#cmakedefine CURL_TYPEOF_CURL_OFF_T ${CURL_TYPEOF_CURL_OFF_T}
/* Data type definition of curl_off_t. */
typedef CURL_TYPEOF_CURL_OFF_T curl_off_t;
/* curl_off_t formatting string directive without "%" conversion specifier. */
#cmakedefine CURL_FORMAT_CURL_OFF_T "${CURL_FORMAT_CURL_OFF_T}"
/* unsigned curl_off_t formatting string without "%" conversion specifier. */
#cmakedefine CURL_FORMAT_CURL_OFF_TU "${CURL_FORMAT_CURL_OFF_TU}"
/* curl_off_t formatting string directive with "%" conversion specifier. */
#cmakedefine CURL_FORMAT_OFF_T "${CURL_FORMAT_OFF_T}"
/* The size of `curl_off_t', as computed by sizeof. */
#cmakedefine CURL_SIZEOF_CURL_OFF_T ${CURL_SIZEOF_CURL_OFF_T}
/* curl_off_t constant suffix. */
#cmakedefine CURL_SUFFIX_CURL_OFF_T ${CURL_SUFFIX_CURL_OFF_T}
/* unsigned curl_off_t constant suffix. */
#cmakedefine CURL_SUFFIX_CURL_OFF_TU ${CURL_SUFFIX_CURL_OFF_TU}
#endif /* __CURL_CURLBUILD_H */

View file

@ -0,0 +1,190 @@
#ifndef __CURL_CURLBUILD_H
#define __CURL_CURLBUILD_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* ================================================================ */
/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* Nothing in this file is intended to be modified or adjusted by the
* curl library user nor by the curl library builder.
*
* If you think that something actually needs to be changed, adjusted
* or fixed in this file, then, report it on the libcurl development
* mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/
*
* This header file shall only export symbols which are 'curl' or 'CURL'
* prefixed, otherwise public name space would be polluted.
*
* NOTE 2:
* -------
*
* Right now you might be staring at file include/curl/curlbuild.h.in or
* at file include/curl/curlbuild.h, this is due to the following reason:
*
* On systems capable of running the configure script, the configure process
* will overwrite the distributed include/curl/curlbuild.h file with one that
* is suitable and specific to the library being configured and built, which
* is generated from the include/curl/curlbuild.h.in template file.
*
*/
/* ================================================================ */
/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */
/* ================================================================ */
#ifdef CURL_SIZEOF_LONG
#error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined
#endif
#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
#error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined
#endif
#ifdef CURL_SIZEOF_CURL_SOCKLEN_T
#error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined
#endif
#ifdef CURL_TYPEOF_CURL_OFF_T
#error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined
#endif
#ifdef CURL_FORMAT_CURL_OFF_T
#error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined
#endif
#ifdef CURL_FORMAT_CURL_OFF_TU
#error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined
#endif
#ifdef CURL_FORMAT_OFF_T
#error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined
#endif
#ifdef CURL_SIZEOF_CURL_OFF_T
#error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined
#endif
#ifdef CURL_SUFFIX_CURL_OFF_T
#error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined
#endif
#ifdef CURL_SUFFIX_CURL_OFF_TU
#error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined
#endif
/* ================================================================ */
/* EXTERNAL INTERFACE SETTINGS FOR CONFIGURE CAPABLE SYSTEMS ONLY */
/* ================================================================ */
/* Configure process defines this to 1 when it finds out that system */
/* header file ws2tcpip.h must be included by the external interface. */
#undef CURL_PULL_WS2TCPIP_H
#ifdef CURL_PULL_WS2TCPIP_H
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <winsock2.h>
# include <ws2tcpip.h>
#endif
/* Configure process defines this to 1 when it finds out that system */
/* header file sys/types.h must be included by the external interface. */
#undef CURL_PULL_SYS_TYPES_H
#ifdef CURL_PULL_SYS_TYPES_H
# include <sys/types.h>
#endif
/* Configure process defines this to 1 when it finds out that system */
/* header file stdint.h must be included by the external interface. */
#undef CURL_PULL_STDINT_H
#ifdef CURL_PULL_STDINT_H
# include <stdint.h>
#endif
/* Configure process defines this to 1 when it finds out that system */
/* header file inttypes.h must be included by the external interface. */
#undef CURL_PULL_INTTYPES_H
#ifdef CURL_PULL_INTTYPES_H
# include <inttypes.h>
#endif
/* Configure process defines this to 1 when it finds out that system */
/* header file sys/socket.h must be included by the external interface. */
#undef CURL_PULL_SYS_SOCKET_H
#ifdef CURL_PULL_SYS_SOCKET_H
# include <sys/socket.h>
#endif
/* The size of `long', as computed by sizeof. */
#undef CURL_SIZEOF_LONG
/* Integral data type used for curl_socklen_t. */
#undef CURL_TYPEOF_CURL_SOCKLEN_T
/* The size of `curl_socklen_t', as computed by sizeof. */
#undef CURL_SIZEOF_CURL_SOCKLEN_T
/* Data type definition of curl_socklen_t. */
typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t;
/* Signed integral data type used for curl_off_t. */
#undef CURL_TYPEOF_CURL_OFF_T
/* Data type definition of curl_off_t. */
typedef CURL_TYPEOF_CURL_OFF_T curl_off_t;
/* curl_off_t formatting string directive without "%" conversion specifier. */
#undef CURL_FORMAT_CURL_OFF_T
/* unsigned curl_off_t formatting string without "%" conversion specifier. */
#undef CURL_FORMAT_CURL_OFF_TU
/* curl_off_t formatting string directive with "%" conversion specifier. */
#undef CURL_FORMAT_OFF_T
/* The size of `curl_off_t', as computed by sizeof. */
#undef CURL_SIZEOF_CURL_OFF_T
/* curl_off_t constant suffix. */
#undef CURL_SUFFIX_CURL_OFF_T
/* unsigned curl_off_t constant suffix. */
#undef CURL_SUFFIX_CURL_OFF_TU
#endif /* __CURL_CURLBUILD_H */

View file

@ -0,0 +1,261 @@
#ifndef __CURL_CURLRULES_H
#define __CURL_CURLRULES_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* ================================================================ */
/* COMPILE TIME SANITY CHECKS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* All checks done in this file are intentionally placed in a public
* header file which is pulled by curl/curl.h when an application is
* being built using an already built libcurl library. Additionally
* this file is also included and used when building the library.
*
* If compilation fails on this file it is certainly sure that the
* problem is elsewhere. It could be a problem in the curlbuild.h
* header file, or simply that you are using different compilation
* settings than those used to build the library.
*
* Nothing in this file is intended to be modified or adjusted by the
* curl library user nor by the curl library builder.
*
* Do not deactivate any check, these are done to make sure that the
* library is properly built and used.
*
* You can find further help on the libcurl development mailing list:
* http://cool.haxx.se/mailman/listinfo/curl-library/
*
* NOTE 2
* ------
*
* Some of the following compile time checks are based on the fact
* that the dimension of a constant array can not be a negative one.
* In this way if the compile time verification fails, the compilation
* will fail issuing an error. The error description wording is compiler
* dependent but it will be quite similar to one of the following:
*
* "negative subscript or subscript is too large"
* "array must have at least one element"
* "-1 is an illegal array size"
* "size of array is negative"
*
* If you are building an application which tries to use an already
* built libcurl library and you are getting this kind of errors on
* this file, it is a clear indication that there is a mismatch between
* how the library was built and how you are trying to use it for your
* application. Your already compiled or binary library provider is the
* only one who can give you the details you need to properly use it.
*/
/*
* Verify that some macros are actually defined.
*/
#ifndef CURL_SIZEOF_LONG
# error "CURL_SIZEOF_LONG definition is missing!"
Error Compilation_aborted_CURL_SIZEOF_LONG_is_missing
#endif
#ifndef CURL_TYPEOF_CURL_SOCKLEN_T
# error "CURL_TYPEOF_CURL_SOCKLEN_T definition is missing!"
Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_is_missing
#endif
#ifndef CURL_SIZEOF_CURL_SOCKLEN_T
# error "CURL_SIZEOF_CURL_SOCKLEN_T definition is missing!"
Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_is_missing
#endif
#ifndef CURL_TYPEOF_CURL_OFF_T
# error "CURL_TYPEOF_CURL_OFF_T definition is missing!"
Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_is_missing
#endif
#ifndef CURL_FORMAT_CURL_OFF_T
# error "CURL_FORMAT_CURL_OFF_T definition is missing!"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_is_missing
#endif
#ifndef CURL_FORMAT_CURL_OFF_TU
# error "CURL_FORMAT_CURL_OFF_TU definition is missing!"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_is_missing
#endif
#ifndef CURL_FORMAT_OFF_T
# error "CURL_FORMAT_OFF_T definition is missing!"
Error Compilation_aborted_CURL_FORMAT_OFF_T_is_missing
#endif
#ifndef CURL_SIZEOF_CURL_OFF_T
# error "CURL_SIZEOF_CURL_OFF_T definition is missing!"
Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_is_missing
#endif
#ifndef CURL_SUFFIX_CURL_OFF_T
# error "CURL_SUFFIX_CURL_OFF_T definition is missing!"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_is_missing
#endif
#ifndef CURL_SUFFIX_CURL_OFF_TU
# error "CURL_SUFFIX_CURL_OFF_TU definition is missing!"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_is_missing
#endif
/*
* Macros private to this header file.
*/
#define CurlchkszEQ(t, s) sizeof(t) == s ? 1 : -1
#define CurlchkszGE(t1, t2) sizeof(t1) >= sizeof(t2) ? 1 : -1
/*
* Verify that the size previously defined and expected for long
* is the same as the one reported by sizeof() at compile time.
*/
typedef char
__curl_rule_01__
[CurlchkszEQ(long, CURL_SIZEOF_LONG)];
/*
* Verify that the size previously defined and expected for
* curl_off_t is actually the the same as the one reported
* by sizeof() at compile time.
*/
typedef char
__curl_rule_02__
[CurlchkszEQ(curl_off_t, CURL_SIZEOF_CURL_OFF_T)];
/*
* Verify at compile time that the size of curl_off_t as reported
* by sizeof() is greater or equal than the one reported for long
* for the current compilation.
*/
typedef char
__curl_rule_03__
[CurlchkszGE(curl_off_t, long)];
/*
* Verify that the size previously defined and expected for
* curl_socklen_t is actually the the same as the one reported
* by sizeof() at compile time.
*/
typedef char
__curl_rule_04__
[CurlchkszEQ(curl_socklen_t, CURL_SIZEOF_CURL_SOCKLEN_T)];
/*
* Verify at compile time that the size of curl_socklen_t as reported
* by sizeof() is greater or equal than the one reported for int for
* the current compilation.
*/
typedef char
__curl_rule_05__
[CurlchkszGE(curl_socklen_t, int)];
/* ================================================================ */
/* EXTERNALLY AND INTERNALLY VISIBLE DEFINITIONS */
/* ================================================================ */
/*
* CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow
* these to be visible and exported by the external libcurl interface API,
* while also making them visible to the library internals, simply including
* setup.h, without actually needing to include curl.h internally.
* If some day this section would grow big enough, all this should be moved
* to its own header file.
*/
/*
* Figure out if we can use the ## preprocessor operator, which is supported
* by ISO/ANSI C and C++. Some compilers support it without setting __STDC__
* or __cplusplus so we need to carefully check for them too.
*/
#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \
defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \
defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \
defined(__ILEC400__)
/* This compiler is believed to have an ISO compatible preprocessor */
#define CURL_ISOCPP
#else
/* This compiler is believed NOT to have an ISO compatible preprocessor */
#undef CURL_ISOCPP
#endif
/*
* Macros for minimum-width signed and unsigned curl_off_t integer constants.
*/
#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551)
# define __CURL_OFF_T_C_HLPR2(x) x
# define __CURL_OFF_T_C_HLPR1(x) __CURL_OFF_T_C_HLPR2(x)
# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \
__CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T)
# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \
__CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU)
#else
# ifdef CURL_ISOCPP
# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix
# else
# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix
# endif
# define __CURL_OFF_T_C_HLPR1(Val,Suffix) __CURL_OFF_T_C_HLPR2(Val,Suffix)
# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T)
# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU)
#endif
/*
* Get rid of macros private to this header file.
*/
#undef CurlchkszEQ
#undef CurlchkszGE
/*
* Get rid of macros not intended to exist beyond this point.
*/
#undef CURL_PULL_WS2TCPIP_H
#undef CURL_PULL_SYS_TYPES_H
#undef CURL_PULL_SYS_SOCKET_H
#undef CURL_PULL_STDINT_H
#undef CURL_PULL_INTTYPES_H
#undef CURL_TYPEOF_CURL_SOCKLEN_T
#undef CURL_TYPEOF_CURL_OFF_T
#ifdef CURL_NO_OLDIES
#undef CURL_FORMAT_OFF_T /* not required since 7.19.0 - obsoleted in 7.20.0 */
#endif
#endif /* __CURL_CURLRULES_H */

View file

@ -0,0 +1,69 @@
#ifndef __CURL_CURLVER_H
#define __CURL_CURLVER_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* This header file contains nothing but libcurl version info, generated by
a script at release-time. This was made its own header file in 7.11.2 */
/* This is the global package copyright */
#define LIBCURL_COPYRIGHT "1996 - 2011 Daniel Stenberg, <daniel@haxx.se>."
/* This is the version number of the libcurl package from which this header
file origins: */
#define LIBCURL_VERSION "7.21.7"
/* The numeric version number is also available "in parts" by using these
defines: */
#define LIBCURL_VERSION_MAJOR 7
#define LIBCURL_VERSION_MINOR 21
#define LIBCURL_VERSION_PATCH 7
/* This is the numeric version of the libcurl version number, meant for easier
parsing and comparions by programs. The LIBCURL_VERSION_NUM define will
always follow this syntax:
0xXXYYZZ
Where XX, YY and ZZ are the main version, release and patch numbers in
hexadecimal (using 8 bits each). All three numbers are always represented
using two digits. 1.2 would appear as "0x010200" while version 9.11.7
appears as "0x090b07".
This 6-digit (24 bits) hexadecimal number does not show pre-release number,
and it is always a greater number in a more recent release. It makes
comparisons with greater than and less than work.
*/
#define LIBCURL_VERSION_NUM 0x071507
/*
* This is the date and time when the full source package was created. The
* timestamp is not stored in git, as the timestamp is properly set in the
* tarballs by the maketgz script.
*
* The format of the date should follow this template:
*
* "Mon Feb 12 11:35:33 UTC 2007"
*/
#define LIBCURL_TIMESTAMP "Thu Jun 23 08:25:34 UTC 2011"
#endif /* __CURL_CURLVER_H */

View file

@ -0,0 +1,102 @@
#ifndef __CURL_EASY_H
#define __CURL_EASY_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2008, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
CURL_EXTERN CURL *curl_easy_init(void);
CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...);
CURL_EXTERN CURLcode curl_easy_perform(CURL *curl);
CURL_EXTERN void curl_easy_cleanup(CURL *curl);
/*
* NAME curl_easy_getinfo()
*
* DESCRIPTION
*
* Request internal information from the curl session with this function. The
* third argument MUST be a pointer to a long, a pointer to a char * or a
* pointer to a double (as the documentation describes elsewhere). The data
* pointed to will be filled in accordingly and can be relied upon only if the
* function returns CURLE_OK. This function is intended to get used *AFTER* a
* performed transfer, all results from this function are undefined until the
* transfer is completed.
*/
CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...);
/*
* NAME curl_easy_duphandle()
*
* DESCRIPTION
*
* Creates a new curl session handle with the same options set for the handle
* passed in. Duplicating a handle could only be a matter of cloning data and
* options, internal state info and things like persistent connections cannot
* be transferred. It is useful in multithreaded applications when you can run
* curl_easy_duphandle() for each new thread to avoid a series of identical
* curl_easy_setopt() invokes in every thread.
*/
CURL_EXTERN CURL* curl_easy_duphandle(CURL *curl);
/*
* NAME curl_easy_reset()
*
* DESCRIPTION
*
* Re-initializes a CURL handle to the default values. This puts back the
* handle to the same state as it was in when it was just created.
*
* It does keep: live connections, the Session ID cache, the DNS cache and the
* cookies.
*/
CURL_EXTERN void curl_easy_reset(CURL *curl);
/*
* NAME curl_easy_recv()
*
* DESCRIPTION
*
* Receives data from the connected socket. Use after successful
* curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
*/
CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen,
size_t *n);
/*
* NAME curl_easy_send()
*
* DESCRIPTION
*
* Sends data over the connected socket. Use after successful
* curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
*/
CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer,
size_t buflen, size_t *n);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,81 @@
#ifndef __CURL_MPRINTF_H
#define __CURL_MPRINTF_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2006, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include <stdarg.h>
#include <stdio.h> /* needed for FILE */
#include "curl.h"
#ifdef __cplusplus
extern "C" {
#endif
CURL_EXTERN int curl_mprintf(const char *format, ...);
CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...);
CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...);
CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength,
const char *format, ...);
CURL_EXTERN int curl_mvprintf(const char *format, va_list args);
CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args);
CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args);
CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength,
const char *format, va_list args);
CURL_EXTERN char *curl_maprintf(const char *format, ...);
CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args);
#ifdef _MPRINTF_REPLACE
# undef printf
# undef fprintf
# undef sprintf
# undef vsprintf
# undef snprintf
# undef vprintf
# undef vfprintf
# undef vsnprintf
# undef aprintf
# undef vaprintf
# define printf curl_mprintf
# define fprintf curl_mfprintf
#ifdef CURLDEBUG
/* When built with CURLDEBUG we define away the sprintf() functions since we
don't want internal code to be using them */
# define sprintf sprintf_was_used
# define vsprintf vsprintf_was_used
#else
# define sprintf curl_msprintf
# define vsprintf curl_mvsprintf
#endif
# define snprintf curl_msnprintf
# define vprintf curl_mvprintf
# define vfprintf curl_mvfprintf
# define vsnprintf curl_mvsnprintf
# define aprintf curl_maprintf
# define vaprintf curl_mvaprintf
#endif
#ifdef __cplusplus
}
#endif
#endif /* __CURL_MPRINTF_H */

View file

@ -0,0 +1,345 @@
#ifndef __CURL_MULTI_H
#define __CURL_MULTI_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2007, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
This is an "external" header file. Don't give away any internals here!
GOALS
o Enable a "pull" interface. The application that uses libcurl decides where
and when to ask libcurl to get/send data.
o Enable multiple simultaneous transfers in the same thread without making it
complicated for the application.
o Enable the application to select() on its own file descriptors and curl's
file descriptors simultaneous easily.
*/
/*
* This header file should not really need to include "curl.h" since curl.h
* itself includes this file and we expect user applications to do #include
* <curl/curl.h> without the need for especially including multi.h.
*
* For some reason we added this include here at one point, and rather than to
* break existing (wrongly written) libcurl applications, we leave it as-is
* but with this warning attached.
*/
#include "curl.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void CURLM;
typedef enum {
CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or
curl_multi_socket*() soon */
CURLM_OK,
CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */
CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */
CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */
CURLM_INTERNAL_ERROR, /* this is a libcurl bug */
CURLM_BAD_SOCKET, /* the passed in socket argument did not match */
CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */
CURLM_LAST
} CURLMcode;
/* just to make code nicer when using curl_multi_socket() you can now check
for CURLM_CALL_MULTI_SOCKET too in the same style it works for
curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */
#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM
typedef enum {
CURLMSG_NONE, /* first, not used */
CURLMSG_DONE, /* This easy handle has completed. 'result' contains
the CURLcode of the transfer */
CURLMSG_LAST /* last, not used */
} CURLMSG;
struct CURLMsg {
CURLMSG msg; /* what this message means */
CURL *easy_handle; /* the handle it concerns */
union {
void *whatever; /* message-specific data */
CURLcode result; /* return code for transfer */
} data;
};
typedef struct CURLMsg CURLMsg;
/*
* Name: curl_multi_init()
*
* Desc: inititalize multi-style curl usage
*
* Returns: a new CURLM handle to use in all 'curl_multi' functions.
*/
CURL_EXTERN CURLM *curl_multi_init(void);
/*
* Name: curl_multi_add_handle()
*
* Desc: add a standard curl handle to the multi stack
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle,
CURL *curl_handle);
/*
* Name: curl_multi_remove_handle()
*
* Desc: removes a curl handle from the multi stack again
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle,
CURL *curl_handle);
/*
* Name: curl_multi_fdset()
*
* Desc: Ask curl for its fd_set sets. The app can use these to select() or
* poll() on. We want curl_multi_perform() called as soon as one of
* them are ready.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle,
fd_set *read_fd_set,
fd_set *write_fd_set,
fd_set *exc_fd_set,
int *max_fd);
/*
* Name: curl_multi_perform()
*
* Desc: When the app thinks there's data available for curl it calls this
* function to read/write whatever there is right now. This returns
* as soon as the reads and writes are done. This function does not
* require that there actually is data available for reading or that
* data can be written, it can be called just in case. It returns
* the number of handles that still transfer data in the second
* argument's integer-pointer.
*
* Returns: CURLMcode type, general multi error code. *NOTE* that this only
* returns errors etc regarding the whole multi stack. There might
* still have occurred problems on invidual transfers even when this
* returns OK.
*/
CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle,
int *running_handles);
/*
* Name: curl_multi_cleanup()
*
* Desc: Cleans up and removes a whole multi stack. It does not free or
* touch any individual easy handles in any way. We need to define
* in what state those handles will be if this function is called
* in the middle of a transfer.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle);
/*
* Name: curl_multi_info_read()
*
* Desc: Ask the multi handle if there's any messages/informationals from
* the individual transfers. Messages include informationals such as
* error code from the transfer or just the fact that a transfer is
* completed. More details on these should be written down as well.
*
* Repeated calls to this function will return a new struct each
* time, until a special "end of msgs" struct is returned as a signal
* that there is no more to get at this point.
*
* The data the returned pointer points to will not survive calling
* curl_multi_cleanup().
*
* The 'CURLMsg' struct is meant to be very simple and only contain
* very basic informations. If more involved information is wanted,
* we will provide the particular "transfer handle" in that struct
* and that should/could/would be used in subsequent
* curl_easy_getinfo() calls (or similar). The point being that we
* must never expose complex structs to applications, as then we'll
* undoubtably get backwards compatibility problems in the future.
*
* Returns: A pointer to a filled-in struct, or NULL if it failed or ran out
* of structs. It also writes the number of messages left in the
* queue (after this read) in the integer the second argument points
* to.
*/
CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle,
int *msgs_in_queue);
/*
* Name: curl_multi_strerror()
*
* Desc: The curl_multi_strerror function may be used to turn a CURLMcode
* value into the equivalent human readable error string. This is
* useful for printing meaningful error messages.
*
* Returns: A pointer to a zero-terminated error message.
*/
CURL_EXTERN const char *curl_multi_strerror(CURLMcode);
/*
* Name: curl_multi_socket() and
* curl_multi_socket_all()
*
* Desc: An alternative version of curl_multi_perform() that allows the
* application to pass in one of the file descriptors that have been
* detected to have "action" on them and let libcurl perform.
* See man page for details.
*/
#define CURL_POLL_NONE 0
#define CURL_POLL_IN 1
#define CURL_POLL_OUT 2
#define CURL_POLL_INOUT 3
#define CURL_POLL_REMOVE 4
#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD
#define CURL_CSELECT_IN 0x01
#define CURL_CSELECT_OUT 0x02
#define CURL_CSELECT_ERR 0x04
typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */
curl_socket_t s, /* socket */
int what, /* see above */
void *userp, /* private callback
pointer */
void *socketp); /* private socket
pointer */
/*
* Name: curl_multi_timer_callback
*
* Desc: Called by libcurl whenever the library detects a change in the
* maximum number of milliseconds the app is allowed to wait before
* curl_multi_socket() or curl_multi_perform() must be called
* (to allow libcurl's timed events to take place).
*
* Returns: The callback should return zero.
*/
typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */
long timeout_ms, /* see above */
void *userp); /* private callback
pointer */
CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s,
int *running_handles);
CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle,
curl_socket_t s,
int ev_bitmask,
int *running_handles);
CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle,
int *running_handles);
#ifndef CURL_ALLOW_OLD_MULTI_SOCKET
/* This macro below was added in 7.16.3 to push users who recompile to use
the new curl_multi_socket_action() instead of the old curl_multi_socket()
*/
#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z)
#endif
/*
* Name: curl_multi_timeout()
*
* Desc: Returns the maximum number of milliseconds the app is allowed to
* wait before curl_multi_socket() or curl_multi_perform() must be
* called (to allow libcurl's timed events to take place).
*
* Returns: CURLM error code.
*/
CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle,
long *milliseconds);
#undef CINIT /* re-using the same name as in curl.h */
#ifdef CURL_ISOCPP
#define CINIT(name,type,num) CURLMOPT_ ## name = CURLOPTTYPE_ ## type + num
#else
/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */
#define LONG CURLOPTTYPE_LONG
#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT
#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT
#define OFF_T CURLOPTTYPE_OFF_T
#define CINIT(name,type,number) CURLMOPT_/**/name = type + number
#endif
typedef enum {
/* This is the socket callback function pointer */
CINIT(SOCKETFUNCTION, FUNCTIONPOINT, 1),
/* This is the argument passed to the socket callback */
CINIT(SOCKETDATA, OBJECTPOINT, 2),
/* set to 1 to enable pipelining for this multi handle */
CINIT(PIPELINING, LONG, 3),
/* This is the timer callback function pointer */
CINIT(TIMERFUNCTION, FUNCTIONPOINT, 4),
/* This is the argument passed to the timer callback */
CINIT(TIMERDATA, OBJECTPOINT, 5),
/* maximum number of entries in the connection cache */
CINIT(MAXCONNECTS, LONG, 6),
CURLMOPT_LASTENTRY /* the last unused */
} CURLMoption;
/*
* Name: curl_multi_setopt()
*
* Desc: Sets options for the multi handle.
*
* Returns: CURLM error code.
*/
CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle,
CURLMoption option, ...);
/*
* Name: curl_multi_assign()
*
* Desc: This function sets an association in the multi handle between the
* given socket and a private pointer of the application. This is
* (only) useful for curl_multi_socket uses.
*
* Returns: CURLM error code.
*/
CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle,
curl_socket_t sockfd, void *sockp);
#ifdef __cplusplus
} /* end of extern "C" */
#endif
#endif

Some files were not shown because too many files have changed in this diff Show more