Changeset - ab1a0140c26b
[Not reviewed]
CMakeLists.txt
Show inline comments
 
@@ -10,80 +10,83 @@ set(CMAKE_MODULE_PATH "cmake_modules")
 
set(cppunit_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(cppunit)
 

	
 
set(sqlite3_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(sqlite3)
 

	
 
set(mysql_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(mysql)
 

	
 
set(purple_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(purple)
 

	
 
set(glib_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(glib)
 

	
 
if (NOT WIN32)
 
	set(popt_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
	find_package(popt)
 
endif()
 

	
 
set(event_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(event)
 

	
 
set(Swiften_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(Swiften REQUIRED)
 
find_package(Swiften)
 

	
 
set(openssl_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(openssl REQUIRED)
 
find_package(openssl)
 

	
 
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)
 
message( STATUS "Found Boost: ${Boost_LIBRARIES}, ${Boost_INCLUDE_DIR}")
 

	
 
set(Protobuf_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(Protobuf REQUIRED)
 

	
 
set(Communi_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(Communi)
 

	
 
set(log4cxx_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(log4cxx)
 

	
 
set(event_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(event)
 

	
 
set(pqxx_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(pqxx)
 

	
 
set(dbus_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(dbus)
 

	
 
set(yahoo2_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(yahoo2)
 

	
 
find_package(Doxygen)
 

	
 
INCLUDE(FindQt4)
 
FIND_PACKAGE(Qt4 COMPONENTS QtCore QtNetwork)
 

	
 
# ADD_DEFINITIONS(${SWIFTEN_CFLAGS})
 
ADD_DEFINITIONS(-DSUPPORT_LEGACY_CAPS)
 
ADD_DEFINITIONS(-DBOOST_FILESYSTEM_VERSION=2)
 

	
 
message("  Supported features")
 
message("-----------------------")
 

	
 
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
 
						OUTPUT_VARIABLE GIT_REVISION
 
						OUTPUT_STRIP_TRAILING_WHITESPACE
 
		)
 
		set(SPECTRUM_VERSION 2.0.0-beta-git-${GIT_REVISION})
 
		ADD_DEFINITIONS(-DSPECTRUM_VERSION="${SPECTRUM_VERSION}")
 
	else (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)
 
		set(SPECTRUM_VERSION 2.0.0-alpha)
 
@@ -141,48 +144,56 @@ if (PROTOBUF_FOUND)
 
	else()
 
		message("  libev eventloop : no (install libev-devel)")
 
	endif()
 

	
 
	if(IRC_FOUND)
 
		ADD_DEFINITIONS(-DCOMMUNI_SHARED)
 
		message("IRC plugin        : yes")
 
		include_directories(${QT_QTNETWORK_INCLUDE_DIR})
 
		include_directories(${IRC_INCLUDE_DIR})
 
		include(${QT_USE_FILE})
 
	else()
 
		message("IRC plugin        : no (install libCommuni and libprotobuf-dev)")
 
	endif()
 

	
 
	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()
 

	
 
#	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()
 

	
 
else()
 
	message("Network plugins   : no (install libprotobuf-dev)")
 
	message("Libpurple plugin  : no (install libpurple and libprotobuf-dev)")
 
	message("IRC plugin        : no (install libircclient-qt and libprotobuf-dev)")
 
	message("Frotz plugin      : no (install libprotobuf-dev)")
 
	message("SMSTools3 plugin  : no (install libprotobuf-dev)")
 
endif()
 

	
 
if (LOG4CXX_FOUND)
 
	message("Log4cxx           : yes")
 
	include_directories(${LOG4CXX_INCLUDE_DIR})
 
	ADD_DEFINITIONS(-DWITH_LOG4CXX)
 
else()
 
	set(LOG4CXX_LIBRARIES "")
 
	message("Log4cxx           : no (install log4cxx-devel)")
 
endif()
 

	
 
if (WIN32)
 
ADD_DEFINITIONS(-D_WIN32_WINNT=0x501)
 
ADD_DEFINITIONS(-DWIN32_LEAN_AND_MEAN)
 
endif()
 

	
 
if(CMAKE_BUILD_TYPE MATCHES Debug)
 
if (CMAKE_COMPILER_IS_GNUCXX)
ChangeLog
Show inline comments
 
Version 2.0.0-beta3 (2012-XX-XX):
 
	General:
 
	* Log errors related to backend spawning (Show proper log message for
 
	  example when path to backend binary is not found).
 
	* Update buddies in database only when it's needed and do not execute
 
	  useless database statements.
 
	* Send roster changes also when buddy's group change.
 
	* Fixed bug when transport contact we in all groups.
 
	* Answer to disco#info IQ with proper node (#206).
 
	* Set SQLite3 as default database backend.
 
	* Fixed disconnecting from server caused by sending VCard response
 
	  with bad "from" attribute.
 
	* Added Munin plugin (Thanks to Askovpen).
 
	* Added support for more admin_jid JIDs (Thanks to Askovpen).
 
	* Fixed allowed_servers option.
 

	
 
	Libpurple:
 
	* prpl-gg: Fetch the contact list properly (#252).
 

	
 
	Skype:
 
	* Log more errors.
 

	
 
	Backend API:
 
	* Added Python NetworkPlugin class, so it is now easier to write backends
 
	  in Python (Thanks to Sarang).
 

	
 
Version 2.0.0-beta2 (2012-03-28):
 
	General:
 
	* Fixed bug when Roster Item Exchange and subscribe stanzas were sent
 
	  repeatedly.
 
	* Backends related logs now contain the backend PID.
 
	* Fixed username_mask setting.
 
	* Added new fields into statistics (backends_crashed, messages related
 
	  stats).
 
	* Chatstates are now not counted as incoming messages in stats.
 
	* Log4cxx is now optional dependency. Without Log4cxx, Spectrum 2 logs
 
	  to standard output.
 
	* Fixed crash when Log4cxx configuration file didn't exist.
 
	* Admin can now see "Admin" contact in server-mode.
 

	
 
	libpurple:
 
	* Added initial support for MUC for prpl-jabber protocol.
 

	
 
	LibCommuni IRC backend:
 
	* Fixed sending/receiving UTF8 messages.
 
	* Using the [registration] auto_register=1 config option, users don't
 
	  have to register manually when connecting IRC network.
 

	
 
	Skype:
 
	* Memory usage statistic now includes the Skype client.
backends/CMakeLists.txt
Show inline comments
 
if (PROTOBUF_FOUND)
 
	if ( PURPLE_LIBRARY AND PURPLE_INCLUDE_DIR )
 
		ADD_SUBDIRECTORY(libpurple)
 
	endif()
 

	
 
	if (IRC_FOUND)
 
		ADD_SUBDIRECTORY(libcommuni)
 
	endif()
 

	
 
	ADD_SUBDIRECTORY(smstools3)
 

	
 
	ADD_SUBDIRECTORY(swiften)
 

	
 
# 	if(YAHOO2_FOUND)
 
		ADD_SUBDIRECTORY(libyahoo2)
 
# 	endif()
 

	
 
	ADD_SUBDIRECTORY(template)
 
	
 
	ADD_SUBDIRECTORY(twitter)
 

	
 
if (NOT WIN32)
 
	ADD_SUBDIRECTORY(frotz)
 
	if (${LIBDBUSGLIB_FOUND})
 
		ADD_SUBDIRECTORY(skype)
 
	endif()
 
endif()
 

	
 
endif()
backends/libpurple/gen_dynamic_purple.py
Show inline comments
 
new file 100644
 
import sys
 
import os
 

	
 
# intialize for methods used in libpurple macros
 
methods = ["purple_connection_get_state(", "purple_conversation_get_im_data(",
 
			"purple_conversation_get_chat_data(", "purple_blist_node_get_type("]
 
macros = ["PURPLE_CONV_IM", "PURPLE_CONV_CHAT", "PURPLE_BLIST_NODE_IS_BUDDY", "PURPLE_CONNECTION_IS_CONNECTED"]
 
definitions = []
 

	
 
if len(sys.argv) != 2:
 
	print "Usage:", sys.argv[0], "<path_to_libpurple_dir_containing_libpurple_headers>"
 
	sys.exit(1)
 

	
 

	
 
def handle_file(cpp):
 
	global methods
 
	global macros
 
	sys.stdout.write("getting used methods in " + cpp + ": ")
 
	sys.stdout.flush()
 

	
 
	counter = 0
 

	
 
	new_file = ""
 
	f = open(cpp, "r")
 
	for line in f.readlines():
 
		new_line = ""
 
		index = 0
 
		while index < len(line):
 
			new_line += line[index]
 
			if line[index:].startswith("purple_") or line[index:].startswith("wpurple_") or line[index:].startswith("serv_"):
 
				if line[index:].find("=") != -1 and line[index:].find("=") < line[index:].find("("):
 
					index += 1
 
					continue
 
				if line[index-1] == "_" or line[index:].find("(") == -1 or line[index:].startswith("purple_commands_init") or line[index:].startswith("serv_addr"):
 
					index += 1
 
					continue
 
				m = line[index:line[index:].find("(")+index]
 
				index += len(m)
 
				if m.find("_wrapped") != -1:
 
					new_line += m[1:] + "("
 
					m = m.replace("_wrapped", "")
 
				else:
 
					new_line += m[1:] + "_wrapped("
 
				if not m + "(" in methods and len(m) != 0:
 
					methods += [m + "("]
 
					counter += 1
 
			index += 1
 

	
 
		for x in macros:
 
			if new_line.find(x + "_WRAPPED") == -1:
 
				new_line = new_line.replace(x, x + "_WRAPPED")
 
		new_file += new_line
 
	f.close()
 

	
 
	print counter, "new methods found"
 
	return new_file
 

	
 
def handle_header(header, method):
 
	global definitions
 

	
 
	f = open(os.path.join(sys.argv[1], header), "r")
 

	
 
	lines = f.readlines()
 
	for i in range(len(lines)):
 
		line = lines[i]
 
		if line.find(method) != -1:
 
			if line.startswith(method):
 
				line = lines[i-1][:-1] + line
 
			m = line[:-1]
 
			l = unicode(m).strip()
 
			if l.endswith(")"):
 
				continue
 

	
 
			if m.find("/*") > m.find(";"):
 
				m = m[:m.find("/*")]
 
				m.rstrip()
 
				if len(m) != 0:
 
					while m[-1] == " ":
 
						m = m[:-1]
 

	
 
			index = i;
 
			while not m.endswith(";"):
 
				index += 1
 
				m += " " + lines[index][:-1].lstrip()
 

	
 
			l = unicode(m).strip()
 
			if (l.startswith("#") or l.startswith("*") or l.startswith("/*") or l.count("***") != 0 or l.count("&&") != 0
 
				or l.endswith(")")):
 
				continue;
 

	
 
			m = m.replace("G_GNUC_NULL_TERMINATE", "")
 

	
 
			if not m in definitions:
 
				print "found", method[:-1], "in", header
 
				definitions += [m]
 
			break
 
	f.close()
 

	
 
def get_raw_args(d):
 
	return d[d.find("(")+1:-2]
 

	
 
def get_args(d):
 
	x = d[d.find("(")+1:-2]
 
	x = x.split(",")
 

	
 
	args = []
 
	for arg in x:
 
		y = arg.split(" ")
 
		if len(y) == 1:
 
			continue
 
		args += [y[-1].replace("*", "")]
 

	
 
	return args
 

	
 
def get_name(d):
 
	x = d[:d.find("(")+1].lstrip()
 
	if x.find("wpurple_") != -1:
 
		return x[x.find("wpurple_"):]
 
	if x.find("serv_") != -1:
 
		return x[x.find("serv_"):]
 
	return x[x.find("purple_"):]
 

	
 
def get_rtype(d):
 
	if d.find("wpurple_") != -1:
 
		return d[:d.find("wpurple_")].lstrip()
 
	if d.find("serv_") != -1:
 
		return d[:d.find("serv_")].lstrip()
 
	return d[:d.find("purple_")].lstrip()
 

	
 
def output():
 
	global definitions
 

	
 
	header = open("purple_defs.h", "w")
 
	print >> header, "#pragma once"
 
	print >> header, "#ifdef WIN32"
 

	
 
	print >> header, """
 
#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)
 
"""
 

	
 
	for d in definitions:
 
		#typedef void (_cdecl * purple_util_set_user_wrapped_func)(const char *dir);
 
		print >> header, "typedef", get_rtype(d), "(_cdecl *", get_name(d)[:-1] + "_wrapped_fnc)(" + get_raw_args(d) + ");"
 
		#extern purple_util_set_user_wrapped_func purple_util_set_user_wrapped;
 
		print >> header, "extern", get_name(d)[:-1] + "_wrapped_fnc", get_name(d)[:-1] + "_wrapped;"
 
		print >> header, ""
 

	
 
	print >> header, ""
 
	print >> header, "#else"
 
	print >> header, ""
 

	
 
	print >> header, """
 
#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	
 
"""
 

	
 
	for d in definitions:
 
		#define purple_util_set_user_wrapped purple_util_set_user
 
		print >> header, "#define", get_name(d)[:-1] + "_wrapped", get_name(d)[:-1]
 
			
 
	print >> header, "#endif"
 
	print >> header, ""
 
	print >> header, "bool resolvePurpleFunctions();"
 
	print >> header, ""
 

	
 

	
 
	cpp = open("purple_defs.cpp", "w")
 
	print >> cpp, "#include \"purple_defs.h\""
 
	print >> cpp, ""
 
	print >> cpp, "#ifdef WIN32"
 
	print >> cpp, "static HMODULE f_hPurple = NULL;"
 
	for d in definitions:
 
		#purple_util_set_user_wrapped_fnc purple_util_set_user_wrapped = NULL;
 
		print >> cpp, get_name(d)[:-1] + "_wrapped_fnc", get_name(d)[:-1] + "_wrapped = NULL;"
 

	
 
	print >> cpp, "#endif"
 

	
 
	print >> cpp, "bool resolvePurpleFunctions() {"
 
	print >> cpp, "#ifdef WIN32"
 
	print >> cpp, "\tf_hPurple = LoadLibrary(\"libpurple.dll\");"
 
	print >> cpp, "\tif (!f_hPurple)"
 
	print >> cpp, "\t\t\treturn false;"
 
	for d in definitions:
 
		#purple_util_set_user_wrapped = (purple_util_set_user_wrapped_func)GetProcAddress(f_hPurple, "purple_util_set_user_dir");
 
		print >> cpp, "\t" + get_name(d)[:-1] + "_wrapped = (" + get_name(d)[:-1] + "_wrapped_fnc)GetProcAddress(f_hPurple, \"" + get_name(d)[:-1] + "\");"
 
		#if (!purple_util_set_user_wrapped)
 
		print >> cpp, "\tif (!" + get_name(d)[:-1] + "_wrapped)"
 
		print >> cpp, "\t\treturn false;"
 
		print >> cpp, ""
 
	print >> cpp, "#endif"
 

	
 
	print >> cpp, "\treturn true;"
 
	print >> cpp, "}"
 
	print >> cpp, ""
 

	
 
	cpp.close()
 
	header.close()
 
		
 

	
 
for f in os.listdir("."):
 
	if not f.endswith(".cpp") or f.startswith("purple_defs"):
 
		continue
 
	new_file = handle_file(f)
 

	
 
	print "updating", f
 
	fd = open(f, "w")
 
	fd.write(new_file)
 
	fd.close()
 

	
 
for f in os.listdir(sys.argv[1]):
 
	if not f.endswith(".h"):
 
		continue
 
	for m in methods:
 
		handle_header(f, m)
 

	
 
sys.argv[1] = sys.argv[1] + "/win32"
 
for f in os.listdir(sys.argv[1]):
 
	if not f.endswith(".h"):
 
		continue
 
	for m in methods:
 
		handle_header(f, m)
 

	
 
for m in methods:
 
	found = False
 
	for d in definitions:
 
		if d.find(m[:-1]) != -1:
 
			found = True
 
			break
 
	if not found:
 
		print "NOT FOUND:", m
 

	
 
output()
backends/libpurple/geventloop.cpp
Show inline comments
 
@@ -7,48 +7,50 @@
 
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#include "geventloop.h"
 
#ifdef _WIN32
 
#include "win32/win32dep.h"
 
#undef read
 
#undef write
 
#endif
 
#ifdef WITH_LIBEVENT
 
#include "event.h"
 
#endif
 

	
 
#include "purple_defs.h"
 

	
 
#include "transport/logging.h"
 

	
 
DEFINE_LOGGER(logger, "EventLoop");
 

	
 
typedef struct _PurpleIOClosure {
 
	PurpleInputFunction function;
 
	guint result;
 
	gpointer data;
 
#ifdef WITH_LIBEVENT
 
	GSourceFunc function2;
 
	struct timeval timeout;
 
	struct event evfifo;
 
#endif
 
} PurpleIOClosure;
 

	
 
static gboolean io_invoke(GIOChannel *source,
 
										GIOCondition condition,
 
										gpointer data)
 
{
 
	PurpleIOClosure *closure = (PurpleIOClosure* )data;
 
	PurpleInputCondition purple_cond = (PurpleInputCondition)0;
 

	
 
	int tmp = 0;
 
	if (condition & READ_COND)
backends/libpurple/main.cpp
Show inline comments
 
@@ -6,69 +6,86 @@
 
#include <iostream>
 

	
 
#include "transport/networkplugin.h"
 
#include "transport/logging.h"
 
#include "transport/config.h"
 
#include "transport/logging.h"
 
#include "geventloop.h"
 

	
 
// #include "valgrind/memcheck.h"
 
#include "malloc.h"
 
#include <algorithm>
 
#include "errno.h"
 

	
 
#ifdef WITH_LIBEVENT
 
#include <event.h>
 
#endif
 

	
 
#ifdef WIN32
 
#include "win32/win32dep.h"
 
#define ssize_t SSIZE_T
 
#include <process.h>
 
#define getpid _getpid
 
#endif
 

	
 
#include "purple_defs.h"
 

	
 
DEFINE_LOGGER(logger_libpurple, "libpurple");
 
DEFINE_LOGGER(logger, "backend");
 

	
 
int main_socket;
 
static int writeInput;
 

	
 
using namespace Transport;
 

	
 
template <class T> T fromString(const std::string &str) {
 
	T i;
 
	std::istringstream os(str);
 
	os >> i;
 
	return i;
 
}
 

	
 
template <class T> std::string stringOf(T object) {
 
	std::ostringstream os;
 
	os << object;
 
	return (os.str());
 
}
 

	
 
static std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
 
    std::stringstream ss(s);
 
    std::string item;
 
    while(std::getline(ss, item, delim)) {
 
        elems.push_back(item);
 
    }
 
    return elems;
 
}
 

	
 

	
 
static std::vector<std::string> split(const std::string &s, char delim) {
 
    std::vector<std::string> elems;
 
    return split(s, delim, elems);
 
}
 

	
 
static void transportDataReceived(gpointer data, gint source, PurpleInputCondition cond);
 

	
 
class SpectrumNetworkPlugin;
 

	
 
GKeyFile *keyfile;
 
SpectrumNetworkPlugin *np;
 

	
 
static std::string replaceAll(
 
  std::string result,
 
  const std::string& replaceWhat,
 
  const std::string& replaceWithWhat)
 
{
 
  while(1)
 
  {
 
	const int pos = result.find(replaceWhat);
 
	if (pos==-1) break;
 
	result.replace(pos,replaceWhat.size(),replaceWithWhat);
 
  }
 
  return result;
 
}
 

	
 
static std::string KEYFILE_STRING(const std::string &cat, const std::string &key, const std::string &def = "") {
 
	gchar *str = g_key_file_get_string(keyfile, cat.c_str(), key.c_str(), 0);
 
	if (!str) {
 
@@ -266,48 +283,66 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
 
						case PURPLE_PREF_BOOLEAN:
 
							purple_account_set_bool(account, key.c_str(), fromString<bool>(KEYFILE_STRING("purple", key)));
 
							break;
 

	
 
						case PURPLE_PREF_INT:
 
							purple_account_set_int(account, key.c_str(), fromString<int>(KEYFILE_STRING("purple", key)));
 
							break;
 

	
 
						case PURPLE_PREF_STRING:
 
						case PURPLE_PREF_STRING_LIST:
 
							purple_account_set_string(account, key.c_str(), KEYFILE_STRING("purple", key).c_str());
 
							break;
 
						default:
 
							continue;
 
					}
 
					break;
 
				}
 

	
 
				if (!found) {
 
					purple_account_set_string(account, key.c_str(), KEYFILE_STRING("purple", key).c_str());
 
				}
 
				i++;
 
			}
 
			g_strfreev (keys);
 

	
 
			char* contents;
 
			gsize length;
 
			gboolean ret = g_file_get_contents ("gfire.cfg", &contents, &length, NULL);
 
			if (ret) {
 
				purple_account_set_int(account, "version", fromString<int>(std::string(contents, length)));
 
			}
 

	
 

	
 
			if (KEYFILE_STRING("service", "protocol") == "prpl-novell") {
 
				std::string username(purple_account_get_username(account));
 
				std::vector <std::string> u = split(username, '@');
 
				purple_account_set_username(account, (const char*) u.front().c_str());
 
				std::vector <std::string> s = split(u.back(), ':'); 
 
				purple_account_set_string(account, "server", s.front().c_str());
 
				purple_account_set_int(account, "port", atoi(s.back().c_str()));  
 
			}
 

	
 
		}
 

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
			PurpleAccount *account = NULL;
 

	
 
			std::string name;
 
			std::string protocol;
 
			getProtocolAndName(legacyName, name, protocol);
 

	
 
			if (password.empty()) {
 
				LOG4CXX_INFO(logger,  name.c_str() << ": Empty password");
 
				np->handleDisconnected(user, 0, "Empty password.");
 
				return;
 
			}
 

	
 
			if (!purple_find_prpl(protocol.c_str())) {
 
				LOG4CXX_INFO(logger,  name.c_str() << ": Invalid protocol '" << protocol << "'");
 
				np->handleDisconnected(user, 0, "Invalid protocol " + protocol);
 
				return;
 
			}
 

	
 
			if (purple_accounts_find(name.c_str(), protocol.c_str()) != NULL) {
 
				LOG4CXX_INFO(logger, "Using previously created account with name '" << name.c_str() << "' and protocol '" << protocol << "'");
 
				account = purple_accounts_find(name.c_str(), protocol.c_str());
 
@@ -325,48 +360,52 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
 
			setDefaultAvatar(account, legacyName);
 

	
 
			purple_account_set_password(account, password.c_str());
 
			purple_account_set_bool(account, "custom_smileys", FALSE);
 
			purple_account_set_bool(account, "direct_connect", FALSE);
 

	
 
			setDefaultAccountOptions(account);
 

	
 
			// Enable account + privacy lists
 
			purple_account_set_enabled(account, "spectrum", TRUE);
 
			if (KEYFILE_BOOL("service", "enable_privacy_lists")) {
 
				purple_account_set_privacy_type(account, PURPLE_PRIVACY_DENY_USERS);
 
			}
 

	
 
			// Set the status
 
			const PurpleStatusType *status_type = purple_account_get_status_type_with_primitive(account, PURPLE_STATUS_AVAILABLE);
 
			if (status_type != NULL) {
 
				purple_account_set_status(account, purple_status_type_get_id(status_type), TRUE, NULL);
 
			}
 
		}
 

	
 
		void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
 
			PurpleAccount *account = m_sessions[user];
 
			if (account) {
 
				if (purple_account_get_int(account, "version", 0) != 0) {
 
					std::string data = stringOf(purple_account_get_int(account, "version", 0));
 
					g_file_set_contents ("gfire.cfg", data.c_str(), data.size(), NULL);
 
				}
 
// 				VALGRIND_DO_LEAK_CHECK;
 
				m_sessions.erase(user);
 
				purple_account_disconnect(account);
 
				purple_account_set_enabled(account, "spectrum", FALSE);
 

	
 
				g_free(account->ui_data);
 
				account->ui_data = NULL;
 
				m_accounts.erase(account);
 

	
 
				purple_accounts_delete(account);
 
#ifndef WIN32
 
				malloc_trim(0);
 
#endif
 
// 				VALGRIND_DO_LEAK_CHECK;
 
			}
 
		}
 

	
 
		void handleStatusChangeRequest(const std::string &user, int status, const std::string &statusMessage) {
 
			PurpleAccount *account = m_sessions[user];
 
			if (account) {
 
				int st;
 
				switch(status) {
 
					case pbnetwork::STATUS_AWAY: {
 
						st = PURPLE_STATUS_AWAY;
 
@@ -632,49 +671,53 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
 
			if (xfer) {
 
				m_unhandledXfers.erase(user + fileName + buddyName);
 
				purple_xfer_request_denied(xfer);
 
			}
 
		}
 

	
 
		void handleFTPauseRequest(unsigned long ftID) {
 
			PurpleXfer *xfer = m_xfers[ftID];
 
			if (!xfer)
 
				return;
 
			FTData *ftData = (FTData *) xfer->ui_data;
 
			ftData->paused = true;
 
		}
 

	
 
		void handleFTContinueRequest(unsigned long ftID) {
 
			PurpleXfer *xfer = m_xfers[ftID];
 
			if (!xfer)
 
				return;
 
			FTData *ftData = (FTData *) xfer->ui_data;
 
			ftData->paused = false;
 
			purple_xfer_ui_ready(xfer);
 
		}
 

	
 
		void sendData(const std::string &string) {
 
#ifdef WIN32
 
			::send(main_socket, string.c_str(), string.size(), 0);
 
#else
 
			write(main_socket, string.c_str(), string.size());
 
#endif
 
			if (writeInput == 0)
 
				writeInput = purple_input_add(main_socket, PURPLE_INPUT_WRITE, &transportDataReceived, NULL);
 
		}
 

	
 
		void readyForData() {
 
			if (m_waitingXfers.empty())
 
				return;
 
			std::vector<PurpleXfer *> tmp;
 
			tmp.swap(m_waitingXfers);
 

	
 
			for (std::vector<PurpleXfer *>::const_iterator it = tmp.begin(); it != tmp.end(); it++) {
 
				FTData *ftData = (FTData *) (*it)->ui_data;
 
				if (ftData->timer == 0) {
 
					ftData->timer = purple_timeout_add(1, ft_ui_ready, *it);
 
				}
 
// 				purple_xfer_ui_ready(xfer);
 
			}
 
		}
 

	
 
		std::map<std::string, PurpleAccount *> m_sessions;
 
		std::map<PurpleAccount *, std::string> m_accounts;
 
		std::map<std::string, unsigned int> m_vcards;
 
		std::map<std::string, authRequest *> m_authRequests;
 
		std::map<unsigned long, PurpleXfer *> m_xfers;
 
@@ -768,49 +811,50 @@ static std::vector<std::string> getGroups(PurpleBuddy *m_buddy) {
 
		GSList *buddies = purple_find_buddies(purple_buddy_get_account(m_buddy), purple_buddy_get_name(m_buddy));
 
		while(buddies) {
 
			PurpleGroup *g = purple_buddy_get_group((PurpleBuddy *) buddies->data);
 
			buddies = g_slist_delete_link(buddies, buddies);
 

	
 
			if(g && purple_group_get_name(g)) {
 
				groups.push_back(purple_group_get_name(g));
 
			}
 
		}
 
	}
 

	
 
	if (groups.empty()) {
 
		groups.push_back("Buddies");
 
	}
 

	
 
	return groups;
 
}
 

	
 
static void buddyListNewNode(PurpleBlistNode *node) {
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY(node))
 
		return;
 
	PurpleBuddy *buddy = (PurpleBuddy *) node;
 
	PurpleAccount *account = purple_buddy_get_account(buddy);
 

	
 
	LOG4CXX_INFO(logger, "Buddy updated " << np->m_accounts[account] << " " << purple_buddy_get_name(buddy) << " " << getAlias(buddy));
 
	std::vector<std::string> groups = getGroups(buddy);
 
	LOG4CXX_INFO(logger, "Buddy updated " << np->m_accounts[account] << " " << purple_buddy_get_name(buddy) << " " << getAlias(buddy) << " group (" << groups.size() << ")=" << groups[0]);
 

	
 
	// Status
 
	pbnetwork::StatusType status = pbnetwork::STATUS_NONE;
 
	std::string message;
 
	getStatus(buddy, status, message);
 

	
 
	// Tooltip
 
	PurplePlugin *prpl = purple_find_prpl(purple_account_get_protocol_id(account));
 
	PurplePluginProtocolInfo *prpl_info = PURPLE_PLUGIN_PROTOCOL_INFO(prpl);
 

	
 
	bool blocked = false;
 
	if (KEYFILE_BOOL("service", "enable_privacy_lists")) {
 
		if (prpl_info && prpl_info->tooltip_text) {
 
			PurpleNotifyUserInfo *user_info = purple_notify_user_info_new();
 
			prpl_info->tooltip_text(buddy, user_info, true);
 
			GList *entries = purple_notify_user_info_get_entries(user_info);
 

	
 
			while (entries) {
 
				PurpleNotifyUserInfoEntry *entry = (PurpleNotifyUserInfoEntry *)(entries->data);
 
				if (purple_notify_user_info_entry_get_label(entry) && purple_notify_user_info_entry_get_value(entry)) {
 
					std::string label = purple_notify_user_info_entry_get_label(entry);
 
					if (label == "Blocked" ) {
 
						if (std::string(purple_notify_user_info_entry_get_value(entry)) == "Yes") {
 
							blocked = true;
 
@@ -1403,48 +1447,50 @@ spectrum_glib_log_handler(const gchar *domain,
 
		message.push_back(' ');
 
		message.append(new_msg);
 

	
 
		LOG4CXX_ERROR(logger, message);
 
		g_free(new_msg);
 
	}
 

	
 
	g_free(new_domain);
 
}
 

	
 
static void
 
debug_init(void)
 
{
 
#define REGISTER_G_LOG_HANDLER(name) \
 
	g_log_set_handler((name), \
 
		(GLogLevelFlags)(G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL \
 
										  | G_LOG_FLAG_RECURSION), \
 
					  spectrum_glib_log_handler, NULL)
 

	
 
	REGISTER_G_LOG_HANDLER(NULL);
 
	REGISTER_G_LOG_HANDLER("GLib");
 
	REGISTER_G_LOG_HANDLER("GModule");
 
	REGISTER_G_LOG_HANDLER("GLib-GObject");
 
	REGISTER_G_LOG_HANDLER("GThread");
 
	REGISTER_G_LOG_HANDLER("GConf");
 
	
 

	
 
#undef REGISTER_G_LOD_HANDLER
 
}
 

	
 
static PurpleCoreUiOps coreUiOps =
 
{
 
	NULL,
 
	debug_init,
 
	transport_core_ui_init,
 
	NULL,
 
	spectrum_ui_get_info,
 
	NULL,
 
	NULL,
 
	NULL
 
};
 

	
 
static void signed_on(PurpleConnection *gc, gpointer unused) {
 
	PurpleAccount *account = purple_connection_get_account(gc);
 
	np->handleConnected(np->m_accounts[account]);
 
#ifndef WIN32
 
	// force returning of memory chunks allocated by libxml2 to kernel
 
	malloc_trim(0);
 
#endif
 

	
 
@@ -1493,48 +1539,55 @@ static void buddyTyped(PurpleAccount *account, const char *who, gpointer null) {
 
	if (pos != std::string::npos)
 
		w.erase((int) pos, w.length() - (int) pos);
 
	np->handleBuddyTyped(np->m_accounts[account], w);
 
}
 

	
 
static void buddyTypingStopped(PurpleAccount *account, const char *who, gpointer null){
 
	std::string w = purple_normalize(account, who);
 
	size_t pos = w.find("/");
 
	if (pos != std::string::npos)
 
		w.erase((int) pos, w.length() - (int) pos);
 
	np->handleBuddyStoppedTyping(np->m_accounts[account], w);
 
}
 

	
 
static void gotAttention(PurpleAccount *account, const char *who, PurpleConversation *conv, guint type) {
 
	std::string w = purple_normalize(account, who);
 
	size_t pos = w.find("/");
 
	if (pos != std::string::npos)
 
		w.erase((int) pos, w.length() - (int) pos);
 
	np->handleAttention(np->m_accounts[account], w, "");
 
}
 

	
 
static bool initPurple() {
 
	bool ret;
 

	
 
	if (!resolvePurpleFunctions()) {
 
		LOG4CXX_ERROR(logger, "Unable to load libpurple.dll or some of the needed methods");
 
		return false;
 
	}
 

	
 
	purple_plugins_add_search_path("./plugins");
 

	
 
	purple_util_set_user_dir("./");
 
	remove("./accounts.xml");
 
	remove("./blist.xml");
 

	
 
	purple_debug_set_ui_ops(&debugUiOps);
 
	purple_debug_set_verbose(true);
 

	
 
	purple_core_set_ui_ops(&coreUiOps);
 
	if (KEYFILE_STRING("service", "eventloop") == "libev") {
 
		LOG4CXX_INFO(logger, "Will use libev based event loop");
 
	}
 
	else {
 
		LOG4CXX_INFO(logger, "Will use glib based event loop");
 
	}
 
	purple_eventloop_set_ui_ops(getEventLoopUiOps(KEYFILE_STRING("service", "eventloop") == "libev"));
 

	
 
	ret = purple_core_init("spectrum");
 
	if (ret) {
 
		static int blist_handle;
 
		static int conversation_handle;
 

	
 
		purple_set_blist(purple_blist_new());
 
		purple_blist_load();
 

	
 
@@ -1568,49 +1621,53 @@ static bool initPurple() {
 
// 		purple_signal_connect(purple_blist_get_handle(), "buddy-removed", &blist_handle,PURPLE_CALLBACK(buddyRemoved), NULL);
 
// 		purple_signal_connect(purple_blist_get_handle(), "buddy-signed-on", &blist_handle,PURPLE_CALLBACK(buddySignedOn), NULL);
 
// 		purple_signal_connect(purple_blist_get_handle(), "buddy-signed-off", &blist_handle,PURPLE_CALLBACK(buddySignedOff), NULL);
 
// 		purple_signal_connect(purple_blist_get_handle(), "buddy-status-changed", &blist_handle,PURPLE_CALLBACK(buddyStatusChanged), NULL);
 
		purple_signal_connect(purple_blist_get_handle(), "blist-node-removed", &blist_handle,PURPLE_CALLBACK(NodeRemoved), NULL);
 
// 		purple_signal_connect(purple_conversations_get_handle(), "chat-topic-changed", &conversation_handle, PURPLE_CALLBACK(conv_chat_topic_changed), NULL);
 
		static int xfer_handle;
 
		purple_signal_connect(purple_xfers_get_handle(), "file-send-start", &xfer_handle, PURPLE_CALLBACK(fileSendStart), NULL);
 
		purple_signal_connect(purple_xfers_get_handle(), "file-recv-start", &xfer_handle, PURPLE_CALLBACK(fileRecvStart), NULL);
 
		purple_signal_connect(purple_xfers_get_handle(), "file-recv-request", &xfer_handle, PURPLE_CALLBACK(newXfer), NULL);
 
		purple_signal_connect(purple_xfers_get_handle(), "file-recv-complete", &xfer_handle, PURPLE_CALLBACK(XferReceiveComplete), NULL);
 
		purple_signal_connect(purple_xfers_get_handle(), "file-send-complete", &xfer_handle, PURPLE_CALLBACK(XferSendComplete), NULL);
 
// 
 
// 		purple_commands_init();
 

	
 
	}
 
	return ret;
 
}
 

	
 

	
 
static void transportDataReceived(gpointer data, gint source, PurpleInputCondition cond) {
 
	if (cond & PURPLE_INPUT_READ) {
 
		char buffer[65535];
 
		char *ptr = buffer;
 
#ifdef WIN32
 
		ssize_t n = recv(source, ptr, sizeof(buffer), 0);
 
#else
 
		ssize_t n = read(source, ptr, sizeof(buffer));
 
#endif
 
		if (n <= 0) {
 
			LOG4CXX_INFO(logger, "Diconnecting from spectrum2 server");
 
			exit(errno);
 
		}
 
		std::string d = std::string(buffer, n);
 
		np->handleDataRead(d);
 
	}
 
	else {
 
		if (writeInput != 0) {
 
			purple_input_remove(writeInput);
 
			writeInput = 0;
 
		}
 
		np->readyForData();
 
	}
 
}
 

	
 
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::cerr << "option parsing failed: " << error->message << "\n";
 
		return -1;
backends/libpurple/purple_defs.cpp
Show inline comments
 
new file 100644
 
#include "purple_defs.h"
 
bool resolvePurpleFunctions() {
 
	return true;
 
}
 

	
backends/libpurple/purple_defs.h
Show inline comments
 
new file 100644
 
#pragma once
 

	
 
bool resolvePurpleFunctions();
backends/libpurple/utils.cpp
Show inline comments
 
@@ -26,48 +26,50 @@
 
#include <iostream>
 

	
 
#include "errno.h"
 

	
 
#ifndef WIN32 
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
#include <netinet/if_ether.h>
 
#include <netinet/ip.h>
 
#include <netinet/ip6.h>
 
#include <netinet/udp.h>
 
#include <netinet/tcp.h>
 
#include <netinet/ether.h>
 
#include "sys/socket.h"
 
#include <netdb.h>
 
#include <unistd.h>
 
#include <fcntl.h>
 
#else 
 
#include <process.h>
 
#define getpid _getpid 
 
#define ssize_t SSIZE_T
 
#include "win32/win32dep.h"
 
#endif
 

	
 
#include "purple_defs.h"
 

	
 
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;
 
	if (plugin && PURPLE_PLUGIN_HAS_ACTIONS(plugin)) {
 
		PurplePluginAction *action = NULL;
 
		GList *actions, *l;
 

	
 
		actions = PURPLE_PLUGIN_ACTIONS(plugin, gc);
 

	
 
		for (l = actions; l != NULL; l = l->next) {
 
			if (l->data) {
 
				action = (PurplePluginAction *) l->data;
 
				action->plugin = plugin;
 
				action->context = gc;
 
				if ((std::string) action->label == name) {
 
					action->callback(action);
 
				}
 
				purple_plugin_action_free(action);
 
			}
 
		}
 
	}
 
}
 

	
 
@@ -123,29 +125,29 @@ void spectrum_sigchld_handler(int sig)
 
}
 
#endif
 

	
 
int create_socket(char *host, int portno) {
 
	struct sockaddr_in serv_addr;
 
	
 
	int main_socket = socket(AF_INET, SOCK_STREAM, 0);
 
	memset((char *) &serv_addr, 0, sizeof(serv_addr));
 
	serv_addr.sin_family = AF_INET;
 
	serv_addr.sin_port = htons(portno);
 

	
 
	hostent *hos;  // Resolve name
 
	if ((hos = gethostbyname(host)) == NULL) {
 
		// strerror() will not work for gethostbyname() and hstrerror() 
 
		// is supposedly obsolete
 
		exit(1);
 
	}
 
	serv_addr.sin_addr.s_addr = *((unsigned long *) hos->h_addr_list[0]);
 

	
 
	if (connect(main_socket, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
 
		close(main_socket);
 
		main_socket = 0;
 
	}
 

	
 
	int flags = fcntl(main_socket, F_GETFL);
 
	flags |= O_NONBLOCK;
 
	fcntl(main_socket, F_SETFL, flags);
 
// 	int flags = fcntl(main_socket, F_GETFL);
 
// 	flags |= O_NONBLOCK;
 
// 	fcntl(main_socket, F_SETFL, flags);
 
	return main_socket;
 
}
backends/libyahoo2/CMakeLists.txt
Show inline comments
 
new file 100644
 
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)
 
backends/libyahoo2/httpfetch.cpp
Show inline comments
 
new file 100644
 

	
 
#include "httpfetch.h"
 
#include "transport/logging.h"
 

	
 
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;
 
}
backends/libyahoo2/httpfetch.h
Show inline comments
 
new file 100644
 
#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"
 

	
 
// for signal handler
 
#include "unistd.h"
 
#include "signal.h"
 
#include "sys/wait.h"
 
#include "sys/signal.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;
 
};
backends/libyahoo2/main.cpp
Show inline comments
 
new file 100644
 
// 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/TLS/OpenSSL/OpenSSLContextFactory.h"
 

	
 
// for signal handler
 
#include "unistd.h"
 
#include "signal.h"
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 

	
 
// 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;
 

	
 
	if (signal(SIGCHLD, spectrum_sigchld_handler) == SIG_ERR) {
 
		std::cout << "SIGCHLD handler can't be set\n";
 
		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;
 
	}
 

	
 
	Config config;
 
	if (!config.load(argv[5])) {
 
		std::cerr << "Can't open " << argv[1] << " configuration file.\n";
 
		return 1;
 
	}
 

	
 
	Logging::initBackendLogging(&config);
 

	
 
	register_callbacks();
 
	yahoo_set_log_level(YAHOO_LOG_DEBUG);
 

	
 
	Swift::SimpleEventLoop eventLoop;
 
	loop_ = &eventLoop;
 
	np = new YahooPlugin(&config, &eventLoop, host, port);
 
	loop_->run();
 

	
 
	return 0;
 
}
backends/libyahoo2/sample_client.example
Show inline comments
 
new file 100644
 
/*
 
 * sample yahoo client based on libyahoo2
 
 *
 
 * libyahoo2 is available at http://libyahoo2.sourceforge.net/
 
 *
 
 * $Revision: 373 $
 
 * $Date: 2010-06-02 13:55:25 -0700 (Wed, 02 Jun 2010) $
 
 * 
 
 * Copyright (C) 2002-2004, Philip S Tellis <philip.tellis AT gmx.net>
 
 * Copyright (C) 2009, Siddhesh Poyarekar <siddhesh.poyarekar@gmail.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
 
 *
 
 */
 

	
 
#if HAVE_CONFIG_H
 
# include <config.h>
 
#endif
 
#ifndef _WIN32
 
#include <netdb.h>
 
#include <sys/time.h>
 
#endif
 
#include <sys/types.h>
 
#ifndef _WIN32
 
#include <sys/socket.h>
 
#include <netinet/in.h>
 
#include <arpa/inet.h>
 

	
 
#include <termios.h>
 
#endif
 
#include <stdio.h>
 
#include <stdarg.h>
 
#include <stdlib.h>
 
#include <string.h>
 
#include <ctype.h>
 
#include <time.h>
 
#include <sys/stat.h>
 
#include <fcntl.h>
 
#include <errno.h>
 
#include <openssl/ssl.h>
 
#if HAVE_UNISTD_H
 
#include <unistd.h>
 
#endif
 

	
 
/* Get these from http://libyahoo2.sourceforge.net/ */
 
#include <yahoo2.h>
 
#include <yahoo2_callbacks.h>
 
#include "yahoo_util.h"
 

	
 
#ifndef _WIN32
 
int fileno(FILE * stream);
 
#endif
 

	
 
#define MAX_PREF_LEN 255
 

	
 
static char *local_host = NULL;
 

	
 
static int do_mail_notify = 0;
 
static int do_yahoo_debug = 0;
 
static int ignore_system = 0;
 
static int do_typing_notify = 1;
 
static int accept_webcam_viewers = 1;
 
static int send_webcam_images = 0;
 
static int webcam_direction = YAHOO_WEBCAM_DOWNLOAD;
 
static time_t curTime = 0;
 
static time_t pingTimer = 0;
 
static time_t webcamTimer = 0;
 
static double webcamStart = 0;
 

	
 
/* id of the webcam connection (needed for uploading) */
 
static int webcam_id = 0;
 

	
 
static int poll_loop=1;
 

	
 
static void register_callbacks();
 

	
 
typedef struct {
 
	char yahoo_id[255];
 
	char password[255];
 
	int id;
 
	int fd;
 
	int status;
 
	char *msg;
 
} yahoo_local_account;
 

	
 
typedef struct {
 
	char yahoo_id[255];
 
	char name[255];
 
	int status;
 
	int away;
 
	char *msg;
 
	char group[255];
 
} yahoo_account;
 

	
 
typedef struct {
 
	int id;
 
	char *label;
 
} yahoo_idlabel;
 

	
 
typedef struct {
 
	int id;
 
	char *who;
 
} yahoo_authorize_data;
 

	
 
yahoo_idlabel yahoo_status_codes[] = {
 
	{YAHOO_STATUS_AVAILABLE, "Available"},
 
	{YAHOO_STATUS_BRB, "BRB"},
 
	{YAHOO_STATUS_BUSY, "Busy"},
 
	{YAHOO_STATUS_NOTATHOME, "Not Home"},
 
	{YAHOO_STATUS_NOTATDESK, "Not at Desk"},
 
	{YAHOO_STATUS_NOTINOFFICE, "Not in Office"},
 
	{YAHOO_STATUS_ONPHONE, "On Phone"},
 
	{YAHOO_STATUS_ONVACATION, "On Vacation"},
 
	{YAHOO_STATUS_OUTTOLUNCH, "Out to Lunch"},
 
	{YAHOO_STATUS_STEPPEDOUT, "Stepped Out"},
 
	{YAHOO_STATUS_INVISIBLE, "Invisible"},
 
	{YAHOO_STATUS_IDLE, "Idle"},
 
	{YAHOO_STATUS_OFFLINE, "Offline"},
 
	{YAHOO_STATUS_CUSTOM, "[Custom]"},
 
	{YPACKET_STATUS_NOTIFY, "Notify"},
 
	{0, NULL}
 
};
 

	
 
static void ext_yahoo_close(void *fd);
 

	
 
char * yahoo_status_code(enum yahoo_status s)
 
{
 
	int i;
 
	for(i=0; yahoo_status_codes[i].label; i++)
 
		if(yahoo_status_codes[i].id == s)
 
			return yahoo_status_codes[i].label;
 
	return "Unknown";
 
}
 

	
 
#define YAHOO_DEBUGLOG ext_yahoo_log
 

	
 
static int ext_yahoo_log(const char *fmt,...)
 
{
 
	va_list ap;
 

	
 
	va_start(ap, fmt);
 

	
 
	vfprintf(stderr, fmt, ap);
 
	fflush(stderr);
 
	va_end(ap);
 
	return 0;
 
}
 

	
 
#define LOG(x) if(do_yahoo_debug) { YAHOO_DEBUGLOG("%s:%d: ", __FILE__, __LINE__); \
 
	YAHOO_DEBUGLOG x; \
 
	YAHOO_DEBUGLOG("\n"); }
 

	
 
#define WARNING(x) if(do_yahoo_debug) { YAHOO_DEBUGLOG("%s:%d: warning: ", __FILE__, __LINE__); \
 
	YAHOO_DEBUGLOG x; \
 
	YAHOO_DEBUGLOG("\n"); }
 

	
 
#define print_message(x) { printf x; printf("\n"); }
 

	
 
static yahoo_local_account * ylad = NULL;
 
static YList * buddies = NULL;
 

	
 
static int expired(time_t timer)
 
{
 
	if (timer && curTime >= timer)
 
		return 1;
 

	
 
	return 0;
 
}
 

	
 
static void rearm(time_t *timer, int seconds)
 
{
 
	time(timer);
 
	*timer += seconds;
 
}
 

	
 
#ifndef _WIN32
 
FILE *popen(const char *command, const char *type);
 
int pclose(FILE *stream);
 
int gethostname(char *name, size_t len);
 
#endif
 

	
 
static char * get_local_addresses()
 
{
 
	static char addresses[1024];
 
	char buff[1024];
 
	struct hostent * hn;
 
#ifndef _WIN32
 
	char gateway[16];
 
	char  * c;
 
	int i;
 
	FILE * f;
 
	f = popen("netstat -nr", "r");
 
	if(!f)
 
			goto IP_TEST_2;
 
	while( fgets(buff, sizeof(buff), f)  != NULL ) {
 
			c = strtok( buff, " " );
 
			if( (strstr(c, "default") || strstr(c,"0.0.0.0") ) &&
 
							!strstr(c, "127.0.0" ) )
 
					break;
 
	}
 
	c = strtok( NULL, " " );
 
	pclose(f);
 

	
 
	strncpy(gateway,c, 16);
 

	
 

	
 

	
 
	for(i = strlen(gateway); gateway[i] != '.'; i-- )
 
		gateway[i] = 0;
 

	
 
	gateway[i] = 0;
 

	
 
	for(i = strlen(gateway); gateway[i] != '.'; i-- )
 
		gateway[i] = 0;
 

	
 
	f = popen("/sbin/ifconfig -a", "r");
 
	if(!f)
 
		goto IP_TEST_2;
 

	
 
	while( fgets(buff, sizeof(buff), f) != NULL ) {
 
		if( strstr(buff, "inet") && strstr(buff,gateway) )
 
			break;
 
	}
 
	pclose(f);
 

	
 
	c = strtok( buff, " " );
 
	c = strtok( NULL, " " );
 

	
 
	strncpy ( addresses, c, sizeof(addresses) );
 
	c = strtok(addresses, ":" );
 
	strncpy ( buff, c, sizeof(buff) );
 
	if((c=strtok(NULL, ":")))
 
		strncpy( buff, c, sizeof(buff) );
 

	
 
	strncpy(addresses, buff, sizeof(addresses));
 

	
 
	return addresses;
 
		
 
		
 
IP_TEST_2:
 
#endif /* _WIN32 */
 

	
 
	gethostname(buff,sizeof(buff));
 

	
 
	hn = gethostbyname(buff);
 
	if(hn)
 
		strncpy(addresses, inet_ntoa( *((struct in_addr*)hn->h_addr)), sizeof(addresses) );
 
	else
 
		addresses[0] = 0;
 

	
 
	return addresses;
 
}
 

	
 
static double get_time()
 
{
 
#ifndef _WIN32
 
	struct timeval ct;
 
	gettimeofday(&ct, 0);
 

	
 
	/* return time in milliseconds */
 
	return (ct.tv_sec * 1E3 + ct.tv_usec / 1E3);
 
#else
 
	return timeGetTime();
 
#endif
 
}
 

	
 
static int yahoo_ping_timeout_callback()
 
{
 
	print_message(("Sending a keep alive message"));
 
	yahoo_keepalive(ylad->id);
 
	rearm(&pingTimer, 600);
 
	return 1;
 
}
 

	
 
static int yahoo_webcam_timeout_callback(int id)
 
{
 
	static unsigned image_num = 0;
 
	unsigned char *image = NULL;
 
	unsigned int length = 0;
 
	unsigned int timestamp = get_time() - webcamStart;
 
	char fname[1024];
 
	FILE *f_image = NULL;
 
	struct stat s_image;
 

	
 
	if (send_webcam_images)
 
	{
 
		sprintf(fname, "images/image_%.3d.jpc", image_num++);
 
		if (image_num > 999) image_num = 0;
 
		if (stat(fname, &s_image) == -1)
 
			return -1;
 
		length = s_image.st_size;
 
		image = y_new0(unsigned char, length);
 

	
 
		if ((f_image = fopen(fname, "r")) != NULL) {
 
			fread(image, length, 1, f_image);
 
			fclose(f_image);
 
		} else {
 
			printf("Error reading from %s\n", fname);
 
		}
 
	}
 

	
 
	print_message(("Sending a webcam image (%d bytes)", length));
 
	yahoo_webcam_send_image(id, image, length, timestamp);
 
	FREE(image);
 
	rearm(&webcamTimer, 2);
 
	return 1;
 
}
 

	
 
YList * conferences = NULL;
 
typedef struct {
 
	int id;
 
	char * me;
 
	char * room_name;
 
	char * host;
 
	YList * members;
 
	int joined;
 
} conf_room;
 

	
 
static const char * get_buddy_name(const char * yid)
 
{
 
	YList * b;
 
	for (b = buddies; b; b = b->next) {
 
		yahoo_account * ya = b->data;
 
		if(!strcmp(yid, ya->yahoo_id))
 
			return ya->name&&*ya->name?ya->name:ya->yahoo_id;
 
	}
 

	
 
	return yid;
 
}
 

	
 
static conf_room * find_conf_room_by_name_and_id(int id, const char * me, const char * name)
 
{
 
	YList * l;
 
	for(l = conferences; l; l=l->next) {
 
		conf_room * cr = l->data;
 
		if(cr->id == id && !strcmp(name, cr->room_name) && (me == NULL || cr->me == NULL || !strcmp(me, cr->me))) {
 
			return cr;
 
		}
 
	}
 

	
 
	return NULL;
 
}
 

	
 
static void ext_yahoo_got_conf_invite(int id, const char *me, const char *who, const char *room, const char *msg, YList *members)
 
{
 
	conf_room * cr = y_new0(conf_room, 1);
 
	cr->room_name = strdup(room);
 
	cr->me = strdup(me);
 
	cr->host = strdup(who);
 
	cr->members = members;
 
	cr->id = id;
 

	
 
	conferences = y_list_append(conferences, cr);
 

	
 
	print_message(("%s has invited you [%s] to a conference: %s\n"
 
				"with the message: %s",
 
				who, me, room, msg));
 

	
 
	for(; members; members=members->next)
 
		print_message(("\t%s", (char *)members->data));
 
	
 
}
 
static void ext_yahoo_conf_userdecline(int id, const char *me, const char *who, const char *room, const char *msg)
 
{
 
	YList * l;
 
	/* TODO: probably have to use the me arg to find the room */
 
	conf_room * cr = find_conf_room_by_name_and_id(id, me, room);
 
	
 
	if(cr)
 
	for(l = cr->members; l; l=l->next) {
 
		char * w = l->data;
 
		if(!strcmp(w, who)) {
 
			FREE(l->data);
 
			cr->members = y_list_remove_link(cr->members, l);
 
			y_list_free_1(l);
 
			break;
 
		}
 
	}
 

	
 
	print_message(("%s declined the invitation from %s to %s\n"
 
				"with the message: %s", who, me, room, msg));
 
}
 

	
 
static void ext_yahoo_conf_userjoin(int id, const char *me, const char *who, const char *room)
 
{
 
	conf_room * cr = find_conf_room_by_name_and_id(id, me, room);
 
	if(cr) {
 
	YList * l = NULL;
 
	for(l = cr->members; l; l=l->next) {
 
		char * w = l->data;
 
		if(!strcmp(w, who))
 
			break;
 
	}
 
	if(!l)
 
		cr->members = y_list_append(cr->members, strdup(who));
 
	}
 

	
 
	print_message(("%s joined the conference %s [%s]", who, room, me));
 

	
 
}
 

	
 
static void ext_yahoo_conf_userleave(int id, const char *me, const char *who, const char *room)
 
{
 
	YList * l;
 
	conf_room * cr = find_conf_room_by_name_and_id(id, me, room);
 
	
 
	if(cr)
 
	for(l = cr->members; l; l=l->next) {
 
		char * w = l->data;
 
		if(!strcmp(w, who)) {
 
			FREE(l->data);
 
			cr->members = y_list_remove_link(cr->members, l);
 
			y_list_free_1(l);
 
			break;
 
		}
 
	}
 

	
 
	print_message(("%s left the conference %s [%s]", who, room, me));
 
}
 

	
 
static void ext_yahoo_conf_message(int id, const char *me, const char *who, const char *room, const char *msg, int utf8)
 
{
 
	char * umsg = (char *)msg;
 

	
 
	if(utf8)
 
		umsg = y_utf8_to_str(msg);
 

	
 
	who = get_buddy_name(who);
 

	
 
	print_message(("%s (in %s [%s]): %s", who, room, me, umsg));
 

	
 
	if(utf8)
 
		FREE(umsg);
 
}
 

	
 
static void print_chat_member(struct yahoo_chat_member *ycm) 
 
{
 
	printf("%s (%s) ", ycm->id, ycm->alias);
 
	printf(" Age: %d Sex: ", ycm->age);
 
	if (ycm->attribs & YAHOO_CHAT_MALE) {
 
		printf("Male");
 
	} else if (ycm->attribs & YAHOO_CHAT_FEMALE) {
 
		printf("Female");
 
	} else {
 
		printf("Unknown");
 
	}
 
	if (ycm->attribs & YAHOO_CHAT_WEBCAM) {
 
		printf(" with webcam");
 
	}
 

	
 
	printf("  Location: %s", ycm->location);
 
}
 

	
 
static void ext_yahoo_chat_cat_xml(int id, const char *xml) 
 
{
 
	print_message(("%s", xml));
 
}
 

	
 
static void ext_yahoo_chat_join(int id, const char *me, const char *room, const char * topic, YList *members, void *fd)
 
{
 
	print_message(("You [%s] have joined the chatroom %s with topic %s", me, room, topic));
 

	
 
	while(members) {
 
		YList *n = members->next;
 

	
 
		printf("\t");
 
		print_chat_member(members->data);
 
		printf("\n");
 
		FREE(((struct yahoo_chat_member *)members->data)->id);
 
		FREE(((struct yahoo_chat_member *)members->data)->alias);
 
		FREE(((struct yahoo_chat_member *)members->data)->location);
 
		FREE(members->data);
 
		FREE(members);
 
		members=n;
 
	}
 
}
 

	
 
static void ext_yahoo_chat_userjoin(int id, const char *me, const char *room, struct yahoo_chat_member *who)
 
{
 
	print_chat_member(who);
 
	print_message((" joined the chatroom %s [%s]", room, me));
 
	FREE(who->id);
 
	FREE(who->alias);
 
	FREE(who->location);
 
	FREE(who);
 
}
 

	
 
static void ext_yahoo_chat_userleave(int id, const char *me, const char *room, const char *who)
 
{
 
	print_message(("%s left the chatroom %s [%s]", who, room, me));
 
}
 

	
 
static void ext_yahoo_chat_message(int id, const char *me, const char *who, const char *room, const char *msg, int msgtype, int utf8)
 
{
 
	char * umsg = (char *)msg;
 
	char * charpos;
 

	
 
	if(utf8)
 
		umsg = y_utf8_to_str(msg);
 
	/* Remove escapes */
 
	charpos = umsg;
 
	while(*charpos) {
 
		if (*charpos == 0x1b) {
 
			*charpos = ' ';
 
		}
 
		charpos++;
 
	}
 

	
 
	if (msgtype == 2) {
 
		print_message(("(in %s [%s]) %s %s", room, me, who, umsg));
 
	} else {
 
		print_message(("(in %s [%s]) %s: %s", room, me, who, umsg));
 
	}
 

	
 
	if(utf8)
 
		FREE(umsg);
 
}
 

	
 
static void ext_yahoo_status_changed(int id, const char *who, int stat, const char *msg, int away, int idle, int mobile)
 
{
 
	yahoo_account * ya=NULL;
 
	YList * b;
 
	char buf[1024];
 

	
 
	for(b = buddies; b; b = b->next) {
 
		if(!strcmp(((yahoo_account *)b->data)->yahoo_id, who)) {
 
			ya = b->data;
 
			break;
 
		}
 
	}
 
	
 
	if (msg == NULL) {
 
		sprintf(buf, "%s", yahoo_status_code(stat));
 
	}
 
	else if (stat == YAHOO_STATUS_CUSTOM) {
 
		sprintf(buf, "%s", msg);
 
	} else {
 
		sprintf(buf, "%s: %s", yahoo_status_code(stat), msg);
 
	}
 

	
 
	if (away > 0) {
 
		char away_buf[32];
 
		sprintf(away_buf, " away[%d]", away);
 
		strcat(buf, away_buf);
 
	}
 

	
 
	if (mobile > 0) {
 
		char mobile_buf[32];
 
		sprintf(mobile_buf, " mobile[%d]", mobile);
 
		strcat(buf, mobile_buf);
 
	}
 

	
 
	if (idle > 0) {
 
		char time_buf[32];
 
		sprintf(time_buf, " idle for %d:%02d:%02d", idle/3600, (idle/60)%60, idle%60);
 
		strcat(buf, time_buf);
 
	}
 

	
 
	print_message(("%s (%s) is now %s", ya?ya->name:who, who, buf))
 

	
 
	if(ya) {
 
		ya->status = stat;
 
		ya->away = away;
 
		if(msg) {
 
			FREE(ya->msg);
 
			ya->msg = strdup(msg);
 
		}
 
	}
 
}
 

	
 
static void ext_yahoo_got_buddies(int id, YList * buds)
 
{
 
	while(buddies) {
 
		FREE(buddies->data);
 
		buddies = buddies->next;
 
		if(buddies)
 
			FREE(buddies->prev);
 
	}
 
	for(; buds; buds = buds->next) {
 
		yahoo_account *ya = y_new0(yahoo_account, 1);
 
		struct yahoo_buddy *bud = buds->data;
 
		strncpy(ya->yahoo_id, bud->id, 255);
 
		if(bud->real_name)
 
			strncpy(ya->name, bud->real_name, 255);
 
		strncpy(ya->group, bud->group, 255);
 
		ya->status = YAHOO_STATUS_OFFLINE;
 
		buddies = y_list_append(buddies, ya);
 

	
 
/*		print_message(("%s is %s", bud->id, bud->real_name));*/
 
	}
 
}
 

	
 
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)
 
{
 
	who = get_buddy_name(who);
 

	
 
	printf("\a");
 
	if(tm) {
 
		char timestr[255];
 

	
 
		strncpy(timestr, ctime((time_t *)&tm), sizeof(timestr));
 
		timestr[strlen(timestr) - 1] = '\0';
 

	
 
		print_message(("[Offline message at %s to %s from %s]: **DING**",
 
				timestr, me, who))
 
	} else
 
		print_message(("[%s]%s: **DING**", me, who))
 
}
 

	
 
static void ext_yahoo_got_im(int id, const char *me, const char *who, const char *msg, long tm, int stat, int utf8)
 
{
 
	char *umsg = (char *)msg;
 

	
 
	if(stat == 2) {
 
		LOG(("Error sending message from %s to %s", me, who));
 
		return;
 
	}
 

	
 
	if(!msg)
 
		return;
 

	
 
	if(utf8)
 
		umsg = y_utf8_to_str(msg);
 
	
 
	who = get_buddy_name(who);
 

	
 
	if(tm) {
 
		char timestr[255];
 

	
 
		strncpy(timestr, ctime((time_t *)&tm), sizeof(timestr));
 
		timestr[strlen(timestr) - 1] = '\0';
 

	
 
		print_message(("[Offline message at %s to %s from %s]: %s", 
 
				timestr, me, who, umsg))
 
	} else
 
		print_message(("[%s]%s: %s", me, who, umsg))
 

	
 
	if(utf8)
 
		FREE(umsg);
 
}
 

	
 
static void ext_yahoo_rejected(int id, const char *who, const char *msg)
 
{
 
	print_message(("%s has rejected you%s%s", who, 
 
				(msg?" with the message:\n":"."), 
 
				(msg?msg:"")));
 
}
 

	
 
static void ext_yahoo_contact_added(int id, const char *myid, const char *who, const char *msg)
 
{
 
	char buff[1024];
 

	
 
	snprintf(buff, sizeof(buff), "%s, the yahoo user %s has added you to their contact list", myid, who);
 
	if(msg) {
 
		strcat(buff, " with the following message:\n");
 
		strcat(buff, msg);
 
		strcat(buff, "\n");
 
	} else {
 
		strcat(buff, ".  ");
 
	}
 
	strcat(buff, "Do you want to allow this [Y/N]?");
 

	
 
/*	print_message((buff));
 
	scanf("%c", &choice);
 
	if(choice != 'y' && choice != 'Y')
 
		yahoo_reject_buddy(id, who, "Thanks, but no thanks.");
 
*/
 
}
 

	
 
static void ext_yahoo_typing_notify(int id, const char* me, const char *who, int stat)
 
{
 
	if(stat && do_typing_notify)
 
		print_message(("[%s]%s is typing...", me, who));
 
}
 

	
 
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)
 
{
 
	char buff[1024] = {0};
 
	
 
	if(!do_mail_notify)
 
		return;
 

	
 
	if(from && subj)
 
		snprintf(buff, sizeof(buff), 
 
				"You have new mail from %s about %s\n", 
 
				from, subj);
 
	if(cnt) {
 
		char buff2[100];
 
		snprintf(buff2, sizeof(buff2), 
 
				"You have %d message%s\n", 
 
				cnt, cnt==1?"":"s");
 
		strcat(buff, buff2);
 
	}
 

	
 
	if(buff[0])
 
		print_message((buff));
 
}
 

	
 
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 unsigned char *cur_image = NULL;
 
	static unsigned int cur_image_len = 0;
 
	static unsigned int image_num = 0;
 
	FILE* f_image;
 
	char fname[1024];
 

	
 
	/* copy image part to cur_image */
 
	if (real_size)
 
	{
 
		if (!cur_image) cur_image = y_new0(unsigned char, image_size);
 
		memcpy(cur_image + cur_image_len, image, real_size);
 
		cur_image_len += real_size;
 
	}
 

	
 
	if (image_size == cur_image_len)
 
	{
 
		print_message(("Received a image update at %d (%d bytes)",
 
			 timestamp, image_size));
 

	
 
		/* if we recieved an image then write it to file */
 
		if (image_size)
 
		{
 
			sprintf(fname, "images/%s_%.3d.jpc", who, image_num++);
 

	
 
			if ((f_image = fopen(fname, "w")) != NULL) {
 
				fwrite(cur_image, image_size, 1, f_image);
 
				fclose(f_image);
 
			} else {
 
				printf("Error writing to %s\n", fname);
 
			}
 
			FREE(cur_image);
 
			cur_image_len = 0;
 
			if (image_num > 999) image_num = 0;
 
		}
 
	}
 
}
 

	
 
static void ext_yahoo_webcam_viewer(int id, const char *who, int connect)
 
{
 
	switch (connect)
 
	{
 
		case 0:
 
			print_message(("%s has stopped viewing your webcam", who));
 
			break;
 
		case 1:
 
			print_message(("%s has started viewing your webcam", who));
 
			break;
 
		case 2:
 
			print_message(("%s is trying to view your webcam", who));
 
			yahoo_webcam_accept_viewer(id, who, accept_webcam_viewers);
 
			break;
 
	}
 
}
 

	
 
static void ext_yahoo_webcam_closed(int id, const char *who, int reason)
 
{
 
	switch(reason)
 
	{
 
		case 1:
 
			print_message(("%s stopped broadcasting", who));
 
			break;
 
		case 2:
 
			print_message(("%s cancelled viewing permission", who));
 
			break;
 
		case 3:
 
			print_message(("%s declines permission to view his/her webcam", who));
 
			break;
 
		case 4:
 
			print_message(("%s does not have his/her webcam online", who));
 
			break;
 
	}
 
}
 

	
 
static void ext_yahoo_webcam_data_request(int id, int send)
 
{
 
	webcam_id = id;
 

	
 
	if (send) {
 
		print_message(("Got request to start sending images"));
 
		if (!webcamTimer)
 
			rearm(&webcamTimer, 2);
 
	} else {
 
		print_message(("Got request to stop sending images"));
 
	}
 
	send_webcam_images = send;
 
}
 

	
 
static void ext_yahoo_webcam_invite(int id, const char *me, const char *from)
 
{
 
	print_message(("Got a webcam invitation to %s from %s", me, from));
 
}
 

	
 
static void ext_yahoo_webcam_invite_reply(int id, const char *me, const char *from, int accept)
 
{
 
	if(accept) {
 
		print_message(("[%s]%s accepted webcam invitation...", me, from));
 
	} else {
 
		print_message(("[%s]%s declined webcam invitation...", me, from));
 
	}
 
}
 

	
 
static void ext_yahoo_system_message(int id, const char *me, const char *who, const char *msg)
 
{
 
	if(ignore_system)
 
		return;
 

	
 
	print_message(("Yahoo System Message: %s", msg));
 
}
 

	
 
void yahoo_logout()
 
{
 
	if (ylad->id <= 0) {
 
		return;
 
	}
 

	
 
	pingTimer=0;
 

	
 
	while(conferences) {
 
		YList * n = conferences->next;
 
		conf_room * cr = conferences->data;
 
		if(cr->joined)
 
			yahoo_conference_logoff(ylad->id, NULL, cr->members, cr->room_name);
 
		FREE(cr->me);
 
		FREE(cr->room_name);
 
		FREE(cr->host);
 
		while(cr->members) {
 
			YList *n = cr->members->next;
 
			FREE(cr->members->data);
 
			FREE(cr->members);
 
			cr->members=n;
 
		}
 
		FREE(cr);
 
		FREE(conferences);
 
		conferences = n;
 
	}
 
	
 
	yahoo_logoff(ylad->id);
 
	yahoo_close(ylad->id);
 

	
 
	ylad->status = YAHOO_STATUS_OFFLINE;
 
	ylad->id = 0;
 

	
 
	poll_loop=0;
 

	
 
	print_message(("logged_out"));
 
}
 

	
 
static void ext_yahoo_login(yahoo_local_account * ylad, int login_mode)
 
{
 
	LOG(("ext_yahoo_login"));
 

	
 
	ylad->id = yahoo_init_with_attributes(ylad->yahoo_id, ylad->password, 
 
			"local_host", local_host,
 
			"pager_port", 5050,
 
			NULL);
 
	ylad->status = YAHOO_STATUS_OFFLINE;
 
	yahoo_login(ylad->id, login_mode);
 

	
 
/*	if (ylad->id <= 0) {
 
		print_message(("Could not connect to Yahoo server.  Please verify that you are connected to the net and the pager host and port are correctly entered."));
 
		return;
 
	}
 
*/
 
	rearm(&pingTimer, 600);
 
}
 

	
 
static void ext_yahoo_got_cookies(int id)
 
{
 
	/*yahoo_get_yab(id);*/
 
}
 

	
 
static void ext_yahoo_login_response(int id, int succ, const char *url)
 
{
 
	char buff[1024];
 

	
 
	if(succ == YAHOO_LOGIN_OK) {
 
		ylad->status = yahoo_current_status(id);
 
		print_message(("logged in"));
 
		return;
 
		
 
	} else if(succ == YAHOO_LOGIN_UNAME) {
 

	
 
		snprintf(buff, sizeof(buff), "Could not log into Yahoo service - username not recognised.  Please verify that your username is correctly typed.");
 
	} else if(succ == YAHOO_LOGIN_PASSWD) {
 

	
 
		snprintf(buff, sizeof(buff), "Could not log into Yahoo service - password incorrect.  Please verify that your password is correctly typed.");
 

	
 
	} else if(succ == YAHOO_LOGIN_LOCK) {
 
		
 
		snprintf(buff, sizeof(buff), "Could not log into Yahoo service.  Your account has been locked.\nVisit %s to reactivate it.", url);
 

	
 
	} else if(succ == YAHOO_LOGIN_DUPL) {
 

	
 
		snprintf(buff, sizeof(buff), "You have been logged out of the yahoo service, possibly due to a duplicate login.");
 
	} else if(succ == YAHOO_LOGIN_SOCK) {
 

	
 
		snprintf(buff, sizeof(buff), "The server closed the socket.");
 
	} else {
 
		snprintf(buff, sizeof(buff), "Could not log in, unknown reason: %d.", succ);
 
	}
 

	
 
	ylad->status = YAHOO_STATUS_OFFLINE;
 
	print_message((buff));
 
	yahoo_logout();
 
	poll_loop=0;
 
}
 

	
 
static void ext_yahoo_error(int id, const char *err, int fatal, int num)
 
{
 
	fprintf(stdout, "Yahoo Error: ");
 
	fprintf(stdout, "%s", err);
 
	switch(num) {
 
		case E_UNKNOWN:
 
			fprintf(stdout, "unknown error %s", err);
 
			break;
 
		case E_CUSTOM:
 
			fprintf(stdout, "custom error %s", err);
 
			break;
 
		case E_CONFNOTAVAIL:
 
			fprintf(stdout, "%s is not available for the conference", err);
 
			break;
 
		case E_IGNOREDUP:
 
			fprintf(stdout, "%s is already ignored", err);
 
			break;
 
		case E_IGNORENONE:
 
			fprintf(stdout, "%s is not in the ignore list", err);
 
			break;
 
		case E_IGNORECONF:
 
			fprintf(stdout, "%s is in buddy list - cannot ignore ", err);
 
			break;
 
		case E_SYSTEM:
 
			fprintf(stdout, "system error %s", err);
 
			break;
 
		case E_CONNECTION:
 
			fprintf(stdout, "server connection error %s", err);
 
			break;
 
	}
 
	fprintf(stdout, "\n");
 
	if(fatal)
 
		yahoo_logout();
 
}
 

	
 
void yahoo_set_current_state(int yahoo_state)
 
{
 
	if (ylad->status == YAHOO_STATUS_OFFLINE && yahoo_state != YAHOO_STATUS_OFFLINE) {
 
		ext_yahoo_login(ylad, yahoo_state);
 
		return;
 
	} else if (ylad->status != YAHOO_STATUS_OFFLINE && yahoo_state == YAHOO_STATUS_OFFLINE) {
 
		yahoo_logout();
 
		return;
 
	}
 

	
 
	ylad->status = yahoo_state;
 
	if(yahoo_state == YAHOO_STATUS_CUSTOM) {
 
		if(ylad->msg)
 
			yahoo_set_away(ylad->id, yahoo_state, ylad->msg, 1);
 
		else
 
			yahoo_set_away(ylad->id, yahoo_state, "delta p * delta x too large", 1);
 
	} else
 
		yahoo_set_away(ylad->id, yahoo_state, NULL, 1);
 
}
 

	
 
static int ext_yahoo_connect(const char *host, int port)
 
{
 
	WARNING(("This should not be used anymore. File a bug report."));
 
	return -1;
 
}
 

	
 
/*************************************
 
 * Callback handling code starts here
 
 */
 
YList *connections = NULL;
 
struct _conn {
 
	int fd;
 
	SSL *ssl;
 
	int use_ssl;
 
	int remove;
 
};
 

	
 
struct conn_handler {
 
	struct _conn *con;
 
	int id;
 
	int tag;
 
	yahoo_input_condition cond;
 
	int remove;
 
	void *data;
 
};
 

	
 
static int connection_tags=0;
 

	
 
static int ext_yahoo_add_handler(int id, void *d, yahoo_input_condition cond, void *data)
 
{
 
	struct conn_handler *h = y_new0(struct conn_handler, 1);
 

	
 
	h->id = id;
 
	h->tag = ++connection_tags;
 
	h->con = d;
 
	h->cond = cond;
 
	h->data = data;
 

	
 
	LOG(("Add %d(%d) for %d, tag %d", h->con->fd, cond, id, h->tag));
 

	
 
	connections = y_list_prepend(connections, h);
 

	
 
	return h->tag;
 
}
 

	
 
static void ext_yahoo_remove_handler(int id, int tag)
 
{
 
	YList *l;
 
	if (!tag)
 
		return;
 

	
 
	for(l = connections; l; l = y_list_next(l)) {
 
		struct conn_handler *c = l->data;
 
		if(c->tag == tag) {
 
			/* don't actually remove it, just mark it for removal */
 
			/* we'll remove when we start the next poll cycle */
 
			LOG(("Marking id:%d fd:%p tag:%d for removal",
 
				c->id, c->con, c->tag));
 
			c->remove = 1;
 
			return;
 
		}
 
	}
 
}
 

	
 
static SSL *do_ssl_connect(int fd)
 
{
 
	SSL *ssl;
 
	SSL_CTX *ctx;
 

	
 
	LOG(("SSL Handshake"));
 

	
 
	SSL_library_init ();
 
	ctx = SSL_CTX_new(SSLv23_client_method());
 
	ssl = SSL_new(ctx);
 
	SSL_CTX_free(ctx);
 
	SSL_set_fd(ssl, fd);
 

	
 
	if (SSL_connect(ssl) == 1)
 
		return ssl;
 

	
 
	return NULL;
 
}
 

	
 
struct connect_callback_data {
 
	yahoo_connect_callback callback;
 
	void * callback_data;
 
	int id;
 
	int tag;
 
};
 

	
 
static void connect_complete(void *data, struct _conn *source, yahoo_input_condition condition)
 
{
 
	struct connect_callback_data *ccd = data;
 
	int error, err_size = sizeof(error);
 

	
 
	ext_yahoo_remove_handler(0, ccd->tag);
 
	getsockopt(source->fd, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&err_size);
 

	
 
	if(error)
 
		goto err;
 

	
 
	LOG(("Connected fd: %d, error: %d", source->fd, error));
 

	
 
	if (source->use_ssl) {
 
		source->ssl = do_ssl_connect(source->fd);
 

	
 
		if (!source->ssl) {
 
err:
 
			LOG(("SSL Handshake Failed!"));
 
			ext_yahoo_close(source);
 

	
 
			ccd->callback(NULL, 0, ccd->callback_data);
 
			FREE(ccd);
 
			return;
 
		}
 
	}
 

	
 
	fcntl(source->fd, F_SETFL, O_NONBLOCK);
 

	
 
	ccd->callback(source, error, ccd->callback_data);
 
	FREE(ccd);
 
}
 

	
 
void yahoo_callback(struct conn_handler *c, yahoo_input_condition cond)
 
{
 
	int ret=1;
 
	char buff[1024]={0};
 

	
 
	if(c->id < 0) {
 
		connect_complete(c->data, c->con, cond);
 
	} else {
 
		if(cond & YAHOO_INPUT_READ)
 
			ret = yahoo_read_ready(c->id, c->con, c->data);
 
		if(ret>0 && cond & YAHOO_INPUT_WRITE)
 
			ret = yahoo_write_ready(c->id, c->con, c->data);
 

	
 
		if(ret == -1)
 
			snprintf(buff, sizeof(buff), 
 
				"Yahoo read error (%d): %s", errno, strerror(errno));
 
		else if(ret == 0)
 
			snprintf(buff, sizeof(buff), 
 
				"Yahoo read error: Server closed socket");
 

	
 
		if(buff[0])
 
			print_message((buff));
 
	}
 
}
 

	
 
static int ext_yahoo_write(void *fd, char *buf, int len)
 
{
 
	struct _conn *c = fd;
 

	
 
	if (c->use_ssl)
 
		return SSL_write(c->ssl, buf, len);
 
	else
 
		return write(c->fd, buf, len);
 
}
 

	
 
static int ext_yahoo_read(void *fd, char *buf, int len)
 
{
 
	struct _conn *c = fd;
 

	
 
	if (c->use_ssl)
 
		return SSL_read(c->ssl, buf, len);
 
	else
 
		return read(c->fd, buf, len);
 
}
 

	
 
static void ext_yahoo_close(void *fd)
 
{
 
	struct _conn *c = fd;
 
	YList *l;
 

	
 
	if (c->use_ssl)
 
		SSL_free(c->ssl);
 

	
 
	close(c->fd);
 
	c->fd = 0;
 

	
 
	/* Remove all handlers */
 
	for (l = connections; l; l = y_list_next(l)) {
 
		struct conn_handler *h = l->data;
 

	
 
		if (h->con == c)
 
			h->remove = 1;
 
	}
 

	
 
	c->remove = 1;
 
}
 

	
 
static int ext_yahoo_connect_async(int id, const char *host, int port, 
 
		yahoo_connect_callback callback, void *data, int use_ssl)
 
{
 
	struct sockaddr_in serv_addr;
 
	static struct hostent *server;
 
	int servfd;
 
	struct connect_callback_data * ccd;
 
	int error;
 
	SSL *ssl = NULL;
 

	
 
	struct _conn *c;
 

	
 
	LOG(("Connecting to %s:%d", host, port));
 
	
 
	if(!(server = gethostbyname(host))) {
 
		errno=h_errno;
 
		return -1;
 
	}
 

	
 
	if((servfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
 
		return -1;
 
	}
 

	
 
	memset(&serv_addr, 0, sizeof(serv_addr));
 
	serv_addr.sin_family = AF_INET;
 
	memcpy(&serv_addr.sin_addr.s_addr, *server->h_addr_list, server->h_length);
 
	serv_addr.sin_port = htons(port);
 

	
 
	c = y_new0(struct _conn, 1);
 
	c->fd = servfd;
 
	c->use_ssl = use_ssl;
 

	
 
	error = connect(servfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
 

	
 
	LOG(("Trying to connect: fd:%d error:%d", servfd, error));
 
	if(!error) {
 
		LOG(("Connected"));
 
		if (use_ssl) {
 
			ssl = do_ssl_connect(servfd);
 

	
 
			if (!ssl) {
 
				LOG(("SSL Handshake Failed!"));
 
				ext_yahoo_close(c);
 

	
 
				callback(NULL, 0, data);
 
				return -1;
 
			}
 
		}
 

	
 
		c->ssl = ssl;
 
		fcntl(c->fd, F_SETFL, O_NONBLOCK);
 

	
 
		callback(c, 0, data);
 
		return 0;
 
	} else if(error == -1 && errno == EINPROGRESS) {
 
		ccd = calloc(1, sizeof(struct connect_callback_data));
 
		ccd->callback = callback;
 
		ccd->callback_data = data;
 
		ccd->id = id;
 

	
 
		ccd->tag = ext_yahoo_add_handler(-1, c, YAHOO_INPUT_WRITE, ccd);
 
		return ccd->tag;
 
	} else {
 
		if(error == -1)
 
			LOG(("Connection failure: %s", strerror(errno)));
 

	
 
		ext_yahoo_close(c);
 

	
 
		callback(NULL, errno, data);
 
		return -1;
 
	}
 
}
 
/*
 
 * Callback handling code ends here
 
 ***********************************/
 

	
 
static void process_commands(char *line)
 
{
 
	char *cmd, *to, *msg;
 

	
 
	char *tmp, *start;
 
	char *copy = strdup(line);
 
	int yid = 0;
 

	
 
	enum yahoo_status state;
 

	
 
	start = cmd = copy;
 
	tmp = strchr(copy, ' ');
 
	if(tmp) {
 
		*tmp = '\0';
 
		copy = tmp+1;
 
	} else {
 
		copy = NULL;
 
	}
 

	
 
	if(!strncasecmp(cmd, "MSG", strlen("MSG"))) {
 
		/* send a message */
 
		to = copy;
 
		tmp = strchr(copy, ' ');
 
		if(tmp) {
 
			*tmp = '\0';
 
			copy = tmp+1;
 
		}
 
		msg = copy;
 
		if(to && msg) {
 
			if(!strcmp(msg, "\a"))
 
				yahoo_send_im(ylad->id, NULL, to, "<ding>", 0,0);
 
			else {
 
				msg = y_str_to_utf8(msg);
 
				yahoo_send_im(ylad->id, NULL, to, msg, 1,0);
 
				FREE(msg)
 
			}
 
		}
 
	} else if(!strncasecmp(cmd, "CMS", strlen("CMS"))) {
 
		/* send a message */
 
		conf_room * cr;
 
		to = copy;
 
		tmp = strchr(copy, ' ');
 
		if(tmp) {
 
			*tmp = '\0';
 
			copy = tmp+1;
 
		}
 
		msg = copy;
 
		cr = find_conf_room_by_name_and_id(ylad->id, NULL, to);
 
		if(!cr) {
 
			print_message(("no such room: %s", copy));
 
			goto end_parse;
 
		}
 
		if(msg)
 
			yahoo_conference_message(ylad->id, NULL, cr->members, to, msg, 0);
 
	} else if(!strncasecmp(cmd, "CLS", strlen("CLS"))) {
 
		YList * l;
 
		if(copy) {
 
			conf_room * cr = find_conf_room_by_name_and_id(ylad->id, NULL, copy);
 
			if(!cr) {
 
				print_message(("no such room: %s", copy));
 
				goto end_parse;
 
			}
 
			print_message(("Room: %s", copy));
 
			for(l = cr->members; l; l=l->next) {
 
				print_message(("%s", (char *)l->data))
 
			}
 
		} else {
 
			print_message(("All Rooms:"));
 
			for(l = conferences; l; l=l->next) {
 
				conf_room * cr = l->data;
 
				print_message(("%s", cr->room_name));
 
			}
 
		}
 

	
 
	} else if(!strncasecmp(cmd, "CCR", strlen("CCR"))) {
 
		conf_room * cr = y_new0(conf_room, 1);
 
		while((tmp = strchr(copy, ' ')) != NULL) {
 
			*tmp = '\0';
 
			if(!cr->room_name)
 
				cr->room_name = strdup(copy);
 
			else
 
				cr->members = y_list_append(cr->members,
 
						strdup(copy));
 
			copy = tmp+1;
 
		}
 
		cr->members = y_list_append(cr->members, strdup(copy));
 

	
 
		if(!cr->room_name || !cr->members) {
 
			FREE(cr);
 
		} else {
 
			cr->id = ylad->id;
 
			cr->joined = 1;
 
			conferences = y_list_append(conferences, cr);
 
			yahoo_conference_invite(ylad->id, NULL, cr->members, cr->room_name, "Join my conference");
 
			cr->members = y_list_append(cr->members,strdup(ylad->yahoo_id));
 
		}
 
	} else if(!strncasecmp(cmd, "CIN", strlen("CIN"))) {
 
		conf_room * cr;
 
		char * room=copy;
 
		YList * l1, *l = NULL;
 

	
 
		while((tmp = strchr(copy, ' ')) != NULL) {
 
			*tmp = '\0';
 
			copy = tmp+1;
 
			l = y_list_append(l, copy);
 
		}
 

	
 
		cr = find_conf_room_by_name_and_id(ylad->id, NULL, room);
 
		if(!cr) {
 
			print_message(("no such room: %s", room));
 
			y_list_free(l);
 
			goto end_parse;
 
		}
 

	
 
		for(l1 = l; l1; l1=l1->next) {
 
			char * w = l1->data;
 
			yahoo_conference_addinvite(ylad->id, NULL, w, room, cr->members, "Join my conference");
 
			cr->members = y_list_append(cr->members, strdup(w));
 
		}
 
		y_list_free(l);
 

	
 
	} else if(!strncasecmp(cmd, "CLN", strlen("CLN"))) {
 
		conf_room * cr = find_conf_room_by_name_and_id(ylad->id, NULL, copy);
 
		YList * l;
 
		if(!cr) {
 
			print_message(("no such room: %s", copy));
 
			goto end_parse;
 
		}
 

	
 
		cr->joined = 1;
 
		for(l = cr->members; l; l=l->next) {
 
			char * w = l->data;
 
			if(!strcmp(w, ylad->yahoo_id))
 
				break;
 
		}
 
		if(!l)
 
			cr->members = y_list_append(cr->members, strdup(ylad->yahoo_id));
 
		yahoo_conference_logon(ylad->id, NULL, cr->members, copy);
 

	
 
	} else if(!strncasecmp(cmd, "CLF", strlen("CLF"))) {
 
		conf_room * cr = find_conf_room_by_name_and_id(ylad->id, NULL, copy);
 
		
 
		if(!cr) {
 
			print_message(("no such room: %s", copy));
 
			goto end_parse;
 
		}
 

	
 
		yahoo_conference_logoff(ylad->id, NULL, cr->members, copy);
 

	
 
		conferences = y_list_remove(conferences, cr);
 
		FREE(cr->room_name);
 
		FREE(cr->host);
 
		while(cr->members) {
 
			YList *n = cr->members->next;
 
			FREE(cr->members->data);
 
			FREE(cr->members);
 
			cr->members=n;
 
		}
 
		FREE(cr);
 

	
 
	} else if(!strncasecmp(cmd, "CDC", strlen("CDC"))) {
 
		conf_room * cr;
 
		char * room = copy;
 
		tmp = strchr(copy, ' ');
 
		if(tmp) {
 
			*tmp = '\0';
 
			copy = tmp+1;
 
			msg = copy;
 
		} else {
 
			msg = "Thanks, but no thanks!";
 
		}
 
		
 
		cr = find_conf_room_by_name_and_id(ylad->id, NULL, room);
 
		if(!cr) {
 
			print_message(("no such room: %s", room));
 
			goto end_parse;
 
		}
 

	
 
		yahoo_conference_decline(ylad->id, NULL, cr->members, room,msg);
 

	
 
		conferences = y_list_remove(conferences, cr);
 
		FREE(cr->room_name);
 
		FREE(cr->host);
 
		while(cr->members) {
 
			YList *n = cr->members->next;
 
			FREE(cr->members->data);
 
			FREE(cr->members);
 
			cr->members=n;
 
		}
 
		FREE(cr);
 

	
 

	
 
	} else if(!strncasecmp(cmd, "CHL", strlen("CHL"))) {
 
		int roomid;
 
		roomid = atoi(copy);
 
		yahoo_get_chatrooms(ylad->id, roomid);
 
	} else if(!strncasecmp(cmd, "CHJ", strlen("CHJ"))) {
 
		char *roomid, *roomname;
 
/* Linux, FreeBSD, Solaris:1 */
 
/* 1600326591 */
 
		roomid = copy;
 
		tmp = strchr(copy, ' ');
 
		if(tmp) {
 
			*tmp = '\0';
 
			copy = tmp+1;
 
		}
 
		roomname = copy;
 
		if(roomid && roomname) {
 
			yahoo_chat_logon(ylad->id, NULL, roomname, roomid);
 
		}
 

	
 
	} else if(!strncasecmp(cmd, "CHM", strlen("CHM"))) {
 
		char *msg, *roomname;
 
		roomname = copy;
 
		tmp = strstr(copy, "  ");
 
		if(tmp) {
 
			*tmp = '\0';
 
			copy = tmp+2;
 
		}
 
		msg = copy;
 
		if(roomname && msg) {
 
			yahoo_chat_message(ylad->id, NULL, roomname, msg, 1, 0);
 
		}
 

	
 
	} else if(!strncasecmp(cmd, "CHX", strlen("CHX"))) {
 
		yahoo_chat_logoff(ylad->id, NULL);
 
	} else if(!strncasecmp(cmd, "STA", strlen("STA"))) {
 
		if(isdigit(copy[0])) {
 
			state = (enum yahoo_status)atoi(copy);
 
			copy = strchr(copy, ' ');
 
			if(state == 99) {
 
				if(copy)
 
					msg = copy;
 
				else
 
					msg = "delta x * delta p too large";
 
			} else
 
				msg = NULL;
 
		} else {
 
			state = YAHOO_STATUS_CUSTOM;
 
			msg = copy;
 
		}
 

	
 
		yahoo_set_away(ylad->id, state, msg, 1);
 

	
 
	} else if(!strncasecmp(cmd, "OFF", strlen("OFF"))) {
 
		/* go offline */
 
		printf("Going offline\n");
 
		poll_loop=0;
 
	} else if(!strncasecmp(cmd, "IDS", strlen("IDS"))) {
 
		/* print identities */
 
		const YList * ids = yahoo_get_identities(ylad->id);
 
		printf("Identities: ");
 
		for(; ids; ids = ids->next)
 
			printf("%s, ", (char *)ids->data);
 
		printf("\n");
 
	} else if(!strncasecmp(cmd, "AID", strlen("AID"))) {
 
		/* activate identity */
 
		yahoo_set_identity_status(ylad->id, copy, 1);
 
	} else if(!strncasecmp(cmd, "DID", strlen("DID"))) {
 
		/* deactivate identity */
 
		yahoo_set_identity_status(ylad->id, copy, 0);
 
	} else if(!strncasecmp(cmd, "LST", strlen("LST"))) {
 
		YList * b = buddies;
 
		for(; b; b=b->next) {
 
			yahoo_account * ya = b->data;
 
			if(ya->status == YAHOO_STATUS_OFFLINE)
 
				continue;
 
			if(ya->msg)
 
				print_message(("%s (%s) is now %s", ya->name, ya->yahoo_id, 
 
							ya->msg))
 
			else
 
				print_message(("%s (%s) is now %s", ya->name, ya->yahoo_id, 
 
						yahoo_status_code(ya->status)))
 
		}
 
	} else if(!strncasecmp(cmd, "NAM", strlen("NAM"))) {
 
		struct yab * yab;
 
		
 
		to = copy;
 
		tmp = strchr(copy, ' ');
 
		if(tmp) {
 
			*tmp = '\0';
 
			copy = tmp+1;
 
		}
 
		yid = atoi(copy);
 

	
 
		tmp = strchr(copy, ' ');
 
		if(tmp) {
 
			*tmp = '\0';
 
			copy = tmp+1;
 
		}
 
		msg = copy;
 

	
 
		if(to && msg) {
 
			yab = y_new0(struct yab, 1);
 
			yab->id = to;
 
			yab->yid = yid;	/* Only do this if you have got it from the server */
 
			yab->nname = msg;
 
			yahoo_set_yab(ylad->id, yab);
 
			FREE(yab);
 
		}
 
	} else if(!strncasecmp(cmd, "WCAM", strlen("WCAM"))) {
 
		if (copy)
 
		{
 
			printf("Viewing webcam (%s)\n", copy);
 
			webcam_direction = YAHOO_WEBCAM_DOWNLOAD;
 
			yahoo_webcam_get_feed(ylad->id, copy);
 
		} else {
 
			printf("Starting webcam\n");
 
			webcam_direction = YAHOO_WEBCAM_UPLOAD;
 
			yahoo_webcam_get_feed(ylad->id, NULL);
 
		}
 
	} else if(!strncasecmp(cmd, "WINV", strlen("WINV"))) {
 
		printf("Inviting %s to view webcam\n", copy);
 
		yahoo_webcam_invite(ylad->id, copy);
 
	} else {
 
		fprintf(stderr, "Unknown command: %s\n", cmd);
 
	}
 

	
 
end_parse:
 
	FREE(start);
 
}
 

	
 
#ifndef _WIN32
 
static void local_input_callback(int source)
 
{
 
	char line[1024] = {0};
 
	int i;
 
	char c;
 
	i=0; c=0;
 
	do {
 
		if(read(source, &c, 1) <= 0)
 
			c='\0';
 
		if(c == '\r')
 
			continue;
 
		if(c == '\n')
 
			break;
 
		if(c == '\b') {
 
			if(!i)
 
				continue;
 
			c = '\0';
 
			i--;
 
		}
 
		if(c) {
 
			line[i++] = c;
 
			line[i]='\0';
 
		}
 
	} while(i<1023 && c != '\n');
 

	
 
	if(line[0])
 
		process_commands(line);
 
}
 
#else
 
#include <conio.h>
 
static void local_input_callback(char c)
 
{
 
	static char line[1024] = {0};
 
	static int line_length = 0;
 

	
 
	if (c == '\b' || (int)c == 127) {
 
		if (line_length > 0) {
 
			_cputs("\b \b");
 
			line_length--;
 
		}
 
		return;
 
	}
 

	
 
	if (c == '\n' || c == '\r' || c == 3) {
 
		_cputs("\n");
 
		line[line_length] = 0;
 
		process_commands(line);
 
		line_length = 0;
 
		line[0] = 0;
 
		return;
 
	}
 

	
 
	_putch(c);
 
	line[line_length++] = c;
 
}
 
#endif
 

	
 
int main(int argc, char * argv[])
 
{
 
	int status;
 
	int log_level;
 
	int lfd=0;
 

	
 
	fd_set inp, outp;
 
	struct timeval tv;
 

	
 
#ifndef _WIN32
 
	int fd_stdin = fileno(stdin);
 
#endif
 
	YList *l=connections;
 

	
 
#ifdef _WIN32
 
	WSADATA wsa;	
 
	if (WSAStartup(MAKEWORD(2,2), &wsa))
 
		return -1;
 
#endif
 

	
 
	ylad = y_new0(yahoo_local_account, 1);
 

	
 
	local_host = strdup(get_local_addresses());
 

	
 
	printf("Yahoo Id: ");
 
	scanf("%s", ylad->yahoo_id);
 
	printf("Password: ");
 
#ifdef _WIN32
 
	scanf("%s", ylad->password);
 
#else
 
	{
 
		tcflag_t oflags;
 
		struct termios term;
 
		tcgetattr(fd_stdin, &term);
 
		oflags = term.c_lflag;
 
		term.c_lflag = oflags & ~(ECHO | ECHOK | ICANON);
 
		term.c_cc[VTIME] = 1;
 
		tcsetattr(fd_stdin, TCSANOW, &term);
 
		
 
		scanf("%s", ylad->password);
 

	
 
		term.c_lflag = oflags;
 
		term.c_cc[VTIME] = 0;
 
		tcsetattr(fd_stdin, TCSANOW, &term);
 
	}
 
	printf("\n");
 
#endif
 

	
 
	printf("Initial Status: ");
 
	scanf("%d", &status);
 

	
 
	printf("Log Level: ");
 
	scanf("%d", &log_level);
 
	do_yahoo_debug=log_level;
 

	
 
	register_callbacks();
 
	yahoo_set_log_level(log_level);
 

	
 
	ext_yahoo_login(ylad, status);
 

	
 
	while(poll_loop) {
 
		FD_ZERO(&inp);
 
		FD_ZERO(&outp);
 
#ifndef _WIN32
 
		FD_SET(fd_stdin, &inp);
 
		tv.tv_sec=1;
 
		tv.tv_usec=0;
 
#else
 
		tv.tv_sec=0;
 
		tv.tv_usec=1E4;
 
#endif
 
		lfd=0;
 

	
 
		for(l=connections; l; ) {
 
			struct conn_handler *c = l->data;
 
			if(c->remove) {
 
				YList *n = y_list_next(l);
 
				LOG(("Removing id:%d fd:%d", c->id, c->con->fd));
 
				connections = y_list_remove_link(connections, l);
 
				y_list_free_1(l);
 
				FREE(c);
 
				l=n;
 
			} else {
 
				if(c->cond & YAHOO_INPUT_READ)
 
					FD_SET(c->con->fd, &inp);
 
				if(c->cond & YAHOO_INPUT_WRITE)
 
					FD_SET(c->con->fd, &outp);
 
				if(lfd < c->con->fd)
 
					lfd = c->con->fd;
 
				l = y_list_next(l);
 
			}
 
		}
 

	
 
		select(lfd + 1, &inp, &outp, NULL, &tv);
 
		time(&curTime);
 

	
 
#ifndef _WIN32
 
		if(FD_ISSET(fd_stdin, &inp))	local_input_callback(0);
 
#else
 
		if (_kbhit()) local_input_callback(_getch());
 
#endif
 

	
 
		for(l = connections; l; l = y_list_next(l)) {
 
			struct conn_handler *c = l->data;
 
			if(c->con->remove) {
 
				FREE(c->con);
 
				c->con = NULL;
 
				continue;
 
			}
 
			if(c->remove)
 
				continue;
 
			if(FD_ISSET(c->con->fd, &inp))
 
				yahoo_callback(c, YAHOO_INPUT_READ);
 
			if(FD_ISSET(c->con->fd, &outp))
 
				yahoo_callback(c, YAHOO_INPUT_WRITE);
 
		}
 

	
 
		if(expired(pingTimer))		yahoo_ping_timeout_callback();
 
		if(expired(webcamTimer))	yahoo_webcam_timeout_callback(webcam_id);
 
	}
 
	LOG(("Exited loop"));
 

	
 
	while(connections) {
 
		YList *tmp = connections;
 
		struct conn_handler *c = connections->data;
 
		FREE(c);
 
		connections = y_list_remove_link(connections, connections);
 
		y_list_free_1(tmp);
 
	}
 

	
 
	yahoo_logout();
 

	
 
	FREE(ylad);
 

	
 
#ifdef _WIN32
 
	WSACleanup();
 
#endif
 
	return 0;
 
}
 

	
 
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)
 
{
 
	LOG(("Got a File transfer request (%s, %ld bytes) from %s", fname, fesize, who));
 
}
 

	
 
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)
 
{ 
 
 	LOG(("got chat logout for %s", me));
 
}
 

	
 
static void ext_yahoo_chat_yahooerror(int id, const char *me)
 
{ 
 
 	LOG(("got chat error for %s", me));
 
}
 

	
 
static void ext_yahoo_got_ping(int id, const char *errormsg)
 
{ 
 
 	LOG(("got ping errormsg %s", errormsg));
 
}
 

	
 
static void ext_yahoo_got_search_result(int id, int found, int start, int total, YList *contacts)
 
{
 
	LOG(("got search result"));
 
}
 

	
 
static void ext_yahoo_got_buddyicon_checksum(int id, const char *a, const char *b, int checksum)
 
{
 
	LOG(("got buddy icon 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 *a, const char *b, const char *c, int checksum)
 
{
 
	LOG(("got buddy icon"));
 
}
 

	
 
static void ext_yahoo_buddyicon_uploaded(int id, const char *url)
 
{
 
	LOG(("buddy icon uploaded"));
 
}
 

	
 
static void ext_yahoo_got_buddyicon_request(int id, const char *me, const char *who)
 
{
 
	LOG(("got buddy icon request from %s",who));
 
}
 

	
 
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);
 
}
 

	
backends/libyahoo2/yahoo/crypt.c
Show inline comments
 
new file 100644
 
/* 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;
 
}

Changeset was too big and was cut off... Show full diff anyway

0 comments (0 inline, 0 general)