bool facebook_client::feeds( )
{
	handle_entry( "feeds" );

	// Get feeds
	http::response resp = flap( FACEBOOK_REQUEST_FEEDS );

	// Process result data
	validate_response(&resp);
  
	switch ( resp.code )
	{
	case HTTP_CODE_OK:
		if (resp.data.find("\"num_stories\":0") == std::string::npos) {
			std::string* response_data = new std::string( resp.data );
		    ForkThread( &FacebookProto::ProcessFeeds, this->parent, ( void* )response_data );
		}
		return handle_success( "feeds" );

	case HTTP_CODE_FAKE_ERROR:
	case HTTP_CODE_FAKE_DISCONNECTED:
	default:
		return handle_error( "feeds" );
	}
}
bool Omegle_client::stop( )
{
	if ( parent->isOffline())
		return true;

	handle_entry( "stop" );

	std::string data = "id=" + this->chat_id_;

	http::response resp = flap( OMEGLE_REQUEST_STOP, &data );

	if (hConnection)
		Netlib_CloseHandle(hConnection);
	hConnection = NULL;

	if (hEventsConnection)
		Netlib_CloseHandle(hEventsConnection);
	hEventsConnection = NULL;

	if (resp.data == "win") {
		return handle_success( "stop" );
	} else {
		return handle_error( "stop" );
	}

/*	switch ( resp.code )
	{
	case HTTP_CODE_OK:
	case HTTP_CODE_FOUND:

	default:
		
	}*/
}
Exemple #3
0
bool facebook_client::logout()
{
	if (parent->getByte(FACEBOOK_KEY_DISABLE_LOGOUT, 0))
		return true;

	handle_entry("logout");

	std::string data = "fb_dtsg=" + (!this->dtsg_.empty() ? this->dtsg_ : "0");
	data += "&ref=mb&h=" + this->logout_hash_;

	http::response resp = flap(REQUEST_LOGOUT, &data);

	if (hFcbCon)
		Netlib_CloseHandle(hFcbCon);
	hFcbCon = NULL;

	// Process result
	username_ = password_ = self_.user_id = "";

	switch (resp.code)
	{
	case HTTP_CODE_OK:
	case HTTP_CODE_FOUND:
		return handle_success("logout");

	default:
		return false; // Logout not finished properly, but..okay, who cares :P
	}
}
bool facebook_client::set_status(const std::string &status_text)
{
	handle_entry( "set_status" );

	std::string data = "post_form_id_source=AsyncRequest&post_form_id=";
	data += ( this->post_form_id_.length( ) ) ? this->post_form_id_ : "0";
	data += "&fb_dtsg=";
	data += ( this->dtsg_.length( ) ) ? this->dtsg_ : "0";
	data += "&target_id=";
	data += this->self_.user_id;

	if ( status_text.length( ) )
	{
		data += "&action=PROFILE_UPDATE&app_id=&hey_kid_im_a_composer=true&display_context=profile&_log_display_context=profile&ajax_log=1&status=";
		data += utils::url::encode( status_text );
		data += "&profile_id=";
		data += this->self_.user_id;
	}

	http::response resp = flap( FACEBOOK_REQUEST_STATUS_SET, &data );

	validate_response(&resp);

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
  		return handle_success( "set_status" );

  	case HTTP_CODE_FAKE_ERROR:
	case HTTP_CODE_FAKE_DISCONNECTED:
	default:
  		return handle_error( "set_status" );
	}
}
Exemple #5
0
bool facebook_client::reconnect()
{
	handle_entry("reconnect");

	// Request reconnect
	http::response resp = flap(REQUEST_RECONNECT);

	switch (resp.code)
	{
	case HTTP_CODE_OK:
	{
		this->chat_channel_ = utils::text::source_get_value(&resp.data, 2, "\"user_channel\":\"", "\"");
		parent->debugLogA("      Got self channel: %s", this->chat_channel_.c_str());
				
		this->chat_channel_partition_ = utils::text::source_get_value2(&resp.data, "\"partition\":", ",}");
		parent->debugLogA("      Got self channel partition: %s", this->chat_channel_partition_.c_str());
		
		this->chat_channel_host_ = utils::text::source_get_value(&resp.data, 2, "\"host\":\"", "\"");
		parent->debugLogA("      Got self channel host: %s", this->chat_channel_host_.c_str());

		this->chat_sequence_num_ = utils::text::source_get_value2(&resp.data, "\"seq\":", ",}");
		parent->debugLogA("      Got self sequence number: %s", this->chat_sequence_num_.c_str());

		this->chat_conn_num_ = utils::text::source_get_value2(&resp.data, "\"max_conn\":", ",}");
		parent->debugLogA("      Got self max_conn: %s", this->chat_conn_num_.c_str());

		return handle_success("reconnect");
	}
	 
	default:
		return handle_error("reconnect", FORCE_DISCONNECT);
	}
}
bool facebook_client::logout( )
{
	if ( DBGetContactSettingByte(NULL, parent->m_szModuleName, FACEBOOK_KEY_DISABLE_LOGOUT, 0) )
		return true;

	handle_entry( "logout" );

	std::string data = "post_form_id=";
	data += ( this->post_form_id_.length( ) ) ? this->post_form_id_ : "0";
	data += "&fb_dtsg=";
	data += ( this->dtsg_.length( ) ) ? this->dtsg_ : "0";
	data += "&ref=mb&h=";
	data += this->logout_hash_;

	http::response resp = flap( FACEBOOK_REQUEST_LOGOUT, &data );

	if (hFcbCon)
		Netlib_CloseHandle(hFcbCon);
	hFcbCon = NULL;

	// Process result
	username_ = password_ = self_.user_id = "";

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
	case HTTP_CODE_FOUND:
		return handle_success( "logout" );

	default:
		return false; // Logout not finished properly, but..okay, who cares :P
	}
}
/* main: */
int main (int argc, char *argv[])
{
    char *token[MAX_TOKENS];
    int fd, num_tokens;
    string origin, cur_origin;
    unsigned int ttl = DEFAULT_TTL;

    if (argc != 4) {
        fprintf (stderr, "  usage: bind-to-tinydns "
             "<origin/domain> <output file> <temp file>\n"
             "    (input is read from stdin)\n");
        exit (1);
    }

    /* init origin */
    origin.text[0] = '.';
    origin.text[1] = '\0';
    origin.len = origin.real_len = 1;
    if (qualify_domain (&origin, argv[1], &origin))
        fatal ("unable to qualify initial origin", -1);
    memcpy (&cur_origin, &origin, sizeof (string));

    /* open temp file */
    filename = argv[3];
    if ((fd = open (filename, O_WRONLY | O_CREAT | O_EXCL, 0644)) == -1) {
        fprintf (stderr, "fatal: unable to create temp file: %s\n",
             strerror (errno));
        exit (1);
    }
    if (!(file = fdopen (fd, "w"))) {
        fprintf (stderr, "fatal: unable to create file stream: %s\n",
             strerror (errno));
        exit (1);
    }

    /* tokenize, parse, and emit each entry */
    while ((num_tokens = tokenize (token)) != -1)
        handle_entry (num_tokens, (const char **) token,
                  &cur_origin, &origin, &ttl);

    /* close and rename temp file */
    if (fclose (file)) {
        fprintf (stderr, "fatal: unable to close temp file: %s\n",
             strerror (errno));
        exit (1);
    }
    if (rename (filename, argv[2])) {
        fprintf (stderr, "fatal: unable to rename temp file: %s\n",
             strerror (errno));
        if (unlink (filename)) {
            fprintf (stderr, "unable to unlink temp file: %s\n",
                 strerror (errno));
        }
        exit (1);
    }

    return 0;
}
Exemple #8
0
bool facebook_client::chat_state(bool online)
{
	handle_entry("chat_state");
  
	std::string data = (online ? "visibility=1" : "visibility=0");
	data += "&window_id=0";
	data += "&fb_dtsg=" + (!dtsg_.empty() ? dtsg_ : "0");
	data += "&phstamp=0&__user="******"chat_state");

	return handle_success("chat_state");
}
bool facebook_client::chat_state( bool online )
{
	handle_entry( "chat_state" );
  
	std::string data = "visibility=";
	data += ( online ) ? "1" : "0";
	data += "&window_id=0";
	data += "&post_form_id=";
	data += ( post_form_id_.length( ) ) ? post_form_id_ : "0";
	data += "&post_form_id_source=AsyncRequest";
	data += "&fb_dtsg=" + this->dtsg_;
	data += "&lsd=&phstamp=0&__user="******"chat_state" );
}
std::string Omegle_client::get_page( const int request_type )
{
	handle_entry( "get_page" );

	http::response resp = flap( OMEGLE_REQUEST_COUNT );

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
		handle_success( "get_page" );
		break;

	case HTTP_CODE_FAKE_ERROR:
	case HTTP_CODE_FAKE_DISCONNECTED:
	default:
		handle_error( "get_page" );
	}

	return resp.data;
}
bool facebook_client::buddy_list( )
{
	handle_entry( "buddy_list" );

	// Prepare update data
	std::string data = "user="******"&fetch_mobile=true&post_form_id=" + this->post_form_id_ + "&fb_dtsg=" + this->dtsg_ + "&lsd=&post_form_id_source=AsyncRequest&__user="******"&available_user_info_ids[";
			data += utils::conversion::to_string(&counter, UTILS_CONV_UNSIGNED_NUMBER);
			data += "]=";
			data += i->data->user_id;
		}
	}

	// Get buddy list
	http::response resp = flap( FACEBOOK_REQUEST_BUDDY_LIST, &data );

	// Process result data
	validate_response(&resp);

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
	{
		std::string* response_data = new std::string( resp.data );
		ForkThread( &FacebookProto::ProcessBuddyList, this->parent, ( void* )response_data );
		return handle_success( "buddy_list" );
	}

	case HTTP_CODE_FAKE_ERROR:
	case HTTP_CODE_FAKE_DISCONNECTED:
	default:
		return handle_error( "buddy_list" );
	}
}
bool Omegle_client::typing_stop()
{
	handle_entry( "typing_stop" );

	std::string data = "id=" + this->chat_id_;

	http::response resp = flap( OMEGLE_REQUEST_TYPING_STOP, &data );

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
		if (resp.data == "win") {
			return handle_success( "typing_stop" );
		}

	case HTTP_CODE_FAKE_ERROR:
	case HTTP_CODE_FAKE_DISCONNECTED:
	default:
		return handle_error( "typing_stop" );
	}
}
bool facebook_client::reconnect( )
{
	handle_entry( "reconnect" );

	// Request reconnect
	http::response resp = flap( FACEBOOK_REQUEST_RECONNECT );

	// Process result data
	validate_response(&resp);

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
	{
		this->chat_channel_jslogger_ = utils::text::source_get_value( &resp.data, 2, "\"jslogger_suffix\":\"", "\"" );
		parent->Log("      Got self channel jslogger: %s", this->chat_channel_jslogger_.c_str());
				
		this->chat_channel_partition_ = utils::text::source_get_value2( &resp.data, "\"partition\":", ",}" );
		parent->Log("      Got self channel partition: %s", this->chat_channel_partition_.c_str());
		
		this->chat_channel_host_ = utils::text::source_get_value( &resp.data, 2, "\"host\":\"", "\"" );
		parent->Log("      Got self channel host: %s", this->chat_channel_host_.c_str());

		this->chat_sequence_num_ = utils::text::source_get_value2( &resp.data, "\"seq\":", ",}" );
		parent->Log("      Got self sequence number: %s", this->chat_sequence_num_.c_str());

		if (this->chat_channel_jslogger_.empty()) {
			if (!atoi(this->chat_channel_host_.substr(0, this->chat_channel_host_.find(".")).c_str())) {
				this->chat_channel_jslogger_ = "SOMETHING";
				parent->Log("      Got no jslogger, changed.");
			}
		}
  		
		return handle_success( "reconnect" );
	}
	 
	default:
		return handle_error( "reconnect", FORCE_DISCONNECT );
	}
}
bool Omegle_client::send_message( std::string message_text )
{
	handle_entry( "send_message" );

	std::string data = "msg=" + utils::url::encode( message_text );
	data += "&id=" + this->chat_id_;

	http::response resp = flap( OMEGLE_REQUEST_SEND, &data );

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
		if (resp.data == "win") {
			return handle_success( "send_message" );
		}

	case HTTP_CODE_FAKE_ERROR:
	case HTTP_CODE_FAKE_DISCONNECTED:
	default:
		return handle_error( "send_message" );
	}
}
Exemple #15
0
static void
loop(void *_port)
{
	struct event_iocp_port *port = _port;
	long ms = port->ms;
	HANDLE p = port->port;

	if (ms <= 0)
		ms = INFINITE;

	while (1) {
		OVERLAPPED *overlapped=NULL;
		ULONG_PTR key=0;
		DWORD bytes=0;
		int ok = GetQueuedCompletionStatus(p, &bytes, &key,
			&overlapped, ms);
		EnterCriticalSection(&port->lock);
		if (port->shutdown) {
			if (--port->n_live_threads == 0)
				ReleaseSemaphore(port->shutdownSemaphore, 1,
						NULL);
			LeaveCriticalSection(&port->lock);
			return;
		}
		LeaveCriticalSection(&port->lock);

		if (key != NOTIFICATION_KEY && overlapped)
			handle_entry(overlapped, key, bytes, ok);
		else if (!overlapped)
			break;
	}
	event_warnx("GetQueuedCompletionStatus exited with no event.");
	EnterCriticalSection(&port->lock);
	if (--port->n_live_threads == 0)
		ReleaseSemaphore(port->shutdownSemaphore, 1, NULL);
	LeaveCriticalSection(&port->lock);
}
bool Omegle_client::recaptcha()
{
	// TODO: Implement!

	handle_entry( "recaptcha" );

	// data:{id:this.clientID,challenge:b,response:a}}
	//std::string data = "?id=...&challenge= ..., &response= ...";

	http::response resp = flap( OMEGLE_REQUEST_RECAPTCHA );

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
/*		if (resp.data == "win") {
			return handle_success( "typing_start" );
		}*/

	case HTTP_CODE_FAKE_ERROR:
	case HTTP_CODE_FAKE_DISCONNECTED:
	default:
		return handle_error( "typing_start" );
	}
}
bool facebook_client::load_friends( )
{
	handle_entry( "load_friends" );

	// Get buddy list
	http::response resp = flap( FACEBOOK_REQUEST_LOAD_FRIENDS );

	// Process result data
	validate_response(&resp);

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
	{
		std::string* response_data = new std::string( resp.data );
		ForkThread( &FacebookProto::ProcessFriendList, this->parent, ( void* )response_data );
		return handle_success( "load_friends" );
	}
	case HTTP_CODE_FAKE_ERROR:
	case HTTP_CODE_FAKE_DISCONNECTED:
	default:
		return handle_error( "load_friends" );
	}
}
Exemple #18
0
bool facebook_client::send_message(MCONTACT hContact, std::string message_recipient, std::string message_text, std::string *error_text, MessageMethod method)
{
	ScopedLock s(send_message_lock_);

	handle_entry("send_message");

	http::response resp;

	switch (method) {
		case MESSAGE_INBOX:
		{
			parent->debugLogA("    > Sending message through INBOX");
			std::string data = "action=send";
			data += "&body=" + utils::url::encode(message_text);
			data += "&recipients[0]=" + message_recipient;
			data += "&__user="******"&__a=1";
			data += "&fb_dtsg=" + (!dtsg_.empty() ? dtsg_ : "0");
			data += "&phstamp=0";

			resp = flap(REQUEST_MESSAGE_SEND2, &data);
			break;
		}
		case MESSAGE_MERCURY:
		{
			parent->debugLogA("    > Sending message through CHAT");
			std::string data = "message_batch[0][action_type]=ma-type:user-generated-message";
			data += "&message_batch[0][thread_id]";
			data += "&message_batch[0][author]=fbid:" + this->self_.user_id;
			data += "&message_batch[0][author_email]";
			data += "&message_batch[0][coordinates]";
			data += "&message_batch[0][timestamp]=" + utils::time::mili_timestamp();
			data += "&message_batch[0][timestamp_absolute]";
			data += "&message_batch[0][timestamp_relative]";
			data += "&message_batch[0][is_unread]=false";
			data += "&message_batch[0][is_cleared]=false";
			data += "&message_batch[0][is_forward]=false";
			data += "&message_batch[0][spoof_warning]=false";
			data += "&message_batch[0][source]=source:chat:web";
			data += "&message_batch[0][source_tags][0]=source:chat";
			data += "&message_batch[0][body]=" + utils::url::encode(message_text);
			data += "&message_batch[0][has_attachment]=false";
			data += "&message_batch[0][html_body]=false";
			data += "&message_batch[0][specific_to_list][0]=fbid:" + message_recipient;
			data += "&message_batch[0][specific_to_list][1]=fbid:" + this->self_.user_id;
			data += "&message_batch[0][status]=0";
			data += "&message_batch[0][message_id]";
			data += "&message_batch[0][client_thread_id]=user:"******"&client=mercury";
			data += "&fb_dtsg=" + (!dtsg_.empty() ? dtsg_ : "0");
			data += "&__user="******"&__a=1";
			data += "&phstamp=0";

			resp = flap(REQUEST_MESSAGE_SEND, &data);
			break;
		}
		case MESSAGE_TID:
		{
			parent->debugLogA("    > Sending message through MERCURY (TID)");
			std::string data = "message_batch[0][action_type]=ma-type:user-generated-message";
			data += "&message_batch[0][thread_id]=" + message_recipient;
			data += "&message_batch[0][author]=fbid:" + this->self_.user_id;
			data += "&message_batch[0][timestamp]=" + utils::time::mili_timestamp();
			data += "&message_batch[0][timestamp_absolute]=";
			data += "&message_batch[0][timestamp_relative]=";
			data += "&message_batch[0][is_unread]=false";
			data += "&message_batch[0][is_cleared]=false";
			data += "&message_batch[0][is_forward]=false";
			data += "&message_batch[0][source]=source:chat:web";
			data += "&message_batch[0][body]=" + utils::url::encode(message_text);
			data += "&message_batch[0][has_attachment]=false";
			data += "&message_batch[0][is_html]=false";
			data += "&message_batch[0][message_id]=";
			data += "&fb_dtsg=" + (!dtsg_.empty() ? dtsg_ : "0");
			data += "&__user="******"&phstamp=0";

			resp = flap(REQUEST_MESSAGE_SEND, &data);
			break;
		}
		case MESSAGE_ASYNC:
		{
			parent->debugLogA("    > Sending message through ASYNC");
			std::string data = "action=send";
			data += "&body=" + utils::url::encode(message_text);
			data += "&recipients[0]=" + message_recipient;
			data += "&lsd=";
			data += "&fb_dtsg=" + (!dtsg_.empty() ? dtsg_ : "0");

			resp = flap(REQUEST_ASYNC, &data);
			break;
		}
	}
	
	*error_text = resp.error_text;

	switch (resp.error_number)
	{
  	case 0: // Everything is OK
	{
		// Remember this message id
		std::string mid = utils::text::source_get_value(&resp.data, 2, "\"message_id\":\"", "\"");
		parent->setString(hContact, FACEBOOK_KEY_MESSAGE_ID, mid.c_str());
		messages_ignore.insert(std::make_pair(mid, false));
	} break;

    //case 1356002: // You are offline - wtf??

	case 1356003: // Contact is offline
	{
		MCONTACT hContact = parent->ContactIDToHContact(message_recipient);
		if (hContact != NULL)
  			parent->setWord(hContact, "Status", ID_STATUS_OFFLINE);
		return false;
	} break;

  	case 1356026: // Contact has alternative client
	{
		client_notify(TranslateT("Need confirmation for sending messages to other clients.\nOpen Facebook website and try to send message to this contact again!"));
		return false;
	} break;
 
    default: // Other error
		parent->debugLogA(" !!!  Send message error #%d: %s", resp.error_number, resp.error_text);
		return false;
 	}

	switch (resp.code)
	{
	case HTTP_CODE_OK:
		return handle_success("send_message");

	case HTTP_CODE_FAKE_ERROR:
	case HTTP_CODE_FAKE_DISCONNECTED:
	default:
		*error_text = Translate("Timeout when sending message.");

		handle_error("send_message");
		return false;
	}
}
Exemple #19
0
/**
 * OS specific function to load the different mntents into the cache.
 * This function should be called with a write lock on the mntent_cache.
 */
