Example #1
0
static void
dologin_named(const char *name)
{
	PurpleAccount *account;
	char **names;
	int i;

	if (name != NULL) { /* list of names given */
		names = g_strsplit(name, ",", 64);
		for (i = 0; names[i] != NULL; i++) {
			account = purple_accounts_find(names[i], NULL);
			if (account != NULL) { /* found a user */
				purple_account_set_enabled(account, PIDGIN_UI, TRUE);
			}
		}
		g_strfreev(names);
	} else { /* no name given, use the first account */
		GList *accounts;

		accounts = purple_accounts_get_all();
		if (accounts != NULL)
		{
			account = (PurpleAccount *)accounts->data;
			purple_account_set_enabled(account, PIDGIN_UI, TRUE);
		}
	}
}
Example #2
0
static void
pidgin_connection_report_disconnect_reason (PurpleConnection *gc,
                                            PurpleConnectionError reason,
                                            const char *text)
{
	PurpleAccount *account = NULL;
	PidginAutoRecon *info;

	account = purple_connection_get_account(gc);
	info = g_hash_table_lookup(auto_reconns, account);

	if (!purple_connection_error_is_fatal (reason)) {
		if (info == NULL) {
			info = g_new0(PidginAutoRecon, 1);
			g_hash_table_insert(auto_reconns, account, info);
			info->delay = g_random_int_range(INITIAL_RECON_DELAY_MIN, INITIAL_RECON_DELAY_MAX);
		} else {
			info->delay = MIN(2 * info->delay, MAX_RECON_DELAY);
			if (info->timeout != 0)
				g_source_remove(info->timeout);
		}
		info->timeout = g_timeout_add(info->delay, do_signon, account);
	} else {
		if (info != NULL)
			g_hash_table_remove(auto_reconns, account);

		purple_account_set_enabled(account, PIDGIN_UI, FALSE);
	}
}
Example #3
0
static void purple_login(account_t *acc)
{
	struct im_connection *ic = imcb_new(acc);
	struct purple_data *pd;

	if ((local_bee != NULL && local_bee != acc->bee) ||
	    (global.conf->runmode == RUNMODE_DAEMON && !getenv("BITLBEE_DEBUG"))) {
		imcb_error(ic,  "Daemon mode detected. Do *not* try to use libpurple in daemon mode! "
		           "Please use inetd or ForkDaemon mode instead.");
		imc_logout(ic, FALSE);
		return;
	}
	local_bee = acc->bee;

	/* For now this is needed in the _connected() handlers if using
	   GLib event handling, to make sure we're not handling events
	   on dead connections. */
	purple_connections = g_slist_prepend(purple_connections, ic);

	ic->proto_data = pd = g_new0(struct purple_data, 1);
	pd->account = purple_account_new(acc->user, (char *) acc->prpl->data);
	pd->input_requests = g_hash_table_new_full(g_direct_hash, g_direct_equal,
	                                           NULL, g_free);
	pd->next_request_id = 0;
	purple_account_set_password(pd->account, acc->pass);
	purple_sync_settings(acc, pd->account);

	purple_account_set_enabled(pd->account, "BitlBee", TRUE);

	if (set_getbool(&acc->set, "mail_notifications") && set_getstr(&acc->set, "mail_notifications_handle")) {
		imcb_add_buddy(ic, set_getstr(&acc->set, "mail_notifications_handle"), NULL);
	}
}
Example #4
0
static void purple_login( account_t *acc )
{
	struct im_connection *ic = imcb_new( acc );
	PurpleAccount *pa;
	
	if( ( local_bee != NULL && local_bee != acc->bee ) ||
	    ( global.conf->runmode == RUNMODE_DAEMON && !getenv( "BITLBEE_DEBUG" ) ) )
	{
		imcb_error( ic,  "Daemon mode detected. Do *not* try to use libpurple in daemon mode! "
		                 "Please use inetd or ForkDaemon mode instead." );
		imc_logout( ic, FALSE );
		return;
	}
	local_bee = acc->bee;
	
	/* For now this is needed in the _connected() handlers if using
	   GLib event handling, to make sure we're not handling events
	   on dead connections. */
	purple_connections = g_slist_prepend( purple_connections, ic );
	
	ic->proto_data = pa = purple_account_new( acc->user, (char*) acc->prpl->data );
	purple_account_set_password( pa, acc->pass );
	purple_sync_settings( acc, pa );
	
	purple_account_set_enabled( pa, "BitlBee", TRUE );
}
static int account_set_enabled(LuaState *L)/*{{{*/
{
    PurpleAccount **account = ms_lua_checkclass(L, "purple.account", 1);
    gboolean enabled        = ms_lua_checkboolean(L, 2);
    purple_account_set_enabled(*account, "moonshine", enabled);
    return 0;
}/*}}}*/
Example #6
0
File: basic.c Project: ghetzel/zee
int main(int argc, char *argv[])
{

	GMainLoop *loop = g_main_loop_new(NULL, FALSE);

	/* libpurple's built-in DNS resolution forks processes to perform
	 * blocking lookups without blocking the main process.  It does not
	 * handle SIGCHLD itself, so if the UI does not you quickly get an army
	 * of zombie subprocesses marching around.
	 */
	signal(SIGCHLD, SIG_IGN);

	init_libpurple();

	printf("libpurple initialized. Running version %s.\n", purple_core_get_version()); //I like to see the version number

	connect_to_signals();

	PurpleAccount *account = purple_account_new(PACCOUNT_NAME, "prpl-aim"); //this could be prpl-aim, prpl-yahoo, prpl-msn, prpl-icq, etc.
	purple_account_set_password(account, PACCOUNT_PASS);

	purple_accounts_add(account);
	purple_account_set_enabled(account, UI_ID, TRUE);

	g_main_loop_run(loop);

	return 0;

}
Example #7
0
PurpleAccount *mimoc_account_new(char *name, char *protocoll, _Bool enabled)
{
	PurpleAccount *account = purple_account_new(name, protocoll);
	purple_accounts_add(account);
	purple_account_set_enabled(account, UI_ID, enabled);
	return account;
}
Example #8
0
int main(int argc, char *argv[])
{

	if(argc < 4)
	{
		printf("Usage: %s [Gtalk username] [password] [recipient address] [message]\n", argv[0]);
		return 1;
	}	
	input_address = argv[3];
	input_message = argv[4];
	GMainLoop *loop = g_main_loop_new(NULL, FALSE);

	/* libpurple's built-in DNS resolution forks processes to perform
	 * blocking lookups without blocking the main process.  It does not
	 * handle SIGCHLD itself, so if the UI does not you quickly get an army
	 * of zombie subprocesses marching around.
	 */
	signal(SIGCHLD, SIG_IGN);

	init_libpurple();

	connect_to_signals();

	PurpleAccount *account = purple_account_new(argv[1], "prpl-jabber");
	purple_account_set_password(account, argv[2]);

	purple_accounts_add(account);
	purple_account_set_enabled(account, UI_ID, TRUE);

	g_main_loop_run(loop);

	return 0;

}
Example #9
0
static void purple_logout( struct im_connection *ic )
{
	PurpleAccount *pa = ic->proto_data;
	
	purple_account_set_enabled( pa, "BitlBee", FALSE );
	purple_connections = g_slist_remove( purple_connections, ic );
	purple_accounts_remove( pa );
}
static void setup_integration (void)
{
  init_libpurple();

  PurpleAccount* prpl_account = purple_account_new("test_user", "yammer");
  purple_account_set_enabled(prpl_account, "test_runner", TRUE);
  account = yammer_account_new(prpl_account);
}
Example #11
0
static void
auth_no_pass_cb(PurpleConnection *gc, PurpleRequestFields *fields)
{
	/* TODO: the password prompt dialog doesn't get disposed if the account disconnects */
	PURPLE_ASSERT_CONNECTION_IS_VALID(gc);

	/* Disable the account as the user has cancelled connecting */
	purple_account_set_enabled(purple_connection_get_account(gc), purple_core_get_ui(), FALSE);
}
Example #12
0
void AccountWindow::BoolOption::onToggle(CheckBox& /*activator*/,
    bool new_state)
{
  if (type == TYPE_REMEMBER_PASSWORD)
    purple_account_set_remember_password(account, new_state);
  else if (type == TYPE_ENABLE_ACCOUNT)
    purple_account_set_enabled(account, PACKAGE_NAME, new_state);
  else
    purple_account_set_bool(account,
        purple_account_option_get_setting(option), new_state);
}
Example #13
0
QuetzalAccount::QuetzalAccount(const QString &id, QuetzalProtocol *protocol) : Account(id, protocol)
{
	Q_ASSERT(!"Shouldn't use this constructor");
	m_isLoading = false;
	Config cfg = config();
	QString purpleId = id;
	if (protocol->id() == QLatin1String("irc")) {
		purpleId = cfg.value(QLatin1String("nicks"), QStringList()).value(0);
		purpleId += QLatin1Char('@');
		int size = cfg.beginArray("servers");
		if (size == 0) {
			qCritical("Invalid irc account without server info: \"%s\"", qPrintable(id));
			deleteLater();
			return;
		}
		cfg.setArrayIndex(0);
		purpleId += cfg.value(QLatin1String("hostName"), QString());
		cfg.endArray();
	}
	m_account = purple_account_new(purpleId.toUtf8(), protocol->plugin()->info->id);
	m_account->ui_data = this;
	fillStatusActions();
	setContactsFactory(new QuetzalContactsFactory(this));
//	if (PURPLE_PLUGIN_PROTOCOL_INFO(m_account->gc->prpl)->chat_info != NULL) {
//		addAction((new ActionGenerator(QIcon(), QT_TRANSLATE_NOOP("Quetzal", "Join groupchat"), this, SLOT(showJoinGroupChat())))->setType(1));
//	}
	debug() << "created!" << this << m_account->protocol_id;
	// Hack for anti-auto-connect
	for (GList *it = purple_presence_get_statuses(m_account->presence); it; it = it->next) {
		PurpleStatus *status = reinterpret_cast<PurpleStatus *>(it->data);
//		debug() << purple_status_type_get_primitive(purple_status_get_type(status))
//				<< !!purple_status_is_online(status)
//				<< purple_status_get_id(status)
//				<< purple_status_get_name(status);
		if (!purple_status_is_online(status)) {
			purple_presence_set_status_active(m_account->presence, purple_status_get_id(status), TRUE);
			break;
		}
	}


	m_isLoading = true;
	load(cfg);
	m_isLoading = false;
//	if (protocol->id() == "jabber" && id.contains("qutim.org")) {
	if (!purple_account_get_enabled(m_account, "qutim"))
		purple_account_set_enabled(m_account, "qutim", TRUE);

//		purple_account_connect(m_account);
//	} else
//		purple_account_set_enabled(m_account, "qutim", FALSE);
}
Example #14
0
void client_enable_account(PurpleAccount *account) {

	if ((account) && !purple_account_get_enabled(account, UI_ID)) {
		LM_DBG("account %s disabled, enabling...\n", account->username);
		purple_account_set_enabled(account, UI_ID, TRUE);
	}

	if ((account) && purple_account_is_disconnected(account)) {
		LM_DBG("account %s disconnected, reconnecting...\n", account->username);
		purple_account_connect(account);
		LM_DBG("account %s connection called\n", account->username);
	}
}
Example #15
0
QuetzalAccount::QuetzalAccount(PurpleAccount *account, QuetzalProtocol *protocol) :
		Account(quetzal_fix_id(protocol, account->username), protocol)
{
	m_isLoading = false;
	m_account = account;
	m_account->ui_data = this;
	fillStatusActions();
//	setContactsFactory(new QuetzalContactsFactory(this));
	if (!purple_account_get_enabled(m_account, "qutim"))
		purple_account_set_enabled(m_account, "qutim", TRUE);
//	purple_accounts_add(account);
	save();
}
Example #16
0
static VALUE login(VALUE self, VALUE protocol, VALUE username, VALUE password)
{
  PurpleAccount* account = purple_account_new(RSTRING_PTR(username), RSTRING_PTR(protocol));
  if (NULL == account || NULL == account->presence) {
    rb_raise(rb_eRuntimeError, "No able to create account: %s", RSTRING_PTR(protocol));
  }
  purple_account_set_password(account, RSTRING_PTR(password));
  purple_account_set_remember_password(account, TRUE);
  purple_account_set_enabled(account, UI_ID, TRUE);
  PurpleSavedStatus *status = purple_savedstatus_new(NULL, PURPLE_STATUS_AVAILABLE);
	purple_savedstatus_activate(status);
	purple_accounts_add(account);
	return Data_Wrap_Struct(cAccount, NULL, NULL, account);
}
Example #17
0
static void purple_logout(struct im_connection *ic)
{
	struct purple_data *pd = ic->proto_data;

	if (!pd) {
		return;
	}

	purple_account_set_enabled(pd->account, "BitlBee", FALSE);
	purple_connections = g_slist_remove(purple_connections, ic);
	purple_accounts_remove(pd->account);
	g_hash_table_destroy(pd->input_requests);
	g_free(pd);
}
Example #18
0
static void
auth_no_pass_cb(PurpleConnection *gc, PurpleRequestFields *fields)
{
	PurpleAccount *account;
	JabberStream *js;

	/* The password prompt dialog doesn't get disposed if the account disconnects */
	if (!PURPLE_CONNECTION_IS_VALID(gc))
		return;

	account = purple_connection_get_account(gc);

	/* Disable the account as the user has cancelled connecting */
	purple_account_set_enabled(account, purple_core_get_ui(), FALSE);
}
static void
pb_oauth_set_access_token_cb(gpointer data, const gchar *access_token)
{
	PurpleAccount *account = data;
	gchar *real_access_token;
	const gchar *access_token_start;
	const gchar *access_token_end;
	gchar *strtmp;
	
	if (!access_token || !(*access_token)) {
		return;
	}
	
	if((access_token_start = strstr(access_token, "access_token=")))
	{
		access_token_start += 13;
		access_token_end = strchr(access_token_start, '&');
		if (access_token_end)
			real_access_token = g_strndup(access_token_start, access_token_end - access_token_start);
		else
			real_access_token = g_strdup(access_token_start);
		
		strtmp = g_strdup(purple_url_decode(real_access_token));
		g_free(real_access_token);
		real_access_token = strtmp;
	} else {
		real_access_token = g_strdup(access_token);
	}
	
	if (real_access_token && *real_access_token) {
		purple_account_set_remember_password(account, TRUE);
		purple_account_set_password(account, real_access_token);
		
		purple_account_set_enabled(account, purple_core_get_ui(), TRUE);
		purple_account_connect(account);
	}
	
	g_free(real_access_token);
}
Example #20
0
void AccountCollector::collectNow(PurpleAccount *account, bool remove) {
	if (account->ui_data == NULL) {
		Log("AccountCollector","freeing account " << purple_account_get_username(account));
		
		if (remove)
			g_hash_table_remove(m_accounts, purple_account_get_username(account));

		purple_account_set_enabled(account, purple_core_get_ui(), FALSE);

		purple_notify_close_with_handle(account);
		purple_request_close_with_handle(account);

		purple_accounts_remove(account);

		GSList *buddies = purple_find_buddies(account, NULL);
		while(buddies) {
			PurpleBuddy *b = (PurpleBuddy *) buddies->data;
			purple_blist_remove_buddy(b);
			buddies = g_slist_delete_link(buddies, buddies);
		}

		/* Remove any open conversation for this account */
		for (GList *it = purple_get_conversations(); it; ) {
			PurpleConversation *conv = (PurpleConversation *) it->data;
			it = it->next;
			if (purple_conversation_get_account(conv) == account)
				purple_conversation_destroy(conv);
		}

		/* Remove this account's pounces */
 			// purple_pounce_destroy_all_by_account(account);

		/* This will cause the deletion of an old buddy icon. */
		purple_buddy_icons_set_account_icon(account, NULL, 0);

		purple_account_destroy(account);
// 		VALGRIND_DO_LEAK_CHECK;
	}
}
Example #21
0
void IMInvoker::invoke(void *userdata, const std::string event) {
	_accountMutex.lock();

	EventContext* ctx = (EventContext*)userdata;
	IMInvoker* instance = ctx->instance;

	std::string username;
	Event::getParam(ctx->invokeReq.params, "username", username);
	std::string protocolId;
	Event::getParam(ctx->invokeReq.params, "protocol", protocolId);
	std::string password;
	Event::getParam(ctx->invokeReq.params, "password", password);

	instance->_account = purple_account_new(username.c_str(), protocolId.c_str());
	_accountInstances[instance->_account] = instance;

#if LIBPURPLE_VERSION_MAJOR >= 3
	purple_account_set_password(instance->_account, password.c_str(), NULL, NULL);
#else
	purple_account_set_password(instance->_account, password.c_str());
#endif
	purple_account_set_enabled(instance->_account, "uscxml", true);

	GSList* buddies = purple_blist_get_buddies();
	GSList *cur;
	for (cur = buddies; cur; cur = cur->next) {
		std::string buddyName = purple_buddy_get_name((PurpleBuddy *)cur->data);
		Data buddyData = buddyToData((PurpleBuddy *)cur->data);
		instance->_dataModelVars.compound["buddies"].compound[buddyName] = buddyData;
	}
	g_slist_free(buddies);



	delete(ctx);
	_accountMutex.unlock();
}
Example #22
0
int parse(char*toParse, char*ret_buffer, char**uid)
{
  char command = -1,
       *pCur,
       *pPrev;

  int ix,
      Bound = TK__LAST;

  taim_session *ses;

  pCur = toParse;

  for(ix = 0; ix < Bound; ix++)
  {
    if(!strncmp(pCur, g_commands[ix], strlen(g_commands[ix])))
    {
      command = ix;
      pCur += strlen(g_commands[ix]);
      break;
    }
  }

  switch(command) {
    case TK_UID:
      if(*pCur == ' ') {
        pCur++;
        pPrev = pCur;
        while(*pCur > 32) {
          pCur ++;
        }
        *uid = (char*) malloc(pCur - pPrev);
        memcpy(*uid, pPrev, pCur - pPrev);
        (*uid)[pCur - pPrev] = 0;
      } else {
        *uid = 0;

        do {
          if(*uid != 0)
          {
            free(*uid);
          }
          *uid = (char*) malloc(KEY_LENGTH + 1);
          memcpy(*uid, generate_uid(), KEY_LENGTH);
        } while(uid_addsession(*uid) == 0);
      }

      memcpy(ret_buffer, *uid, strlen(*uid));
      sprintf(ret_buffer + strlen(*uid) + 1, "\n");
      return RET_NODATA;
      break;

    case TK_USER:
      pCur++;

      pPrev = pCur;
      while(*pCur > 32 ) {
        pCur++;
      }
      *uid = (char*)malloc(pCur - pPrev + 1);
      memcpy(*uid, pPrev, pCur - pPrev);
      (*uid)[pCur - pPrev] = 0;
      ses = uid_find(*uid);
      pCur ++;

      {
        char *username = pCur;

        for(	ix = 0;
            username[ix] > ' ';
            ix++);

        username[ix] = 0;

        GList *iter = purple_plugins_get_protocols();
        PurplePlugin *plugin = iter->data;
        PurplePluginInfo *info = plugin->info;
        printf("<%x>", (unsigned int)ses);
        fflush(0);

        if(ses->pses->account == 0) {
          taim_new_account(ses);
        }
        d(username);
        ses->pses->account->account = purple_account_new(username, info->id);
      }
      return RET_NODATA;
      break;

    case TK_PASS:
      pCur++;

      pPrev = pCur;
      while(*pCur > 32 ) {
        pCur++;
      }
      *uid = (char*)malloc(pCur - pPrev + 1);
      memcpy(*uid, pPrev, pCur - pPrev);
      (*uid)[pCur - pPrev] = 0;
      pCur ++;
      ses = uid_find(*uid);

      {
        PurpleSavedStatus *status;

        char	*password = pCur,
              hash[20];

        for(ix = 0; password[ix] > ' '; ix++);

        password[ix] = 0;

        if(ses->pses->account->hash_have == 1) {
          // See if the hashes match
          if(!memcmp(SHA1(password, strlen(password), hash), ses->pses->account->hash, 20)) {
            // If so, then bond the stuff
          }
          else
            // Otherwise, try to auth anyway
          {
            strcpy(ses->pses->account->password_try, password);
          }
          purple_account_set_password(ses->pses->account->account, password);
          purple_account_set_enabled(ses->pses->account->account, UI_ID, TRUE);
          // Either way, this password is replaced with the new one
        } else {
          strcpy(ses->pses->account->password_try, password);
          purple_account_set_password(ses->pses->account->account, password);
          purple_account_set_enabled(ses->pses->account->account, UI_ID, TRUE);
        }

        // Now, to connect the account(s), create a status and activate it. 
        status = purple_savedstatus_new(NULL, PURPLE_STATUS_AVAILABLE);
        purple_savedstatus_activate(status);
        pthread_mutex_unlock(&g_mutex_init);
      }	
      return RET_NODATA;
      break;

    case TK_GET:
      pCur++;

      pPrev = pCur;
      while(*pCur > 32 ) {
        pCur++;
      }

      *uid = (char*)malloc(pCur - pPrev + 1);
      memcpy(*uid, pPrev, pCur - pPrev);
      (*uid)[pCur - pPrev] = 0;
      pCur ++;

      if((*uid)[0]) {
        d(*uid);
        drecurse(g_blist->root, *uid);
        return RET_DATA;
      } else {
        return RET_NODATA;
      }
      break;

    case TK_SEND:
      pCur++;

      pPrev = pCur;
      while(*pCur > 32 ) {
        pCur++;
      }

      *uid = (char*)malloc(pCur - pPrev + 1);
      memcpy(*uid, pPrev, pCur - pPrev);
      (*uid)[pCur - pPrev] = 0;
      pCur ++;

      pCur[strlen(pCur) - 1] = 0;
      taim_send(pCur, *uid, ret_buffer);
      return RET_NODATA;
      break;

    case TK_QUIT:
      do_exit();
      break;

    default:
      return RET_ERROR;
      // unknown command
      break;
  }
  return RET_ERROR;
}
Example #23
0
static void signed_off(PurpleConnection *gc) {
	LM_DBG("signed-off with <%s>\n", gc->account->username);
	purple_account_set_enabled(gc->account, UI_ID, FALSE);
}
Example #24
0
int main(int argc, char *argv[])
{
	GList *iter;
	int i, num;
	GList *names = NULL;
	const char *prpl;
	char name[128];
	char *password;
	GMainLoop *loop = g_main_loop_new(NULL, FALSE);
	PurpleAccount *account;
	PurpleSavedStatus *status;
	char *res;

#ifndef _WIN32
	/* libpurple's built-in DNS resolution forks processes to perform
	 * blocking lookups without blocking the main process.  It does not
	 * handle SIGCHLD itself, so if the UI does not you quickly get an army
	 * of zombie subprocesses marching around.
	 */
	signal(SIGCHLD, SIG_IGN);
#endif

	init_libpurple();

	printf("libpurple initialized.\n");

	iter = purple_plugins_get_protocols();
	for (i = 0; iter; iter = iter->next) {
		PurplePlugin *plugin = iter->data;
		PurplePluginInfo *info = plugin->info;
		if (info && info->name) {
			printf("\t%d: %s\n", i++, info->name);
			names = g_list_append(names, info->id);
		}
	}
	printf("Select the protocol [0-%d]: ", i-1);
	res = fgets(name, sizeof(name), stdin);
	if (!res) {
		fprintf(stderr, "Failed to gets protocol selection.");
		abort();
	}
	sscanf(name, "%d", &num);
	prpl = g_list_nth_data(names, num);

	printf("Username: "******"Failed to read user name.");
		abort();
	}
	name[strlen(name) - 1] = 0;  /* strip the \n at the end */


	/* Create the account */
	account = purple_account_new(name, prpl);

	/* Get the password for the account */
	password = getpass("Password: ");
	purple_account_set_password(account, password);

	/* It's necessary to enable the account first. */
	purple_account_set_enabled(account, UI_ID, TRUE);

	/* Now, to connect the account(s), create a status and activate it. */
	status = purple_savedstatus_new(NULL, PURPLE_STATUS_AVAILABLE);
	purple_savedstatus_activate(status);

	connect_to_signals_for_demonstration_purposes_only();

	g_main_loop_run(loop);

	return 0;
}
Example #25
0
int main(int argc, char *argv[])
#endif
{
	gboolean opt_force_online = FALSE;
	gboolean opt_help = FALSE;
	gboolean opt_login = FALSE;
	gboolean opt_nologin = FALSE;
	gboolean opt_version = FALSE;
	gboolean opt_si = TRUE;     /* Check for single instance? */
	char *opt_config_dir_arg = NULL;
	char *opt_login_arg = NULL;
	char *opt_session_arg = NULL;
	char *search_path;
	GList *accounts;
#ifdef HAVE_SIGNAL_H
	int sig_indx;	/* for setting up signal catching */
	sigset_t sigset;
	RETSIGTYPE (*prev_sig_disp)(int);
	char errmsg[BUFSIZ];
	GIOChannel *signal_channel;
	GIOStatus signal_status;
	guint signal_channel_watcher;
#ifndef DEBUG
	char *segfault_message_tmp;
#endif
	GError *error;
#endif
	int opt;
	gboolean gui_check;
	gboolean debug_enabled;
	gboolean migration_failed = FALSE;
	GList *active_accounts;
	struct stat st;

	struct option long_options[] = {
		{"config",       required_argument, NULL, 'c'},
		{"debug",        no_argument,       NULL, 'd'},
		{"force-online", no_argument,       NULL, 'f'},
		{"help",         no_argument,       NULL, 'h'},
		{"login",        optional_argument, NULL, 'l'},
		{"multiple",     no_argument,       NULL, 'm'},
		{"nologin",      no_argument,       NULL, 'n'},
		{"session",      required_argument, NULL, 's'},
		{"version",      no_argument,       NULL, 'v'},
		{"display",      required_argument, NULL, 'D'},
		{"sync",         no_argument,       NULL, 'S'},
		{0, 0, 0, 0}
	};

#ifdef DEBUG
	debug_enabled = TRUE;
#else
	debug_enabled = FALSE;
#endif

	/* Initialize GThread before calling any Glib or GTK+ functions. */
	g_thread_init(NULL);

	g_set_prgname("Pidgin");

#ifdef ENABLE_NLS
	bindtextdomain(PACKAGE, LOCALEDIR);
	bind_textdomain_codeset(PACKAGE, "UTF-8");
	textdomain(PACKAGE);
#endif

#ifdef HAVE_SETLOCALE
	/* Locale initialization is not complete here.  See gtk_init_check() */
	setlocale(LC_ALL, "");
#endif

#ifdef HAVE_SIGNAL_H

#ifndef DEBUG
		/* We translate this here in case the crash breaks gettext. */
		segfault_message_tmp = g_strdup_printf(_(
			"%s %s has segfaulted and attempted to dump a core file.\n"
			"This is a bug in the software and has happened through\n"
			"no fault of your own.\n\n"
			"If you can reproduce the crash, please notify the developers\n"
			"by reporting a bug at:\n"
			"%ssimpleticket/\n\n"
			"Please make sure to specify what you were doing at the time\n"
			"and post the backtrace from the core file.  If you do not know\n"
			"how to get the backtrace, please read the instructions at\n"
			"%swiki/GetABacktrace\n"),
			PIDGIN_NAME, DISPLAY_VERSION, PURPLE_DEVEL_WEBSITE, PURPLE_DEVEL_WEBSITE
		);

		/* we have to convert the message (UTF-8 to console
		   charset) early because after a segmentation fault
		   it's not a good practice to allocate memory */
		error = NULL;
		segfault_message = g_locale_from_utf8(segfault_message_tmp,
						      -1, NULL, NULL, &error);
		if (segfault_message != NULL) {
			g_free(segfault_message_tmp);
		}
		else {
			/* use 'segfault_message_tmp' (UTF-8) as a fallback */
			g_warning("%s\n", error->message);
			g_error_free(error);
			segfault_message = segfault_message_tmp;
		}
#else
		/* Don't mark this for translation. */
		segfault_message = g_strdup(
			"Hi, user.  We need to talk.\n"
			"I think something's gone wrong here.  It's probably my fault.\n"
			"No, really, it's not you... it's me... no no no, I think we get along well\n"
			"it's just that.... well, I want to see other people.  I... what?!?  NO!  I \n"
			"haven't been cheating on you!!  How many times do you want me to tell you?!  And\n"
			"for the last time, it's just a rash!\n"
		);
#endif

	/*
	 * Create a socket pair for receiving unix signals from a signal
	 * handler.
	 */
	if (socketpair(AF_UNIX, SOCK_STREAM, 0, signal_sockets) < 0) {
		perror("Failed to create sockets for GLib signal handling");
		exit(1);
	}
	signal_channel = g_io_channel_unix_new(signal_sockets[1]);

	/*
	 * Set the channel encoding to raw binary instead of the default of
	 * UTF-8, because we'll be sending integers across instead of strings.
	 */
	error = NULL;
	signal_status = g_io_channel_set_encoding(signal_channel, NULL, &error);
	if (signal_status != G_IO_STATUS_NORMAL) {
		fprintf(stderr, "Failed to set the signal channel to raw "
				"binary: %s", error->message);
		exit(1);
	}
	signal_channel_watcher = g_io_add_watch(signal_channel, G_IO_IN, mainloop_sighandler, NULL);
	g_io_channel_unref(signal_channel);

	/* Let's not violate any PLA's!!!! */
	/* jseymour: whatever the fsck that means */
	/* Robot101: for some reason things like gdm like to block     *
	 * useful signals like SIGCHLD, so we unblock all the ones we  *
	 * declare a handler for. thanks JSeymour and Vann.            */
	if (sigemptyset(&sigset)) {
		snprintf(errmsg, sizeof(errmsg), "Warning: couldn't initialise empty signal set");
		perror(errmsg);
	}
	for(sig_indx = 0; catch_sig_list[sig_indx] != -1; ++sig_indx) {
		if((prev_sig_disp = signal(catch_sig_list[sig_indx], sighandler)) == SIG_ERR) {
			snprintf(errmsg, sizeof(errmsg), "Warning: couldn't set signal %d for catching",
				catch_sig_list[sig_indx]);
			perror(errmsg);
		}
		if(sigaddset(&sigset, catch_sig_list[sig_indx])) {
			snprintf(errmsg, sizeof(errmsg), "Warning: couldn't include signal %d for unblocking",
				catch_sig_list[sig_indx]);
			perror(errmsg);
		}
	}
	for(sig_indx = 0; ignore_sig_list[sig_indx] != -1; ++sig_indx) {
		if((prev_sig_disp = signal(ignore_sig_list[sig_indx], SIG_IGN)) == SIG_ERR) {
			snprintf(errmsg, sizeof(errmsg), "Warning: couldn't set signal %d to ignore",
				ignore_sig_list[sig_indx]);
			perror(errmsg);
		}
	}

	if (sigprocmask(SIG_UNBLOCK, &sigset, NULL)) {
		snprintf(errmsg, sizeof(errmsg), "Warning: couldn't unblock signals");
		perror(errmsg);
	}
#endif

	/* scan command-line options */
	opterr = 1;
	while ((opt = getopt_long(argc, argv,
#ifndef _WIN32
				  "c:dfhmnl::s:v",
#else
				  "c:dfhmnl::v",
#endif
				  long_options, NULL)) != -1) {
		switch (opt) {
		case 'c':	/* config dir */
			g_free(opt_config_dir_arg);
			opt_config_dir_arg = g_strdup(optarg);
			break;
		case 'd':	/* debug */
			debug_enabled = TRUE;
			break;
		case 'f':	/* force-online */
			opt_force_online = TRUE;
			break;
		case 'h':	/* help */
			opt_help = TRUE;
			break;
		case 'n':	/* no autologin */
			opt_nologin = TRUE;
			break;
		case 'l':	/* login, option username */
			opt_login = TRUE;
			g_free(opt_login_arg);
			if (optarg != NULL)
				opt_login_arg = g_strdup(optarg);
			break;
		case 's':	/* use existing session ID */
			g_free(opt_session_arg);
			opt_session_arg = g_strdup(optarg);
			break;
		case 'v':	/* version */
			opt_version = TRUE;
			break;
		case 'm':   /* do not ensure single instance. */
			opt_si = FALSE;
			break;
		case 'D':   /* --display */
		case 'S':   /* --sync */
			/* handled by gtk_init_check below */
			break;
		case '?':	/* show terse help */
		default:
			show_usage(argv[0], TRUE);
#ifdef HAVE_SIGNAL_H
			g_free(segfault_message);
#endif
			return 0;
			break;
		}
	}

	/* show help message */
	if (opt_help) {
		show_usage(argv[0], FALSE);
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}
	/* show version message */
	if (opt_version) {
		printf("%s %s (libpurple %s)\n", PIDGIN_NAME, DISPLAY_VERSION,
		                                 purple_core_get_version());
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}

	/* set a user-specified config directory */
	if (opt_config_dir_arg != NULL) {
		purple_util_set_user_dir(opt_config_dir_arg);
	}

	/*
	 * We're done piddling around with command line arguments.
	 * Fire up this baby.
	 */

	purple_debug_set_enabled(debug_enabled);

	/* If we're using a custom configuration directory, we
	 * do NOT want to migrate, or weird things will happen. */
	if (opt_config_dir_arg == NULL)
	{
		if (!purple_core_migrate())
		{
			migration_failed = TRUE;
		}
	}

	search_path = g_build_filename(purple_user_dir(), "gtkrc-2.0", NULL);
	gtk_rc_add_default_file(search_path);
	g_free(search_path);

	gui_check = gtk_init_check(&argc, &argv);
	if (!gui_check) {
		char *display = gdk_get_display();

		printf("%s %s\n", PIDGIN_NAME, DISPLAY_VERSION);

		g_warning("cannot open display: %s", display ? display : "unset");
		g_free(display);
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif

		return 1;
	}

	g_set_application_name(PIDGIN_NAME);

#ifdef _WIN32
	winpidgin_init(hint);
#endif

	if (migration_failed)
	{
		char *old = g_strconcat(purple_home_dir(),
		                        G_DIR_SEPARATOR_S ".gaim", NULL);
		const char *text = _(
			"%s encountered errors migrating your settings "
			"from %s to %s. Please investigate and complete the "
			"migration by hand. Please report this error at http://developer.pidgin.im");
		GtkWidget *dialog;

		dialog = gtk_message_dialog_new(NULL,
		                                0,
		                                GTK_MESSAGE_ERROR,
		                                GTK_BUTTONS_CLOSE,
		                                text, PIDGIN_NAME,
		                                old, purple_user_dir());
		g_free(old);

		g_signal_connect_swapped(dialog, "response",
		                         G_CALLBACK(gtk_main_quit), NULL);

		gtk_widget_show_all(dialog);

		gtk_main();

#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}

	purple_core_set_ui_ops(pidgin_core_get_ui_ops());
	purple_eventloop_set_ui_ops(pidgin_eventloop_get_ui_ops());

	/*
	 * Set plugin search directories. Give priority to the plugins
	 * in user's home directory.
	 */
	search_path = g_build_filename(purple_user_dir(), "plugins", NULL);
	if (!g_stat(search_path, &st))
		g_mkdir(search_path, S_IRUSR | S_IWUSR | S_IXUSR);
	purple_plugins_add_search_path(search_path);
	g_free(search_path);
	purple_plugins_add_search_path(LIBDIR);

	if (!purple_core_init(PIDGIN_UI)) {
		fprintf(stderr,
				"Initialization of the libpurple core failed. Dumping core.\n"
				"Please report this!\n");
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		abort();
	}

	if (opt_si && !purple_core_ensure_single_instance()) {
#ifdef HAVE_DBUS
		DBusConnection *conn = purple_dbus_get_connection();
		DBusMessage *message = dbus_message_new_method_call(DBUS_SERVICE_PURPLE, DBUS_PATH_PURPLE,
				DBUS_INTERFACE_PURPLE, "PurpleBlistSetVisible");
		gboolean tr = TRUE;
		dbus_message_append_args(message, DBUS_TYPE_INT32, &tr, DBUS_TYPE_INVALID);
		dbus_connection_send_with_reply_and_block(conn, message, -1, NULL);
		dbus_message_unref(message);
#endif
		gdk_notify_startup_complete();
		purple_core_quit();
		g_printerr(_("Exiting because another libpurple client is already running.\n"));
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}

	/* TODO: Move blist loading into purple_blist_init() */
	purple_set_blist(purple_blist_new());
	purple_blist_load();

	/* load plugins we had when we quit */
	purple_plugins_load_saved(PIDGIN_PREFS_ROOT "/plugins/loaded");

	/* TODO: Move pounces loading into purple_pounces_init() */
	purple_pounces_load();

	ui_main();

#ifdef USE_SM
	pidgin_session_init(argv[0], opt_session_arg, opt_config_dir_arg);
#endif
	if (opt_session_arg != NULL) {
		g_free(opt_session_arg);
		opt_session_arg = NULL;
	}
	if (opt_config_dir_arg != NULL) {
		g_free(opt_config_dir_arg);
		opt_config_dir_arg = NULL;
	}

	/* This needs to be before purple_blist_show() so the
	 * statusbox gets the forced online status. */
	if (opt_force_online)
		purple_network_force_online();

	/*
	 * We want to show the blist early in the init process so the
	 * user feels warm and fuzzy (not cold and prickley).
	 */
	purple_blist_show();

	if (purple_prefs_get_bool(PIDGIN_PREFS_ROOT "/debug/enabled"))
		pidgin_debug_window_show();

	if (opt_login) {
		/* disable all accounts */
		for (accounts = purple_accounts_get_all(); accounts != NULL; accounts = accounts->next) {
			PurpleAccount *account = accounts->data;
			purple_account_set_enabled(account, PIDGIN_UI, FALSE);
		}
		/* honor the startup status preference */
		if (!purple_prefs_get_bool("/purple/savedstatus/startup_current_status"))
			purple_savedstatus_activate(purple_savedstatus_get_startup());
		/* now enable the requested ones */
		dologin_named(opt_login_arg);
		if (opt_login_arg != NULL) {
			g_free(opt_login_arg);
			opt_login_arg = NULL;
		}
	} else if (opt_nologin)	{
		/* Set all accounts to "offline" */
		PurpleSavedStatus *saved_status;

		/* If we've used this type+message before, lookup the transient status */
		saved_status = purple_savedstatus_find_transient_by_type_and_message(
							PURPLE_STATUS_OFFLINE, NULL);

		/* If this type+message is unique then create a new transient saved status */
		if (saved_status == NULL)
			saved_status = purple_savedstatus_new(NULL, PURPLE_STATUS_OFFLINE);

		/* Set the status for each account */
		purple_savedstatus_activate(saved_status);
	} else {
		/* Everything is good to go--sign on already */
		if (!purple_prefs_get_bool("/purple/savedstatus/startup_current_status"))
			purple_savedstatus_activate(purple_savedstatus_get_startup());
		purple_accounts_restore_current_statuses();
	}

	if ((active_accounts = purple_accounts_get_all_active()) == NULL)
	{
		pidgin_accounts_window_show();
	}
	else
	{
		g_list_free(active_accounts);
	}

	/* GTK clears the notification for us when opening the first window,
	 * but we may have launched with only a status icon, so clear the it
	 * just in case. */
	gdk_notify_startup_complete();

#ifdef _WIN32
	winpidgin_post_init();
#endif

	gtk_main();

#ifdef HAVE_SIGNAL_H
	g_free(segfault_message);
	g_source_remove(signal_channel_watcher);
	close(signal_sockets[0]);
	close(signal_sockets[1]);
#endif

#ifdef _WIN32
	winpidgin_cleanup();
#endif

	return 0;
}