static void refresh_mount_cache(mntent_cache_entry_t *handle_entry(uint32_t dev,
                                                                   const char *special,
                                                                   const char *mountpoint,
                                                                   const char *fstype,
                                                                   const char *mntopts))
{
#if defined(HAVE_GETMNTENT)
   FILE *fp;
   struct stat st;
#if defined(HAVE_LINUX_OS) || \
    defined(HAVE_HPUX_OS) || \
    defined(HAVE_IRIX_OS) || \
    defined(HAVE_AIX_OS) || \
    defined(HAVE_HURD_OS)
   struct mntent *mnt;

#if defined(HAVE_LINUX_OS)
   if ((fp = setmntent("/proc/mounts", "r")) == (FILE *)NULL) {
      if ((fp = setmntent(_PATH_MOUNTED, "r")) == (FILE *)NULL) {
         return;
      }
   }
#elif defined(HAVE_HPUX_OS)
   if ((fp = fopen(MNT_MNTTAB, "r")) == (FILE *)NULL) {
      return;
   }
#elif defined(HAVE_IRIX_OS)
   if ((fp = setmntent(MOUNTED, "r")) == (FILE *)NULL) {
      return;
   }
#elif defined(HAVE_AIX_OS)
   if ((fp = setmntent(MNTTAB, "r")) == (FILE *)NULL) {
      return;
   }
#elif defined(HAVE_HURD_OS)
   if ((fp = setmntent(_PATH_MNTTAB, "r")) == (FILE *)NULL) {
      return;
   }
#endif

   while ((mnt = getmntent(fp)) != (struct mntent *)NULL) {
      if (skip_fstype(mnt->mnt_type)) {
         continue;
      }

      if (stat(mnt->mnt_dir, &st) < 0) {
         continue;
      }

      handle_entry(st.st_dev,
                   mnt->mnt_fsname,
                   mnt->mnt_dir,
                   mnt->mnt_type,
                   mnt->mnt_opts);
   }

   endmntent(fp);
#elif defined(HAVE_SUN_OS)
   struct mnttab mnt;

   if ((fp = fopen(MNTTAB, "r")) == (FILE *)NULL)
      return;

   while (getmntent(fp, &mnt) == 0) {
      if (skip_fstype(mnt.mnt_fstype)) {
         continue;
      }

      if (stat(mnt.mnt_mountp, &st) < 0) {
         continue;
      }

      handle_entry(st.st_dev,
                   mnt.mnt_special,
                   mnt.mnt_mountp,
                   mnt.mnt_fstype,
                   mnt.mnt_mntopts);
   }

   fclose(fp);
#endif /* HAVE_SUN_OS */
#elif defined(HAVE_GETMNTINFO)
   int cnt;
   struct stat st;
#if defined(HAVE_NETBSD_OS)
   struct statvfs *mntinfo;
#else
   struct statfs *mntinfo;
#endif
#if defined(ST_NOWAIT)
   int flags = ST_NOWAIT;
#elif defined(MNT_NOWAIT)
   int flags = MNT_NOWAIT;
#else
   int flags = 0;
#endif

   if ((cnt = getmntinfo(&mntinfo, flags)) > 0) {
      while (cnt > 0) {
         if (!skip_fstype(mntinfo->f_fstypename) &&
             stat(mntinfo->f_mntonname, &st) == 0) {
            handle_entry(st.st_dev,
                         mntinfo->f_mntfromname,
                         mntinfo->f_mntonname,
                         mntinfo->f_fstypename,
                         NULL);
         }
         mntinfo++;
         cnt--;
      }
   }
#elif defined(HAVE_AIX_OS)
   int bufsize;
   char *entries, *current;
   struct vmount *vmp;
   struct stat st;
   struct vfs_ent *ve;
   int n_entries, cnt;

   if (mntctl(MCTL_QUERY, sizeof(bufsize), (struct vmount *)&bufsize) != 0) {
      return;
   }

   entries = malloc(bufsize);
   if ((n_entries = mntctl(MCTL_QUERY, bufsize, (struct vmount *) entries)) < 0) {
      free(entries);
      return;
   }

   cnt = 0;
   current = entries;
   while (cnt < n_entries) {
      vmp = (struct vmount *)current;

      if (skip_fstype(ve->vfsent_name)) {
         continue;
      }

      if (stat(current + vmp->vmt_data[VMT_STUB].vmt_off, &st) < 0) {
         continue;
      }

      ve = getvfsbytype(vmp->vmt_gfstype);
      if (ve && ve->vfsent_name) {
         handle_entry(st.st_dev,
                      current + vmp->vmt_data[VMT_OBJECT].vmt_off,
                      current + vmp->vmt_data[VMT_STUB].vmt_off,
                      ve->vfsent_name,
                      current + vmp->vmt_data[VMT_ARGS].vmt_off);
      }
      current = current + vmp->vmt_length;
      cnt++;
   }
   free(entries);
#elif defined(HAVE_OSF1_OS)
   struct statfs *entries, *current;
   struct stat st;
   int n_entries, cnt;
   int size;

   if ((n_entries = getfsstat((struct statfs *)0, 0L, MNT_NOWAIT)) < 0) {
      return;
   }

   size = (n_entries + 1) * sizeof(struct statfs);
   entries = malloc(size);

   if ((n_entries = getfsstat(entries, size, MNT_NOWAIT)) < 0) {
      free(entries);
      return;
   }

   cnt = 0;
   current = entries;
   while (cnt < n_entries) {
      if (skip_fstype(current->f_fstypename)) {
         continue;
      }

      if (stat(current->f_mntonname, &st) < 0) {
         continue;
      }
      handle_entry(st.st_dev,
                   current->f_mntfromname,
                   current->f_mntonname,
                   current->f_fstypename,
                   NULL);
      current++;
      cnt++;
   }
   free(stats);
#endif
}
Exemple #20
0
bool facebook_client::login(const char *username, const char *password)
{
	handle_entry("login");

	username_ = username;
	password_ = password;
	
	if (cookies.empty()) {
		// Set device ID
		ptrA device( parent->getStringA(FACEBOOK_KEY_DEVICE_ID));
		if (device != NULL)
			cookies["datr"] = device;

		// Get initial cookies
		flap(REQUEST_HOME);
	}

	// Prepare login data
	std::string data = "persistent=1";
	data += "&email=" + utils::url::encode(username);
	data += "&pass="******"&locale=" + std::string(locale);

	// Send validation
	http::response resp = flap(REQUEST_LOGIN, &data);

	// Save Device ID
	if (!cookies["datr"].empty())
		parent->setString(FACEBOOK_KEY_DEVICE_ID, cookies["datr"].c_str());

	if (resp.code == HTTP_CODE_FOUND && resp.headers.find("Location") != resp.headers.end())
	{
		// Check for invalid requests
		if (resp.headers["Location"].find("invalid_request.php") != std::string::npos) {
			client_notify(TranslateT("Login error: Invalid request."));
			parent->debugLogA(" ! !  Login error: Invalid request.");
			return handle_error("login", FORCE_QUIT);
		}

		// Check whether some Facebook things are required
		if (resp.headers["Location"].find("help.php") != std::string::npos)
		{
			client_notify(TranslateT("Login error: Some Facebook things are required."));
			parent->debugLogA(" ! !  Login error: Some Facebook things are required.");
			// return handle_error("login", FORCE_QUIT);
		}
		
		// Check whether setting Machine name is required
		if (resp.headers["Location"].find("/checkpoint/") != std::string::npos)
		{
			resp = flap(REQUEST_SETUP_MACHINE, NULL, NULL, REQUEST_GET);

			if (resp.data.find("login_approvals_no_phones") != std::string::npos) {
				// Code approval - but no phones in account
				loginError(parent, utils::text::source_get_value(&resp.data, 4, "login_approvals_no_phones", "<div", ">", "</div>"));
				return handle_error("login", FORCE_QUIT);
			}

			std::string inner_data;
			if (resp.data.find("name=\"submit[Continue]\"") != std::string::npos) {
				
				// Check if we need to approve also last unapproved device
				if (resp.data.find("name=\"name_action_selected\"") == std::string::npos) {
					// 1) Continue
					inner_data = "submit[Continue]=Continue";
					inner_data += "&nh=" + utils::text::source_get_value(&resp.data, 3, "name=\"nh\"", "value=\"", "\"");
					inner_data += "&fb_dtsg=" + utils::text::source_get_value(&resp.data, 3, "name=\"fb_dtsg\"", "value=\"", "\"");
					resp = flap(REQUEST_SETUP_MACHINE, &inner_data);

					// 2) Approve last unknown login
					// inner_data = "submit[I%20don't%20recognize]=I%20don't%20recognize"; // Don't recognize - this will force to change account password
					inner_data = "submit[This%20is%20Okay]=This%20is%20Okay"; // Recognize
					inner_data += "&nh=" + utils::text::source_get_value(&resp.data, 3, "name=\"nh\"", "value=\"", "\"");
					inner_data += "&fb_dtsg=" + utils::text::source_get_value(&resp.data, 3, "name=\"fb_dtsg\"", "value=\"", "\"");
					resp = flap(REQUEST_SETUP_MACHINE, &inner_data);

					// 3) Save last device
					inner_data = "submit[Continue]=Continue";
					inner_data += "&nh=" + utils::text::source_get_value(&resp.data, 3, "name=\"nh\"", "value=\"", "\"");
					inner_data += "&fb_dtsg=" + utils::text::source_get_value(&resp.data, 3, "name=\"fb_dtsg\"", "value=\"", "\"");
					inner_data += "&name_action_selected=save_device"; // Save device - or "dont_save"
					resp = flap(REQUEST_SETUP_MACHINE, &inner_data);
				}

				// Save this actual device
				inner_data = "submit[Continue]=Continue";
				inner_data += "&nh=" + utils::text::source_get_value(&resp.data, 3, "name=\"nh\"", "value=\"", "\"");
				inner_data += "&fb_dtsg=" + utils::text::source_get_value(&resp.data, 3, "name=\"fb_dtsg\"", "value=\"", "\"");
				inner_data += "&name_action_selected=save_device"; // Save device - or "dont_save"
				resp = flap(REQUEST_SETUP_MACHINE, &inner_data);
			}

			// Save actual machine name
			// inner_data = "machine_name=Miranda%20NG&submit[Don't%20Save]=Don't%20Save"; // Don't save
			inner_data = "machine_name=Miranda%20NG&submit[Save%20Device]=Save%20Device"; // Save
			inner_data += "&lsd=" + utils::text::source_get_value(&resp.data, 3, "name=\"lsd\"", "value=\"", "\"");
			inner_data += "&nh=" + utils::text::source_get_value(&resp.data, 3, "name=\"nh\"", "value=\"", "\"");
			inner_data += "&fb_dtsg=" + utils::text::source_get_value(&resp.data, 3, "name=\"fb_dtsg\"", "value=\"", "\"");

			resp = flap(REQUEST_SETUP_MACHINE, &inner_data);
		}
	}

	switch (resp.code)
	{
	case HTTP_CODE_FAKE_DISCONNECTED:
	{
		// When is error only because timeout, try login once more
		if (handle_error("login"))
			return login(username, password);
		else
			return handle_error("login", FORCE_QUIT);
	}

	case HTTP_CODE_OK: // OK page returned, but that is regular login page we don't want in fact
	{ 
		// Check whether captcha code is required
		if (resp.data.find("id=\"captcha\"") != std::string::npos)
		{
			client_notify(TranslateT("Login error: Captcha code is required. Bad login credentials?"));
			parent->debugLogA(" ! !  Login error: Captcha code is required.");
			return handle_error("login", FORCE_QUIT);
		}

		// Get and notify error message
		loginError(parent, utils::text::source_get_value(&resp.data, 4, "login_error_box", "<div", ">", "</div>")); 
	}
	case HTTP_CODE_FORBIDDEN: // Forbidden
	case HTTP_CODE_NOT_FOUND: // Not Found
	default:
		return handle_error("login", FORCE_QUIT);

	case HTTP_CODE_FOUND: // Found and redirected to Home, Logged in, everything is OK
	{
		if (cookies.find("c_user") != cookies.end()) {
			this->self_.user_id = cookies.find("c_user")->second;
			parent->setString(FACEBOOK_KEY_ID, this->self_.user_id.c_str());
			parent->debugLogA("      Got self user id: %s", this->self_.user_id.c_str());
			return handle_success("login");
		} else {
			client_notify(TranslateT("Login error, probably bad login credentials."));
			parent->debugLogA(" ! !  Login error, probably bad login credentials.");
			return handle_error("login", FORCE_QUIT);
		}
	}
	}
}
Exemple #21
0
bool facebook_client::post_status(status_data *status)
{
	if (status == NULL || (status->text.empty() && status->url.empty()))
		return false;

	handle_entry("post_status");

	if (status->isPage) {
		std::string data = "fb_dtsg=" + (!this->dtsg_.empty() ? this->dtsg_ : "0");
		data += "&user_id=" + status->user_id;
		data += "&url=" + std::string(FACEBOOK_URL_HOMEPAGE);
		flap(REQUEST_IDENTITY_SWITCH, &data);
	}

	std::string data;
	RequestType request = REQUEST_POST_STATUS;

	if (!status->url.empty()) {
		data = "fb_dtsg=" + (!this->dtsg_.empty() ? this->dtsg_ : "0");
		data += "&composerid=u_jsonp_2_b";
		data += "&targetid=" + (status->user_id.empty() ? this->self_.user_id : status->user_id);
		data += "&istimeline=1&composercontext=composer&onecolumn=1&nctr[_mod]=pagelet_timeline_recent&__a=1&ttstamp=0";
		data += "&__user="******"&loaded_components[0]=maininput&loaded_components[1]=backdateicon&loaded_components[2]=withtaggericon&loaded_components[3]=cameraicon&loaded_components[4]=placetaggericon&loaded_components[5]=mainprivacywidget&loaded_components[6]=withtaggericon&loaded_components[7]=backdateicon&loaded_components[8]=placetaggericon&loaded_components[9]=cameraicon&loaded_components[10]=mainprivacywidget&loaded_components[11]=maininput&loaded_components[12]=explicitplaceinput&loaded_components[13]=hiddenplaceinput&loaded_components[14]=placenameinput&loaded_components[15]=hiddensessionid&loaded_components[16]=withtagger&loaded_components[17]=backdatepicker&loaded_components[18]=placetagger&loaded_components[19]=citysharericon";
		http::response resp = flap(REQUEST_LINK_SCRAPER, &data, &status->url);
		resp.data = utils::text::special_expressions_decode(utils::text::slashu_to_utf8(resp.data));

		data = "&xhpc_context=profile&xhpc_ismeta=1&xhpc_timeline=1&xhpc_composerid=u_jsonp_2_0&is_explicit_place=&composertags_place=&composer_session_id=&composertags_city=&disable_location_sharing=false&composer_predicted_city=&nctr[_mod]=pagelet_composer&__a=1&__dyn=&__req=1f&ttstamp=0";
		std::string form = utils::text::source_get_value(&resp.data, 2, "<form", "</form>");
		utils::text::replace_all(&form, "\\\"", "\"");
		data += "&" + utils::text::source_get_form_data(&form) + "&";
		//data += "&no_picture=0";

		request = REQUEST_STATUS_COMPOSER;
	}

	std::string text = utils::url::encode(status->text);

	data += "fb_dtsg=" + (!this->dtsg_.empty() ? this->dtsg_ : "0");
	data += "&xhpc_targetid=" + (status->user_id.empty() ? this->self_.user_id : status->user_id);
	data += "&__user="******"&xhpc_message=" + text;
	data += "&xhpc_message_text=" + text;
	if (!status->isPage)
		data += "&audience[0][value]=" + get_privacy_type();
	if (!status->place.empty()) {
		data += "&composertags_place_name=";
		data += utils::url::encode(status->place);
	}
	for(std::vector<facebook_user*>::size_type i = 0; i < status->users.size(); i++) {
		data += "&composertags_with[" + utils::conversion::to_string(&i, UTILS_CONV_UNSIGNED_NUMBER);
		data += "]=" + status->users[i]->user_id;
		data += "&text_composertags_with[" + utils::conversion::to_string(&i, UTILS_CONV_UNSIGNED_NUMBER);
		data += "]=" + status->users[i]->real_name;
		delete status->users[i];
	}
	status->users.clear();

	data += "&xhpc_context=profile&xhpc_ismeta=1&xhpc_timeline=1&xhpc_composerid=u_0_2y&is_explicit_place=&composertags_place=&composertags_city=";

	http::response resp = flap(request, &data);

	if (status->isPage) {
		std::string data = "fb_dtsg=" + (!this->dtsg_.empty() ? this->dtsg_ : "0");
		data += "&user_id=" + this->self_.user_id;
		data += "&url=" + std::string(FACEBOOK_URL_HOMEPAGE);
		flap(REQUEST_IDENTITY_SWITCH, &data);
	}

	if (resp.isValid()) {
		parent->NotifyEvent(parent->m_tszUserName, TranslateT("Status update was successful."), NULL, FACEBOOK_EVENT_OTHER);
		return handle_success("post_status");
	}

	return handle_error("post_status");
}
Exemple #22
0
bool facebook_client::home()
{
	handle_entry("home");

	// get fb_dtsg
	http::response resp = flap(REQUEST_DTSG);

	// Check whether HTTPS connection is required and we don't have it enabled
	if (!this->https_ && resp.headers["Location"].find("https://") != std::string::npos) {
		client_notify(TranslateT("Your account requires HTTPS connection. Activating."));
		parent->setByte(FACEBOOK_KEY_FORCE_HTTPS, 1);
		this->https_ = true;
		return home();
	}

	this->dtsg_ = utils::text::source_get_value(&resp.data, 3, "name=\"fb_dtsg\"", "value=\"", "\"");
	parent->debugLogA("      Got self dtsg: %s", this->dtsg_.c_str());

	if (this->dtsg_.empty())
		return false;
		
	resp = flap(REQUEST_HOME);

	switch (resp.code)
	{
	case HTTP_CODE_OK:
	{		
		// Get real name
		this->self_.real_name = utils::text::source_get_value(&resp.data, 2, "<strong class=\"profileName\">", "</strong>");
		
		// Try to get name again, if we've got some some weird version of Facebook
		if (this->self_.real_name.empty())
			this->self_.real_name = utils::text::source_get_value(&resp.data, 4, "id=\"root", "<strong", ">", "</strong>");

		// Get and strip optional nickname
		std::string::size_type pos = this->self_.real_name.find("<span class=\"alternate_name\">");
		if (pos != std::string::npos) {
			this->self_.nick = utils::text::source_get_value(&this->self_.real_name, 2, "<span class=\"alternate_name\">(", ")</span>");
			parent->debugLogA("      Got self nick name: %s", this->self_.nick.c_str());

			this->self_.real_name = this->self_.real_name.substr(0, pos - 1);
		}
		parent->debugLogA("      Got self real name: %s", this->self_.real_name.c_str());

		if (this->self_.real_name.empty()) {
			client_notify(TranslateT("Something happened to Facebook. Maybe there was some major update so you should wait for an update."));
			return handle_error("home", FORCE_QUIT);
		}

		// Save name and nickname
		parent->SaveName(NULL, &this->self_);

		// Get avatar
		this->self_.image_url = utils::text::source_get_value(&resp.data, 3, "class=\"l\"", "<img src=\"", "\"");
		parent->debugLogA("      Got self avatar: %s", this->self_.image_url.c_str());
		parent->CheckAvatarChange(NULL, this->self_.image_url);

		// Get logout hash
		this->logout_hash_ = utils::text::source_get_value2(&resp.data, "/logout.php?h=", "&\"");
		parent->debugLogA("      Got self logout hash: %s", this->logout_hash_.c_str());

		return handle_success("home");
	}
	case HTTP_CODE_FOUND:
		// Work-around for replica_down, f**king hell what's that?
		parent->debugLogA("      REPLICA_DOWN is back in force!");
		return this->home();
	
	default:
		return handle_error("home", FORCE_QUIT);
	}
}
bool facebook_client::home( )
{
	handle_entry( "home" );

	http::response resp = flap( FACEBOOK_REQUEST_HOME );

	// Process result data
	validate_response(&resp);

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
	{		
		if ( resp.data.find( "id=\"navAccountName\"" ) != std::string::npos )
		{ // Backup for old fb version
			// Get real_name
			this->self_.real_name = utils::text::remove_html( utils::text::special_expressions_decode( utils::text::source_get_value( &resp.data, 2, " id=\"navAccountName\">", "</a" ) ) );
			DBWriteContactSettingUTF8String(NULL,parent->m_szModuleName,FACEBOOK_KEY_NAME,this->self_.real_name.c_str());
			DBWriteContactSettingUTF8String(NULL,parent->m_szModuleName,FACEBOOK_KEY_NICK,this->self_.real_name.c_str());
			parent->Log("      Got self real name: %s", this->self_.real_name.c_str());
		} else if ( resp.data.find("id=\"pageNav\"") != std::string::npos ) {
			// Get real_name
			this->self_.real_name = utils::text::remove_html( utils::text::special_expressions_decode( utils::text::source_get_value( &resp.data, 3, " class=\"headerTinymanName\"", ">", "</a" ) ) );
			DBWriteContactSettingUTF8String(NULL,parent->m_szModuleName,FACEBOOK_KEY_NAME,this->self_.real_name.c_str());
			DBWriteContactSettingUTF8String(NULL,parent->m_szModuleName,FACEBOOK_KEY_NICK,this->self_.real_name.c_str());
			parent->Log("      Got self real name: %s", this->self_.real_name.c_str());
		} else {
			client_notify(TranslateT("Something happened to Facebook. Maybe there was some major update so you should wait for an update."));
			return handle_error( "home", FORCE_DISCONNECT );
		}

		// Get avatar
		std::string avatar = utils::text::source_get_value( &resp.data, 3, "class=\\\"fbxWelcomeBoxImg", "src=\\\"", "\\\"" );
		if (avatar.empty())
			avatar = utils::text::source_get_value( &resp.data, 3, "class=\"fbxWelcomeBoxImg", "src=\"", "\"" );

		this->self_.image_url = utils::text::trim( utils::text::special_expressions_decode( avatar ) );
		parent->Log("      Got self avatar: %s", this->self_.image_url.c_str());
		parent->CheckAvatarChange(NULL, this->self_.image_url);

		// Get post_form_id
		this->post_form_id_ = utils::text::source_get_value( &resp.data, 3, "name=\"post_form_id\"", "value=\"", "\"" );
		parent->Log("      Got self post form id: %s", this->post_form_id_.c_str());

		// Get dtsg
		this->dtsg_ = utils::text::source_get_value( &resp.data, 3, "name=\"fb_dtsg\"", "value=\"", "\"" );
		parent->Log("      Got self dtsg: %s", this->dtsg_.c_str());

		// Get logout hash
		this->logout_hash_ = utils::text::source_get_value( &resp.data, 2, "<input type=\"hidden\" autocomplete=\"off\" name=\"h\" value=\"", "\"" );
		parent->Log("      Got self logout hash: %s", this->logout_hash_.c_str());
			
		// TODO: DIrectly get that friend requests
		// Get friend requests count and notify it
		std::string str_count = utils::text::source_get_value( &resp.data, 2, "<span id=\"requestsCountValue\">", "</span>" );
		if ( str_count.length() && str_count != std::string( "0" ) )
		{
			std::string message = Translate("Got new friend requests: ") + str_count;

			TCHAR* tmessage = mir_a2t(message.c_str());
			parent->NotifyEvent( parent->m_tszUserName, tmessage, NULL, FACEBOOK_EVENT_OTHER, TEXT(FACEBOOK_URL_REQUESTS) );
			mir_free( tmessage );
		}

		if (!DBGetContactSettingByte(NULL,parent->m_szModuleName,FACEBOOK_KEY_PARSE_MESSAGES, DEFAULT_PARSE_MESSAGES))
		{
			str_count = utils::text::source_get_value( &resp.data, 2, "<span id=\"messagesCountValue\">", "</span>" );
			if ( str_count.length() && str_count != std::string( "0" ) )
			{
				std::string message = Translate("Got new messages: ") + str_count;

				TCHAR* tmessage = mir_a2t(message.c_str());
				parent->NotifyEvent( parent->m_tszUserName, tmessage, NULL, FACEBOOK_EVENT_OTHER, TEXT(FACEBOOK_URL_MESSAGES) );
				mir_free( tmessage );
			}
		}
			
		str_count = utils::text::source_get_value( &resp.data, 2, "<span id=\"notificationsCountValue\">", "</span>" );
		if ( str_count.length() && str_count != std::string( "0" ) )
		{
			// Parse notifications directly to popups
			ForkThread( &FacebookProto::ProcessNotifications, this->parent, NULL );
		}

		if (DBGetContactSettingByte(NULL, parent->m_szModuleName, FACEBOOK_KEY_ENABLE_GROUPCHATS, DEFAULT_ENABLE_GROUPCHATS)) {
			// Get group chats
			std::string favorites = utils::text::source_get_value( &resp.data, 2, "<div id=\"leftCol\"", "<div id=\"contentCol\"" );

			std::string::size_type pos = 0;
			while ((pos = favorites.find("href=\"/groups/",pos)) != std::string::npos) {
				pos += 14;
				std::string item = favorites.substr(pos, favorites.find("</a>", pos) - pos);
				std::string id = item.substr(0, item.find("/"));
		
				if (!id.empty()) {
					std::string name = utils::text::source_get_value( &item, 3, "class=\"linkWrap", ">", "</div>" );
					name = utils::text::special_expressions_decode(utils::text::slashu_to_utf8( name ) );
					parent->Log("      Got new group chat: %s (id: %s)", name.c_str(), id.c_str());
					if (!name.empty())
						parent->AddChat(id.c_str(), name.c_str());
				}
			}
		}

		return handle_success( "home" );

	}
	case HTTP_CODE_FOUND:
		// Work-around for replica_down, f**king hell what's that?
		parent->Log("      REPLICA_DOWN is back in force!");
		return this->home();
	
	default:
		return handle_error( "home", FORCE_DISCONNECT );
	}
}
/* handle_entry: parses and handles the given entry. */
int handle_entry (int num_tokens, const char **token, string *cur_origin,
                  const string *top_origin, unsigned int *ttl) {
    int i;

    if (!num_tokens) return 0;

    /* $ORIGIN */
    if (!strcasecmp (token[0], "$ORIGIN")) {
        if (num_tokens != 2)
            fatal ("$ORIGIN directive has wrong number "
                   "of arguments", start_line_num);
        if (qualify_domain (cur_origin, token[1], cur_origin))
            fatal ("choked on domain name in $ORIGIN statement",
                   start_line_num);
    /* $TTL */
    } else if (!strcasecmp (token[0], "$TTL")) {
        if (num_tokens != 2) {
            warning ("$TTL directive has wrong number of arguments",
                     start_line_num);
            *ttl = DEFAULT_TTL;
        } else if (str_to_uint (ttl, token[1], 1) ||
               *ttl > 2147483646) {
            warning ("invalid $TTL value; using default instead",
                 start_line_num);
            *ttl = DEFAULT_TTL;
        }
    /* $GENERATE */
    } else if (!strcasecmp (token[0], "$GENERATE")) {
        int start, stop, step, found, num_lhs_parts, num_rhs_parts;
        char *lhs_parts[MAX_GEN_PARTS], *rhs_parts[MAX_GEN_PARTS];
        int lhs_offsets[MAX_GEN_PARTS], rhs_offsets[MAX_GEN_PARTS];
        int lhs_widths[MAX_GEN_PARTS], rhs_widths[MAX_GEN_PARTS];
        char lhs_bases[MAX_GEN_PARTS], rhs_bases[MAX_GEN_PARTS];
        char lhs_line[LINE_LEN+1], rhs_line[LINE_LEN+1];
        char lhs_str[DOMAIN_STR_LEN], rhs_str[DOMAIN_STR_LEN];
        char *gen_token[3];

        if (num_tokens != 5)
            fatal ("$GENERATE directive has wrong number "
                   "of arguments", start_line_num);
        if (strcasecmp (token[3], "PTR") &&
            strcasecmp (token[3], "CNAME") &&
            strcasecmp (token[3], "A") &&
            strcasecmp (token[3], "NS"))
            fatal ("$GENERATE directive has unknown RR type",
                   start_line_num);

        gen_token[1] = (char *) token[3];

        /* read range */
        for (found = 0, start = 0, i = 0;
             token[1][i] >= '0' && token[1][i] <= '9'; i++) {
            start *= 10;
            start += token[1][i] - '0';
            found = 1;
        }
        if (!found || token[1][i] != '-')
            fatal ("$GENERATE directive has invalid range "
                   "(unable to parse start)", start_line_num);
        for (found = 0, stop = 0, i++;
             token[1][i] >= '0' && token[1][i] <= '9'; i++) {
            stop *= 10;
            stop += token[1][i] - '0';
            found = 1;
        }
        if (!found || (token[1][i] != '\0' && token[1][i] != '/'))
            fatal ("$GENERATE directive has invalid range "
                   "(unable to parse stop)", start_line_num);
        if (token[1][i] == '/') {
            for (found = 0, step = 0, i++;
                 token[1][i] >= '0' && token[1][i] <= '9'; i++) {
                step *= 10;
                step += token[1][i] - '0';
                found = 1;
            }
            if (!found || token[1][i] != '\0' || !step)
                fatal ("$GENERATE directive has invalid range "
                       "(unable to parse step)",
                       start_line_num);
        } else {
            step = 1;
        }

        /* parse lhs and rhs */
        strcpy (lhs_line, token[2]);
        strcpy (rhs_line, token[4]);
        parse_gen_string (lhs_line, lhs_parts, lhs_offsets,
                  lhs_widths, lhs_bases, &num_lhs_parts);
        parse_gen_string (rhs_line, rhs_parts, rhs_offsets,
                  rhs_widths, rhs_bases, &num_rhs_parts);

        /* pass generated lines back into this function */
        for (i = start; i <= stop; i += step) {
            construct_gen_output (lhs_str, lhs_parts, lhs_offsets,
                          lhs_widths, lhs_bases,
                          num_lhs_parts, i);
            construct_gen_output (rhs_str, rhs_parts, rhs_offsets,
                          rhs_widths, rhs_bases,
                          num_rhs_parts, i);
            gen_token[0] = lhs_str;
            gen_token[2] = rhs_str;

            handle_entry (3, (const char **) gen_token,
                      cur_origin, top_origin, ttl);
        }
    /* $INCLUDE */
    } else if (!strcasecmp (token[0], "$INCLUDE")) {
        fatal ("sorry, $INCLUDE directive is not implemented",
               start_line_num);
    } else if (token[0][0] == '$') {
        warning ("ignoring unknown $ directive", start_line_num);
    /* handle records */
    } else {
        int next;
        unsigned int local_ttl;
        static string owner;
        static int prev_owner = 0;
        string rdomain;

        if (num_tokens < 3) {
            fatal("RR does not have enough tokens", start_line_num);
        }

        if (strcmp(token[0], " ")) {
            if (qualify_domain(&owner, token[0], cur_origin)) {
                fatal("choked on owner name in RR", start_line_num);
            }
            /* we only need to check that this data is within the top-level
             * origin if the top level origin isn't ".". */
            if (strcmp(top_origin->text, ".")) {
                /* we know that the data is out-of-zone if:
                 * 1) the origin is longer than this record's owner
                 * 2) the fully-qualified owner doesn't end with the origin
                 * 3) the owner doesn't equal the origin, and there's no
                 *    period immediately to the left of the origin in the
                 *    owner. */
                if (top_origin->real_len > owner.real_len ||
                    strcasecmp (top_origin->text,
                        owner.text + owner.real_len -
                        top_origin->real_len) ||
                    (owner.real_len > top_origin->real_len &&
                     *(owner.text + owner.real_len -
                       top_origin->real_len - 1) != '.')) {
                    warning ("ignoring out-of-zone data",
                         start_line_num);
                    return 1;
                }
            }
            prev_owner = 1;
        } else {
            if (!prev_owner) {
                fatal ("RR tried to inherit owner from "
                       "previous record, but there was no "
                       "previous RR", start_line_num);
            }
        }

        local_ttl = *ttl;

        /* process ttl and/or class, and find where type
         * token is.  whose brilliant idea was it to let
         * these two come in either order? */
        next = 1;
        if (!str_to_uint (&local_ttl, token[1], 1)) {
            if (local_ttl > 2147483646) {
                warning ("invalid TTL in RR", start_line_num);
                local_ttl = *ttl;
            }
            if (!strcasecmp (token[2], "IN")) {
                next = 3;
            } else {
                next = 2;
            }
        } else if (!strcasecmp (token[1], "IN")) {
            if (!str_to_uint (&local_ttl, token[2], 1)) {
                if (local_ttl > 2147483646) {
                    warning ("invalid TTL in RR",
                             start_line_num);
                    local_ttl = *ttl;
                }
                next = 3;
            } else {
                next = 2;
            }
        }

        /* SOA */
        if (!strcasecmp (token[next], "SOA")) {
            string rname;
            unsigned int serial, refresh, retry;
            unsigned int expire, minimum;
            if (num_tokens - next - 1 == 2)
                fatal ("wrong number of tokens in SOA RDATA "
                       "(perhaps an opening parenthesis is on "
                       "the next line instead of this one?)",
                       start_line_num);
            if (num_tokens - next - 1 != 7)
                fatal ("wrong number of tokens in SOA RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+1],
                        cur_origin))
                fatal ("choked on MNAME in SOA RDATA",
                       start_line_num);
            if (qualify_domain (&rname, token[next+2], cur_origin))
                fatal ("choked on RNAME in SOA RDATA",
                       start_line_num);
            if (str_to_uint (&serial, token[next+3], 0))
                fatal ("invalid SERIAL in SOA RDATA",
                       start_line_num);
            if (str_to_uint (&refresh, token[next+4], 1) ||
                refresh > 2147483646)
                fatal ("invalid REFRESH in SOA RDATA",
                       start_line_num);
            if (str_to_uint (&retry, token[next+5], 1) ||
                retry > 2147483646)
                fatal ("invalid RETRY in SOA RDATA",
                       start_line_num);
            if (str_to_uint (&expire, token[next+6], 1) ||
                expire > 2147483646)
                fatal ("invalid EXPIRE in SOA RDATA",
                       start_line_num);
            if (str_to_uint (&minimum, token[next+7], 1) ||
                minimum > 2147483646)
                fatal ("invalid MINIMUM in SOA RDATA",
                       start_line_num);
            fprintf (file, "Z%s:%s:%s:%u:%u:%u:%u:%u\n",
                 owner.text, rdomain.text, rname.text,
                 serial, refresh, retry, expire, minimum);
        /* NS */
        } else if (!strcasecmp (token[next], "NS")) {
            if (num_tokens - next - 1 != 1)
                fatal ("wrong number of tokens in NS RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+1],
                        cur_origin))
                fatal ("choked on domain name in NS RDATA",
                       start_line_num);
            fprintf (file, "&%s::%s:%d\n", owner.text,
                 rdomain.text, local_ttl);
        /* MX */
        } else if (!strcasecmp (token[next], "MX")) {
            unsigned int priority;
            if (num_tokens - next - 1 != 2)
                fatal ("wrong number of tokens in MX RDATA",
                       start_line_num);
            if (str_to_uint (&priority, token[next+1], 0) ||
                priority > 65535)
                fatal ("invalid priority in MX RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+2],
                        cur_origin))
                fatal ("choked on domain name in MX RDATA",
                       start_line_num);
            fprintf (file, "@%s::%s:%d:%d\n", owner.text,
                 rdomain.text, priority, local_ttl);
        /* A */
        } else if (!strcasecmp (token[next], "A")) {
            char ip[16];
            if (num_tokens - next - 1 != 1)
                fatal ("wrong number of tokens in A RDATA",
                       start_line_num);
            if (sanitize_ip (ip, token[next+1]))
                fatal ("invalid IP address in A RDATA",
                       start_line_num);
            fprintf (file, "+%s:%s:%d\n", owner.text,
                 ip, local_ttl);
        /* AAAA */
        } else if (!strcasecmp (token[next], "AAAA")) {
            unsigned char ipv6_bytes[16];
            if (num_tokens - next - 1 != 1)
                fatal ("wrong number of tokens in AAAA RDATA", start_line_num);
            if (!inet_pton(AF_INET6, token[next+1], ipv6_bytes))
                fatal ("invalid IPv6 address in AAAA RDATA", start_line_num);
            fprintf (file, ":%s:28:", owner.text);
            for (i = 0; i < 16; i++)
                fprintf (file, "\\%03o", ipv6_bytes[i]);
            fprintf (file, ":%d\n", local_ttl);
        /* CNAME */
        } else if (!strcasecmp (token[next], "CNAME")) {
            if (num_tokens - next - 1 != 1)
                fatal ("wrong number of tokens in CNAME RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+1],
                        cur_origin))
                fatal ("choked on domain name in CNAME RDATA",
                       start_line_num);
            fprintf (file, "C%s:%s:%d\n", owner.text,
                 rdomain.text, local_ttl);
        /* PTR */
        } else if (!strcasecmp (token[next], "PTR")) {
            if (num_tokens - next - 1 != 1)
                fatal ("wrong number of tokens in PTR RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+1],
                        cur_origin))
                fatal ("choked on domain name in PTR RDATA",
                       start_line_num);
            fprintf (file, "^%s:%s:%d\n", owner.text,
                 rdomain.text, local_ttl);
        /* TXT */
        } else if (!strcasecmp (token[next], "TXT")) {
            string txt_rdata;
            if (num_tokens - next - 1 < 1)
                fatal ("too few tokens in TXT RDATA",
                       start_line_num);
            fprintf (file, ":%s:16:", owner.text);
            for (i = next + 1; i < num_tokens; i++) {
                if (sanitize_string (&txt_rdata, token[i]))
                    fatal ("choked while sanitizing TXT "
                           "RDATA", start_line_num);
                fprintf (file, "\\%03o%s", txt_rdata.len,
                     txt_rdata.text);
            }
            fprintf (file, ":%d\n", local_ttl);
        /* SRV */
        } else if (!strcasecmp (token[next], "SRV")) {
            unsigned int priority, weight, port;
            if (num_tokens - next - 1 != 4)
                fatal ("wrong number of tokens "
                       "in SRV RDATA", start_line_num);
            if (str_to_uint (&priority, token[next+1], 0) ||
                priority > 65535)
                fatal ("invalid priority in SRV RDATA",
                       start_line_num);
            if (str_to_uint (&weight, token[next+2], 0) ||
                weight > 65535)
                fatal ("invalid weight in SRV RDATA",
                       start_line_num);
            if (str_to_uint (&port, token[next+3], 0) ||
                port > 65535)
                fatal ("invalid port in SRV RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+4],
                        cur_origin))
                fatal ("choked on domain name in SRV "
                       "RDATA", start_line_num);
            if (octal_escape_hostname_labels (&rdomain, rdomain.text)) {
                fatal ("unable to escape hostname labels in SRV RDATA",
                       start_line_num);
            }
            fprintf (file, ":%s:33:\\%03o\\%03o"
                 "\\%03o\\%03o\\%03o\\%03o%s:%d\n",
                 owner.text, priority / 256, priority % 256,
                 weight / 256, weight % 256, port / 256, port % 256,
                 rdomain.text, local_ttl);
        /* other */
        } else {
            warning ("skipping unknown RR type", start_line_num);
        }
    }

    return 0;
}
bool facebook_client::login(const std::string &username,const std::string &password)
{
	handle_entry( "login" );

	username_ = username;
	password_ = password;

	// Access homepage to get initial cookies
	flap( FACEBOOK_REQUEST_HOME, NULL );

	// Prepare login data
	std::string data = "charset_test=%e2%82%ac%2c%c2%b4%2c%e2%82%ac%2c%c2%b4%2c%e6%b0%b4%2c%d0%94%2c%d0%84&locale=en&email=";
	data += utils::url::encode( username );
	data += "&pass="******"&pass_placeHolder=Password&login=Login&persistent=1";

	// Send validation
	http::response resp = flap( FACEBOOK_REQUEST_LOGIN, &data );

	// Process result data
	validate_response(&resp);

	if ( resp.code == HTTP_CODE_FOUND && resp.headers.find("Location") != resp.headers.end() )
	{
		// Check whether some Facebook things are required
		if ( resp.headers["Location"].find("help.php") != std::string::npos )
		{
			client_notify( TranslateT("Login error: Some Facebook things are required.") );
			parent->Log(" ! !  Login error: Some Facebook things are required.");
			// return handle_error( "login", FORCE_DISCONNECT );
		}
		
		// Check whether setting Machine name is required
		if ( resp.headers["Location"].find("/checkpoint/") != std::string::npos )
		{
			resp = flap( FACEBOOK_REQUEST_SETUP_MACHINE );
			
			std::string inner_data = "machine_name=MirandaIM&submit[Save%20Device]=Save%20Device";
			inner_data += "&post_form_id=";
			inner_data += utils::text::source_get_value(&resp.data, 3, "name=\"post_form_id\"", "value=\"", "\"" );
			
			inner_data += "&lsd=";
			inner_data += utils::text::source_get_value(&resp.data, 3, "name=\"lsd\"", "value=\"", "\"" );
			
			inner_data += "&nh=";
			inner_data += utils::text::source_get_value(&resp.data, 3, "name=\"nh\"", "value=\"", "\"" );

			resp = flap( FACEBOOK_REQUEST_SETUP_MACHINE, &inner_data );
			validate_response(&resp);
		}
	}
	
	if ( resp.code == HTTP_CODE_FOUND && resp.headers.find("Location") != resp.headers.end() )
	{
		// Check whether HTTPS connection is required and we don't have enabled it
		if (!this->https_)
		{    
			if ( resp.headers["Location"].find("https://") != std::string::npos )
			{
				client_notify(TranslateT("Your account requires HTTPS connection. Activating."));
				DBWriteContactSettingByte(NULL, parent->m_szModuleName, FACEBOOK_KEY_FORCE_HTTPS, 1);
				this->https_ = true;
			}
		}

	}

	// Check for Device ID
	if ( cookies["datr"].length() )
		DBWriteContactSettingString( NULL, parent->m_szModuleName, FACEBOOK_KEY_DEVICE_ID, cookies["datr"].c_str() );

	switch ( resp.code )
	{
	case HTTP_CODE_FAKE_DISCONNECTED:
	{
		// When is error only because timeout, try login once more
		if ( handle_error( "login" ) )
			return login(username, password);
		else
			return false;
	}

	case HTTP_CODE_OK: // OK page returned, but that is regular login page we don't want in fact
	{ 
		// Check whether captcha code is required
		if ( resp.data.find("id=\"captcha\"") != std::string::npos )
		{
			client_notify( TranslateT("Login error: Captcha code is required. Bad login credentials?") );
			parent->Log(" ! !  Login error: Captcha code is required.");
			return handle_error( "login", FORCE_DISCONNECT );
		}
		
		// Get error message
		std::string error_str = utils::text::trim(
			utils::text::special_expressions_decode(
				utils::text::remove_html( 
					utils::text::edit_html(
						utils::text::source_get_value( &resp.data, 2, "id=\"standard_error\">", "</h2>" ) ) ) ) );

		if ( !error_str.length() )
			error_str = Translate("Unknown login error");
		parent->Log(" ! !  Login error: %s", error_str.c_str());

		std::string message = Translate("Login error: ") + error_str;
		TCHAR* tmessage = mir_a2t(message.c_str());
		client_notify( tmessage );
		mir_free( tmessage );
	}
	case HTTP_CODE_FORBIDDEN: // Forbidden
	case HTTP_CODE_NOT_FOUND: // Not Found
	default:
		return handle_error( "login", FORCE_DISCONNECT );

	case HTTP_CODE_FOUND: // Found and redirected to Home, Logged in, everything is OK
		if ( cookies.find("c_user") != cookies.end() )
		{
			this->self_.user_id = cookies.find("c_user")->second;
			DBWriteContactSettingString(NULL,parent->m_szModuleName,FACEBOOK_KEY_ID,this->self_.user_id.c_str());
			parent->Log("      Got self user id: %s", this->self_.user_id.c_str());
			return handle_success( "login" );
		} else {
			client_notify(TranslateT("Login error, probably bad login credentials."));
			parent->Log(" ! !  Login error, probably bad login credentials.");
			return handle_error( "login", FORCE_DISCONNECT );
		}
	}
}
bool facebook_client::send_message( std::string message_recipient, std::string message_text, std::string *error_text, bool use_inbox )
{
	handle_entry( "send_message" );

	http::response resp;

	if (parent->isInvisible() || use_inbox) {
		// Use inbox send message when invisible
		std::string data = "action=send&body=";
		data += utils::url::encode( message_text );
		data += "&recipients[0]=";
		data += message_recipient;
		data += "&lsd=&fb_dtsg=";
		data += ( dtsg_.length( ) ) ? dtsg_ : "0";
		data += "&post_form_id=";
		data += ( post_form_id_.length( ) ) ? post_form_id_ : "0";

		resp = flap( FACEBOOK_REQUEST_ASYNC, &data );	
	} else {
		// Use standard send message
		std::string data = "msg_text=";
		data += utils::url::encode( message_text );
		data += "&msg_id=";
		data += utils::time::mili_timestamp( );
		data += "%3A";
		data += utils::time::unix_timestamp( );
		data += "&to=";
		data += message_recipient;
		data += "&__user="******"&client_time=";
		data += utils::time::mili_timestamp( );
		data += "&pvs_time&fb_dtsg=";
		data += ( dtsg_.length( ) ) ? dtsg_ : "0";
		data += "&to_offline=false&to_idle=false&lsd&post_form_id_source=AsyncRequest&num_tabs=1";
		data += "&window_id=0&sidebar_launched=false&sidebar_enabled=false&sidebar_capable=false&sidebar_should_show=false&sidebar_visible=false";
		data += "&post_form_id=";
		data += ( post_form_id_.length( ) ) ? post_form_id_ : "0";

		resp = flap( FACEBOOK_REQUEST_MESSAGE_SEND, &data );
	}

	
	validate_response(&resp);
	*error_text = resp.error_text;

	switch ( resp.error_number )
	{
  	case 0: // Everything is OK
		break;

    //case 1356002: // You are offline - wtf??

	case 1356003: // Contact is offline
	{
		HANDLE hContact = parent->ContactIDToHContact( message_recipient );
		if (hContact != NULL)
  			DBWriteContactSettingWord(hContact,parent->m_szModuleName,"Status",ID_STATUS_OFFLINE);
		return false;
	} break;

  	case 1356026: // Contact has alternative client
	{
		client_notify(TranslateT("Need confirmation for sending messages to other clients.\nOpen facebook website and try to send message to this contact again!"));
      /*
          post na url http://www.facebook.com/ajax/chat/post_application_settings.php?__a=1

          enable_and_send      Povolit a odeslat                                                                                                                                                                                                                                                                                                                                                                                                                               
          to_send              AQCoweMPeszBoKpd4iahcOyhmh0kiTYIhv1b5wCtuBiD0AaPVZIdEp3Pf5JMBmQ-9wf0ju-xdi-VRuk0ERk_I7XzI5dVJCs6-B0FExTZhspD-4-kTZLmZI-_M6fIuF2328yMyT3R3UEUmMV8P9MHcZwu-_pS3mOhsaHf6rIVcQ2rocSqLKi03wLKCfg0m8VsptPADWpOI-UNcIo-xl1PAoC1yVnL2wEXEtnF1qI_xFcmlJZ40AOONfIF_LS_lBrGYA-oCWLUK-GLHtQAHjO8aDeNXDU8Jk7Z_ES-_oAHee2PVLHcG_ACHXpasE7Iu3XFLMrdN2hjM96AjPRIf0Vk8gBZzfW_lUspakZmXxMI7iSNQE8lourK_6B3Z1s4UHxDZCNXYuc9gh70nm_xnaxnF9K1bR00s4MltnFjUT_3ypThzA  
          __d                  1                                                                                                                                                                                                                                                                                                                                                                                                                                               
          post_form_id         c73ebd9d94b7449c40e6965410fcdcf6                                                                                                                                                                                                                                                                                                                                                                                                                
          fb_dtsg              Tb-T9                                                                                                                                                                                                                                                                                                                                                                                                                                           
          lsd                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
          post_form_id_source  AsyncRequest                                                                                                                                                                                                                                                                                                                                                                                                                                    
          */
		return false;
	} break;
 
    default: // Other error
		return false;
 	}

	switch ( resp.code )
	{
	case HTTP_CODE_OK:
		return handle_success( "send_message" );

	case HTTP_CODE_FAKE_ERROR:
	case HTTP_CODE_FAKE_DISCONNECTED:
	default:
		*error_text = Translate("Timeout when sending message.");

		handle_error( "send_message" );
		return false;
	}
}
bool facebook_client::channel( )
{
	handle_entry( "channel" );

	// Get update
	http::response resp = flap( FACEBOOK_REQUEST_MESSAGES_RECEIVE );

	// Process result data
	validate_response(&resp);

	if ( resp.code != HTTP_CODE_OK )
	{
		// Something went wrong
	}
	else if ( resp.data.find( "\"t\":\"continue\"" ) != std::string::npos )
	{
		// Everything is OK, no new message received
	}
	else if ( resp.data.find( "\"t\":\"fullReload\"" ) != std::string::npos )
	{
		// Something went wrong (server flooding?)

		parent->Log("! ! ! Requested full reload");
    
		this->chat_sequence_num_ = utils::text::source_get_value2( &resp.data, "\"seq\":", ",}" );
		parent->Log("      Got self sequence number: %s", this->chat_sequence_num_.c_str());

		this->chat_reconnect_reason_ = utils::text::source_get_value2( &resp.data, "\"reason\":", ",}" );
		parent->Log("      Reconnect reason: %s", this->chat_reconnect_reason_.c_str());
	}
	else if ( resp.data.find( "\"t\":\"refresh\"" ) != std::string::npos )
	{
		// Something went wrong (server flooding?)
		parent->Log("! ! ! Requested channel refresh");
    
		this->chat_reconnect_reason_ = utils::text::source_get_value2( &resp.data, "\"reason\":", ",}" );
		parent->Log("      Reconnect reason: %s", this->chat_reconnect_reason_.c_str());

		this->chat_sequence_num_ = utils::text::source_get_value2( &resp.data, "\"seq\":", ",}" );
		parent->Log("      Got self sequence number: %s", this->chat_sequence_num_.c_str());

		return this->reconnect( );
	} else {
		// Something has been received, throw to new thread to process
		std::string* response_data = new std::string( resp.data );
		ForkThread( &FacebookProto::ProcessMessages, this->parent, ( void* )response_data );

		// Increment sequence number
		this->chat_sequence_num_ = utils::text::source_get_value2( &resp.data, "\"seq\":", ",}" );
		parent->Log("      Got self sequence number: %s", this->chat_sequence_num_.c_str());
	}

	// Return
	switch ( resp.code )
	{
	case HTTP_CODE_OK:
		return handle_success( "channel" );

	case HTTP_CODE_FAKE_DISCONNECTED:
	case HTTP_CODE_FAKE_ERROR:
	default:
		// Testing workaround for channel change
		if (!this->chat_channel_jslogger_.empty())
			this->chat_channel_jslogger_ = "_";
		else
			this->chat_channel_jslogger_.clear();
		
		return handle_error( "channel" );
	}
}
bool Omegle_client::start()
{
	handle_entry( "start" );

	this->server_ = get_server();
	//parent->debugLogA("Chosing server %s", this->server_.c_str());
	//std::string log = Translate("Chosing server: ") + this->server_;
	//parent->UpdateChat(NULL, log.c_str());

	std::string data;

	if (this->spy_mode_) {
		//// get last server from list, which is for spy mode
		//this->server_ = servers[SIZEOF(servers)-1];

		if (this->question_.empty()) {
			data = "&wantsspy=1";
		} else {
			data = "&ask=" + utils::url::encode(this->question_);
			data += "&cansavequestion=";
			data += db_get_b(NULL, parent->m_szModuleName, OMEGLE_KEY_REUSE_QUESTION, 0) ? "1" : "0";
		}
	}
	else if ( db_get_b(NULL, parent->m_szModuleName, OMEGLE_KEY_MEET_COMMON, 0))
	{
		DBVARIANT dbv;
		if (!db_get_utf(NULL, parent->m_szModuleName, OMEGLE_KEY_INTERESTS, &dbv))
		{
			std::string topics = dbv.pszVal;
			std::string topic;
		
			db_free(&dbv);

			std::string::size_type pos = 0;
			std::string::size_type pos2 = 0;
			while ((pos2 = topics.find(",", pos)) != std::string::npos) {
				topic = topics.substr(pos, pos2 - pos);
				topic = utils::text::trim(topic);

				if (!topic.empty()) {
					if (pos > 0)
						data += ",";

					data += "\"" + topic + "\"";
				}

				pos = pos2 + 1;
			}
		
			topic = topics.substr(pos);
			topic = utils::text::trim(topic);
			if (!topic.empty()) {			
				if (pos > 0)
					data += ",";
				data += "\"" + topic + "\"";			
			}

			parent->debugLogA("TOPICS: %s", data.c_str());

			if (!data.empty()) {
				data = "[" + data + "]";
				data = "&topics=" + utils::url::encode(data);
			}

			//// get any server but last, which is for spy mode
			//this->server_ = get_server(true);
		}
	}

	if (db_get_b(NULL, parent->m_szModuleName, OMEGLE_KEY_SERVER_INFO, 0))
	{
		std::string count = get_page( OMEGLE_REQUEST_COUNT );
		if (!count.empty()) {
			char str[255];
			mir_snprintf(str, sizeof(str), Translate("Connected to server %s. There are %s users online now."), server_.c_str(), count.c_str());

			TCHAR *msg = mir_a2t(str);
			parent->UpdateChat(NULL, msg);
			mir_free(msg);
		}
	} else {
		char str[255];
		mir_snprintf(str, sizeof(str), Translate("Connected to server %s."), server_.c_str());

		TCHAR *msg = mir_a2t(str);
		parent->UpdateChat(NULL, msg);
		mir_free(msg);
	}

	// Send validation
	http::response resp = flap( OMEGLE_REQUEST_START, NULL, &data );

	switch ( resp.code )
	{
	case HTTP_CODE_FAKE_DISCONNECTED:
	{
		// If is is only timeout error, try login once more
		if ( handle_error( "start" ))
			return start();
		else
			return false;
	}

	case HTTP_CODE_OK:
	{ 
		if (!resp.data.empty()) {
			this->chat_id_ = resp.data.substr(1,resp.data.length()-2);
			this->state_ = STATE_WAITING;

			return handle_success( "start" );
		} else {
			return handle_error( "start", FORCE_DISCONNECT );
		}
	}

	default:
		return handle_error( "start", FORCE_DISCONNECT );
	}
}
bool Omegle_client::events( )
{
	handle_entry( "events" );

	std::string data = "id=" + this->chat_id_;

	// Get update
	http::response resp = flap( OMEGLE_REQUEST_EVENTS, &data );

	// Return
	switch ( resp.code )
	{
	case HTTP_CODE_OK:
	{
		if ( resp.data == "null" ) {
			// Everything is OK, no new message received -- OR it is a problem
			// TODO: if we are waiting for Stranger with common likes, then we should try standard Stranger if this takes too long
			return handle_error( "events" );
		} else if ( resp.data == "fail" ) {
			// Something went wrong
			return handle_error( "events" );
		}
		
		std::string::size_type pos = 0;
		bool newStranger = false;
		bool waiting = false;
		
		if ( resp.data.find( "[\"waiting\"]" ) != std::string::npos ) {
			// We are just waiting for new Stranger
			waiting = true;
		}

		/*if ( (pos = resp.data.find( "[\"count\"," )) != std::string::npos ) {
			// We got info about count of connected people there
			pos += 9;

			std::string count = utils::text::trim( resp.data.substr(pos, resp.data.find("]", pos) - pos));

			char str[255];
			mir_snprintf(str, sizeof(str), Translate("On whole Omegle are %s strangers online now."), count.c_str());
			
			TCHAR *msg = mir_a2t_cp(str,CP_UTF8);
			parent->UpdateChat(NULL, msg);
			mir_free(msg);
		}*/

		if ( (pos = resp.data.find( "[\"serverMessage\", \"" )) != std::string::npos ) {
			// We got server message
			pos += 19;

			std::string message = utils::text::trim( resp.data.substr(pos, resp.data.find("\"]", pos) - pos));
			TCHAR *tstr = Langpack_PcharToTchar(message.c_str());
			parent->UpdateChat(NULL, tstr);
			mir_free(tstr);
		}

		if ( resp.data.find( "[\"connected\"]" ) != std::string::npos ) {
			// Stranger connected
			if (this->spy_mode_ && !this->question_.empty()) {
				parent->AddChatContact(TranslateT("Stranger 1"));
				parent->AddChatContact(TranslateT("Stranger 2"));
				this->state_ = STATE_SPY;
			} else {			
				parent->AddChatContact(TranslateT("Stranger"));
				this->state_ = STATE_ACTIVE;
			}

			newStranger = true;
			waiting = false;
		}

		if ( (pos = resp.data.find( "[\"commonLikes\"," )) != std::string::npos ) {
			pos += 18;
			std::string like = resp.data.substr(pos, resp.data.find("\"]", pos) - pos);
			utils::text::replace_all(&like, "\", \"", ", ");

			parent->debugLogA("Got common likes: '%s'", like.c_str());

			like = Translate("You and the Stranger both like: ") + like;

			TCHAR *msg = mir_a2t(like.c_str());
			parent->SetTopic(msg);
			mir_free(msg);
		}

		if ( (pos = resp.data.find( "[\"question\"," )) != std::string::npos ) {
			pos += 14;

			std::string question = utils::text::trim(
				utils::text::special_expressions_decode(
					utils::text::slashu_to_utf8(
						resp.data.substr(pos, resp.data.find("\"]", pos) - pos)	)) );

			TCHAR *msg = mir_a2t_cp(question.c_str(),CP_UTF8);
			parent->SetTopic(msg);
			mir_free(msg);
		}

		if ( resp.data.find( "[\"typing\"]" ) != std::string::npos
			|| resp.data.find( "[\"spyTyping\"," ) != std::string::npos )
		{
			// Stranger is typing, not supported by chat module yet
			SkinPlaySound( "StrangerTyp" );
			CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)parent->GetChatHandle(), (LPARAM)TranslateT("Stranger is typing."));
		}

		if ( resp.data.find( "[\"stoppedTyping\"]" ) != std::string::npos
			|| resp.data.find( "[\"spyStoppedTyping\"," ) != std::string::npos )
		{
			// Stranger stopped typing, not supported by chat module yet
			SkinPlaySound( "StrangerTypStop" );
			CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)parent->GetChatHandle(), (LPARAM)TranslateT("Stranger stopped typing."));
		}

		pos = 0;
		while ( (pos = resp.data.find( "[\"gotMessage\",", pos )) != std::string::npos ) {
			pos += 16;

			std::string message = utils::text::trim(
				utils::text::special_expressions_decode(
					utils::text::slashu_to_utf8(
						resp.data.substr(pos, resp.data.find("\"]", pos) - pos)	)) );
			
			if (state_ == STATE_ACTIVE) {
				TCHAR *msg = mir_a2t_cp(message.c_str(),CP_UTF8);
				parent->UpdateChat(TranslateT("Stranger"), msg);
				mir_free(msg);

				CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)parent->GetChatHandle(), 0);
			}
		}

		pos = 0;
		while ( (pos = resp.data.find( "[\"spyMessage\",", pos )) != std::string::npos ) {
			pos += 16;

			std::string message = resp.data.substr(pos, resp.data.find("\"]", pos) - pos);
			
			if (state_ == STATE_SPY) {
				std::string stranger = message.substr(0, message.find("\""));
				message = message.substr(stranger.length() + 4);

				message = utils::text::trim(
							utils::text::special_expressions_decode(
								utils::text::slashu_to_utf8( message )) );
				
				stranger = Translate(stranger.c_str());
				
				TCHAR *str = mir_a2t_cp(stranger.c_str(), CP_UTF8);				
				TCHAR *msg = mir_a2t_cp(message.c_str(), CP_UTF8);

				parent->UpdateChat(str, msg);

				mir_free(msg);
				mir_free(str);
			}
		}

		if ( resp.data.find( "[\"strangerDisconnected\"]" ) != std::string::npos ) {
			// Stranger disconnected
			if (db_get_b(NULL, parent->m_szModuleName, OMEGLE_KEY_DONT_STOP, 0))
			{
				SkinPlaySound( "StrangerChange" );
				parent->NewChat();
			}
			else			
				parent->StopChat(false);
		}

		if ( (pos = resp.data.find( "[\"spyDisconnected\"," )) != std::string::npos ) {
			pos += 21;

			std::string stranger = utils::text::trim(
				utils::text::special_expressions_decode(
					utils::text::slashu_to_utf8(
						resp.data.substr(pos, resp.data.find("\"]", pos) - pos)	)) );

			char str[255];
			mir_snprintf(str, sizeof(str), Translate("%s disconnected."), Translate(stranger.c_str()));
			
			TCHAR *msg = mir_a2t(str);
			parent->UpdateChat(NULL, msg);
			mir_free(msg);

			// Stranger disconnected
			if (db_get_b(NULL, parent->m_szModuleName, OMEGLE_KEY_DONT_STOP, 0))
			{
				SkinPlaySound( "StrangerChange" );
				parent->NewChat();
			}
			else
				parent->StopChat(false);
		}

		if ( resp.data.find( "[\"recaptchaRequired\"" ) != std::string::npos ) {
			// Nothing to do with recaptcha
			parent->UpdateChat(NULL, TranslateT("Recaptcha is required.\nOpen http://omegle.com , solve Recaptcha and try again."));
			parent->StopChat(false);
		}

		if ( resp.data.find( "[\"recaptchaRejected\"]" ) != std::string::npos ) {
			// Nothing to do with recaptcha
			parent->StopChat(false);
		}

		if ( (pos = resp.data.find( "[\"error\"," )) != std::string::npos ) {
			pos += 11;

			std::string error = utils::text::trim(
				utils::text::special_expressions_decode(
					utils::text::slashu_to_utf8(
						resp.data.substr(pos, resp.data.find("\"]", pos) - pos)	)) );

			error = Translate("Error: ") + error;

			TCHAR *msg = mir_a2t(error.c_str());
			parent->UpdateChat(NULL, msg);
			mir_free(msg);
		}
				
		if (newStranger && state_ != STATE_SPY) {
			// We got new stranger in this event, lets say him "Hi message" if enabled			
			if ( db_get_b( NULL, parent->m_szModuleName, OMEGLE_KEY_HI_ENABLED, 0 )) {
				DBVARIANT dbv;
				if ( !db_get_utf( NULL, parent->m_szModuleName, OMEGLE_KEY_HI, &dbv )) {
					std::string *message = new std::string(dbv.pszVal);
					db_free(&dbv);
	
					parent->debugLogA("**Chat - saying Hi! message");
					parent->ForkThread(&OmegleProto::SendMsgWorker, message);
				}
				else parent->debugLogA("**Chat - Hi message is enabled but not used");
			}
		}

		if (waiting) {
			// If we are only waiting in this event...
			parent->UpdateChat(NULL, TranslateT("We are still waiting..."));
		}

		return handle_success( "events" );
	}

	case HTTP_CODE_FAKE_DISCONNECTED:
		// timeout
		return handle_success( "events" );

	case HTTP_CODE_FAKE_ERROR:
	default:
		return handle_error( "events" );
	}
}
Exemple #30
0
bool facebook_client::channel()
{
	handle_entry("channel");

	// Get update
	http::response resp = flap(REQUEST_MESSAGES_RECEIVE);

	if (resp.data.empty()) {
		// Something went wrong
		return handle_error("channel");
	}

	std::string type = utils::text::source_get_value(&resp.data, 2, "\"t\":\"", "\"");
	if (type == "continue" || type == "heartbeat") {
		// Everything is OK, no new message received
	}
	else if (type == "lb") {
		// Some new stuff (idk how does it work yet)
		this->chat_channel_host_ = utils::text::source_get_value(&resp.data, 2, "\"vip\":\"", "\"");
		parent->debugLogA("      Got self channel host: %s", this->chat_channel_host_.c_str());

		this->chat_sticky_num_ = utils::text::source_get_value2(&resp.data, "\"sticky\":\"", "\"");
		parent->debugLogA("      Got self sticky number: %s", this->chat_sticky_num_.c_str());
	}
	else if (type == "fullReload" || type == "refresh") {
		// Something went wrong (server flooding?)
		parent->debugLogA("! ! ! Requested %s", type.c_str());

		this->chat_sequence_num_ = utils::text::source_get_value2(&resp.data, "\"seq\":", ",}");
		parent->debugLogA("      Got self sequence number: %s", this->chat_sequence_num_.c_str());

		this->chat_reconnect_reason_ = utils::text::source_get_value2(&resp.data, "\"reason\":", ",}");
		parent->debugLogA("      Reconnect reason: %s", this->chat_reconnect_reason_.c_str());

		if (type == "refresh")
			return this->reconnect();
	}
	else {
		// Something has been received, throw to new thread to process
		std::string* response_data = new std::string(resp.data);
		parent->ForkThread(&FacebookProto::ProcessMessages, response_data);

		// Increment sequence number
		this->chat_sequence_num_ = utils::text::source_get_value2(&resp.data, "\"seq\":", ",}");
		parent->debugLogA("      Got self sequence number: %s", this->chat_sequence_num_.c_str());
	}

	// Return
	switch (resp.code)
	{
	case HTTP_CODE_OK:
		return handle_success("channel");

	case HTTP_CODE_GATEWAY_TIMEOUT:
		// Maybe we have same clientid as other connected client, try to generate different one
		this->chat_clientid_ = utils::text::rand_string(8, "0123456789abcdef");

		// Intentionally fall to handle_error() below
	case HTTP_CODE_FAKE_DISCONNECTED:
	case HTTP_CODE_FAKE_ERROR:
	default:
		return handle_error("channel");
	}
}