-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathmain.cpp
More file actions
2466 lines (2154 loc) · 81.3 KB
/
main.cpp
File metadata and controls
2466 lines (2154 loc) · 81.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "utils.h"
#include "glib.h"
// win32/libc_interface.h defines its own socket(), read() and so on.
// We don't want to use it here.
#define _LIBC_INTERFACE_H_ 1
#include "purple.h"
#include <algorithm>
#include <iostream>
#include <fstream>
#include "transport/NetworkPlugin.h"
#include "transport/Logging.h"
#include "transport/Config.h"
#include "transport/StorageBackend.h"
#include "geventloop.h"
#include "Swiften/SwiftenCompat.h"
// #include "valgrind/memcheck.h"
#if !defined(__FreeBSD__) && !defined(__APPLE__)
#include "malloc.h"
#endif
#include "errno.h"
#include <boost/make_shared.hpp>
#include <boost/locale.hpp>
#include <boost/locale/conversion.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#ifdef WITH_LIBEVENT
#include <event.h>
#endif
#ifdef WIN32
#include "win32/win32dep.h"
#define close closesocket
#define ssize_t SSIZE_T
#include <process.h>
#define getpid _getpid
#endif
#include "purple_defs.h"
DEFINE_LOGGER(logger_libpurple, "libpurple");
DEFINE_LOGGER(logger, "backend");
/* Additional PURPLE_MESSAGE_* flags as a hack to track the origin of the message. */
typedef enum {
PURPLE_MESSAGE_SPECTRUM2_ORIGINATED = 0x80000000,
} PurpleMessageSpectrum2Flags;
int main_socket;
static int writeInput;
bool firstPing = true;
using namespace Transport;
template <class T> T fromString(const std::string &str) {
T i;
std::istringstream os(str);
os >> i;
return i;
}
template <class T> std::string stringOf(T object) {
std::ostringstream os;
os << object;
return (os.str());
}
static std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
static std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
return split(s, delim, elems);
}
static void transportDataReceived(gpointer data, gint source, PurpleInputCondition cond);
class SpectrumNetworkPlugin;
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Config> config;
SpectrumNetworkPlugin *np;
StorageBackend *storagebackend;
static std::string host;
static int port = 10000;
struct FTData {
unsigned long id;
unsigned long timer;
bool paused;
};
struct NodeCache {
PurpleAccount *account;
std::map<PurpleBlistNode *, int> nodes;
int timer;
};
bool caching = true;
static void *notify_user_info(PurpleConnection *gc, const char *who, PurpleNotifyUserInfo *user_info);
static gboolean ft_ui_ready(void *data) {
PurpleXfer *xfer = (PurpleXfer *) data;
FTData *ftdata = (FTData *) xfer->ui_data;
ftdata->timer = 0;
purple_xfer_ui_ready_wrapped((PurpleXfer *) data);
return FALSE;
}
struct authRequest {
PurpleAccountRequestAuthorizationCb authorize_cb;
PurpleAccountRequestAuthorizationCb deny_cb;
void *user_data;
std::string who;
PurpleAccount *account;
std::string mainJID; // JID of user connected with this request
};
struct inputRequest {
PurpleRequestInputCb ok_cb;
void *user_data;
std::string who;
PurpleAccount *account;
std::string mainJID; // JID of user connected with this request
};
static void *requestAction(const char *title, const char *primary, const char *secondary, int default_action, PurpleAccount *account, const char *who,PurpleConversation *conv, void *user_data, size_t action_count, va_list actions){
std::string t(title ? title : "NULL");
if (t == "SSL Certificate Verification") {
if (CONFIG_BOOL_DEFAULTED(config, "service.verify_certs", false)) {
LOG4CXX_INFO(logger, "rejecting SSL certificate");
va_arg(actions, char *);
va_arg(actions, GCallback);
} else {
LOG4CXX_INFO(logger, "accepting SSL certificate");
}
va_arg(actions, char *);
((PurpleRequestActionCb) va_arg(actions, GCallback)) (user_data, 2);
}
else if (t == "Plaintext Authentication") {
LOG4CXX_INFO(logger, "Rejecting plaintext authentification");
va_arg(actions, char *);
va_arg(actions, GCallback);
va_arg(actions, char *);
((PurpleRequestActionCb) va_arg(actions, GCallback)) (user_data, 2);
}
else {
if (title) {
std::string headerString(title);
LOG4CXX_INFO(logger, "header string: " << headerString);
if (headerString == "SSL Certificate Verification") {
if (CONFIG_BOOL_DEFAULTED(config, "service.verify_certs", false)) {
va_arg(actions, char *);
va_arg(actions, GCallback);
}
va_arg(actions, char *);
((PurpleRequestActionCb) va_arg(actions, GCallback)) (user_data, 2);
}
}
}
return NULL;
}
static std::string getAlias(PurpleBuddy *m_buddy) {
std::string alias;
PurpleContact *contact = PURPLE_CONTACT(PURPLE_BLIST_NODE(m_buddy)->parent);
if (contact && contact->alias) {
alias = contact->alias;
}
else if (purple_buddy_get_alias_wrapped(m_buddy)) {
alias = (std::string) purple_buddy_get_alias_wrapped(m_buddy);
}
else {
alias = (std::string) purple_buddy_get_server_alias_wrapped(m_buddy);
}
return alias;
}
static boost::mutex dblock;
static std::string OAUTH_TOKEN = "hangouts_oauth_token";
static std::string STEAM_ACCESS_TOKEN = "steammobile_access_token";
static bool getUserOAuthToken(const std::string user, std::string &token)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return false;
}
token = "";
int type = TYPE_STRING;
storagebackend->getUserSetting((long)info.id, OAUTH_TOKEN, type, token);
return true;
}
static bool storeUserOAuthToken(const std::string user, const std::string OAuthToken)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return false;
}
storagebackend->updateUserSetting((long)info.id, OAUTH_TOKEN, OAuthToken);
return true;
}
static bool getUserSteamAccessToken(const std::string user, std::string &token)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return false;
}
token = "";
int type = TYPE_STRING;
storagebackend->getUserSetting((long)info.id, STEAM_ACCESS_TOKEN, type, token);
return true;
}
static bool storeUserSteamAccessToken(const std::string user, const std::string token)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return false;
}
storagebackend->updateUserSetting((long)info.id, STEAM_ACCESS_TOKEN, token);
return true;
}
class SpectrumNetworkPlugin : public NetworkPlugin {
public:
SpectrumNetworkPlugin() : NetworkPlugin() {
LOG4CXX_INFO(logger, "Starting libpurple backend " << SPECTRUM_VERSION);
}
void handleExitRequest() {
LOG4CXX_INFO(logger, "Exiting...");
exit(0);
}
void getProtocolAndName(const std::string &legacyName, std::string &name, std::string &protocol) {
name = legacyName;
protocol = CONFIG_STRING(config, "service.protocol");
if (protocol == "any") {
protocol = name.substr(0, name.find("."));
name = name.substr(name.find(".") + 1);
}
}
void setDefaultAvatar(PurpleAccount *account, const std::string &legacyName) {
char* contents;
gsize length;
gboolean ret = false;
if (!CONFIG_STRING(config, "backend.avatars_directory").empty()) {
std::string f = CONFIG_STRING(config, "backend.avatars_directory") + "/" + legacyName;
ret = g_file_get_contents (f.c_str(), &contents, &length, NULL);
}
if (!CONFIG_STRING(config, "backend.default_avatar").empty() && !ret) {
ret = g_file_get_contents (CONFIG_STRING(config, "backend.default_avatar").c_str(),
&contents, &length, NULL);
}
if (ret) {
purple_buddy_icons_set_account_icon_wrapped(account, (guchar *) contents, length);
}
}
void setDefaultAccountOptions(PurpleAccount *account) {
int i = 0;
Config::SectionValuesCont purpleConfigValues = config->getSectionValues("purple");
BOOST_FOREACH ( const Config::SectionValuesCont::value_type & keyItem, purpleConfigValues )
{
std::string key = keyItem.first;
std::string strippedKey = boost::erase_first_copy(key, "purple.");
if (strippedKey == "fb_api_key" || strippedKey == "fb_api_secret") {
purple_account_set_bool_wrapped(account, "auth_fb", TRUE);
}
PurplePlugin *plugin = purple_find_prpl_wrapped(purple_account_get_protocol_id_wrapped(account));
PurplePluginProtocolInfo *prpl_info = PURPLE_PLUGIN_PROTOCOL_INFO(plugin);
bool found = false;
for (GList *l = prpl_info->protocol_options; l != NULL; l = l->next) {
PurpleAccountOption *option = (PurpleAccountOption *) l->data;
PurplePrefType type = purple_account_option_get_type_wrapped(option);
std::string key2(purple_account_option_get_setting_wrapped(option));
if (strippedKey != key2) {
continue;
}
found = true;
switch (type) {
case PURPLE_PREF_BOOLEAN:
purple_account_set_bool_wrapped(account, strippedKey.c_str(), keyItem.second.as<bool>());
break;
case PURPLE_PREF_INT:
purple_account_set_int_wrapped(account, strippedKey.c_str(), fromString<int>(keyItem.second.as<std::string>()));
break;
case PURPLE_PREF_STRING:
case PURPLE_PREF_STRING_LIST:
purple_account_set_string_wrapped(account, strippedKey.c_str(), keyItem.second.as<std::string>().c_str());
break;
default:
continue;
}
break;
}
if (!found) {
purple_account_set_string_wrapped(account, strippedKey.c_str(), keyItem.second.as<std::string>().c_str());
}
i++;
}
char* contents;
gsize length;
gboolean ret = g_file_get_contents ("gfire.cfg", &contents, &length, NULL);
if (ret) {
purple_account_set_int_wrapped(account, "version", fromString<int>(std::string(contents, length)));
}
if (CONFIG_STRING(config, "service.protocol") == "prpl-novell") {
std::string username(purple_account_get_username_wrapped(account));
std::vector <std::string> u = split(username, '@');
purple_account_set_username_wrapped(account, (const char*) u.front().c_str());
std::vector <std::string> s = split(u.back(), ':');
purple_account_set_string_wrapped(account, "server", s.front().c_str());
purple_account_set_int_wrapped(account, "port", atoi(s.back().c_str()));
}
if (!CONFIG_STRING_DEFAULTED(config, "proxy.type", "").empty()) {
PurpleProxyInfo *info = purple_proxy_info_new_wrapped();
if (CONFIG_STRING_DEFAULTED(config, "proxy.type", "") == "http") {
purple_proxy_info_set_type_wrapped(info, PURPLE_PROXY_HTTP);
}
else if (CONFIG_STRING_DEFAULTED(config, "proxy.type", "") == "socks4") {
purple_proxy_info_set_type_wrapped(info, PURPLE_PROXY_SOCKS4);
}
else if (CONFIG_STRING_DEFAULTED(config, "proxy.type", "") == "socks5") {
purple_proxy_info_set_type_wrapped(info, PURPLE_PROXY_SOCKS5);
}
else {
LOG4CXX_ERROR(logger, "Unknown proxy.type " << CONFIG_STRING_DEFAULTED(config, "proxy.type", ""));
}
info->username = NULL;
info->password = NULL;
purple_proxy_info_set_type_wrapped(info, PURPLE_PROXY_SOCKS5);
purple_proxy_info_set_host_wrapped(info, CONFIG_STRING_DEFAULTED(config, "proxy.host", "").c_str());
if (CONFIG_INT_DEFAULTED(config, "proxy.port", 0)) {
purple_proxy_info_set_port_wrapped(info, CONFIG_INT_DEFAULTED(config, "proxy.port", 0));
}
if (!CONFIG_STRING_DEFAULTED(config, "proxy.username", "").empty()) {
purple_proxy_info_set_username_wrapped(info, CONFIG_STRING_DEFAULTED(config, "proxy.username", "").c_str());
}
if (!CONFIG_STRING_DEFAULTED(config, "proxy.password", "").empty()) {
purple_proxy_info_set_password_wrapped(info, CONFIG_STRING_DEFAULTED(config, "proxy.password", "").c_str());
}
purple_account_set_proxy_info_wrapped(account, info);
}
}
void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
PurpleAccount *account = NULL;
std::string name;
std::string protocol;
getProtocolAndName(legacyName, name, protocol);
if (password.empty() && protocol != "prpl-telegram" && protocol != "prpl-hangouts") {
LOG4CXX_INFO(logger, name.c_str() << ": Empty password");
np->handleDisconnected(user, 1, "Empty password.");
return;
}
if (protocol == "prpl-hangouts") {
adminLegacyName = "hangouts";
adminAlias = "hangouts";
}
else if (protocol == "prpl-steam-mobile") {
adminLegacyName = "steam-mobile";
adminAlias = "steam-mobile";
}
if (!purple_find_prpl_wrapped(protocol.c_str())) {
LOG4CXX_INFO(logger, name.c_str() << ": Invalid protocol '" << protocol << "'");
np->handleDisconnected(user, 1, "Invalid protocol " + protocol);
return;
}
if (purple_accounts_find_wrapped(name.c_str(), protocol.c_str()) != NULL) {
account = purple_accounts_find_wrapped(name.c_str(), protocol.c_str());
if (m_accounts.find(account) != m_accounts.end() && m_accounts[account] != user) {
LOG4CXX_INFO(logger, "Account '" << name << "' is already used by '" << m_accounts[account] << "'");
np->handleDisconnected(user, 1, "Account '" + name + "' is already used by '" + m_accounts[account] + "'");
return;
}
LOG4CXX_INFO(logger, "Using previously created account with name '" << name.c_str() << "' and protocol '" << protocol << "'");
}
else {
LOG4CXX_INFO(logger, "Creating account with name '" << name.c_str() << "' and protocol '" << protocol << "'");
account = purple_account_new_wrapped(name.c_str(), protocol.c_str());
purple_accounts_add_wrapped(account);
}
m_sessions[user] = account;
m_accounts[account] = user;
// Default avatar
setDefaultAvatar(account, legacyName);
purple_account_set_password_wrapped(account, password.c_str());
purple_account_set_bool_wrapped(account, "custom_smileys", FALSE);
purple_account_set_bool_wrapped(account, "direct_connect", FALSE);
purple_account_set_bool_wrapped(account, "compat-verification", TRUE);
if (protocol == "prpl-hangouts") {
std::string token;
if (getUserOAuthToken(user, token)) {
purple_account_set_password_wrapped(account, token.c_str());
}
}
else if (protocol == "prpl-steam-mobile") {
std::string token;
if (getUserSteamAccessToken(user, token)) {
purple_account_set_string_wrapped(account, "access_token", token.c_str());
}
}
setDefaultAccountOptions(account);
// Enable account + privacy lists
purple_account_set_enabled_wrapped(account, "spectrum", TRUE);
#if PURPLE_MAJOR_VERSION >= 2 && PURPLE_MINOR_VERSION >= 7
if (CONFIG_BOOL(config, "service.enable_privacy_lists")) {
purple_account_set_privacy_type_wrapped(account, PURPLE_PRIVACY_DENY_USERS);
}
#endif
// Set the status
const PurpleStatusType *status_type = purple_account_get_status_type_with_primitive_wrapped(account, PURPLE_STATUS_AVAILABLE);
if (status_type != NULL) {
purple_account_set_status_wrapped(account, purple_status_type_get_id_wrapped(status_type), TRUE, NULL);
}
// OAuth helper
if (protocol == "prpl-hangouts") {
LOG4CXX_INFO(logger, user << ": Adding Buddy " << adminLegacyName << " " << adminAlias);
handleBuddyChanged(user, adminLegacyName, adminAlias, std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
}
}
void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
PurpleAccount *account = m_sessions[user];
if (account) {
if (account->ui_data) {
NodeCache *cache = (NodeCache *) account->ui_data;
purple_timeout_remove_wrapped(cache->timer);
delete cache;
account->ui_data = NULL;
}
if (purple_account_get_int_wrapped(account, "version", 0) != 0) {
std::string data = stringOf(purple_account_get_int_wrapped(account, "version", 0));
g_file_set_contents ("gfire.cfg", data.c_str(), data.size(), NULL);
}
// VALGRIND_DO_LEAK_CHECK;
m_sessions.erase(user);
purple_account_disconnect_wrapped(account);
purple_account_set_enabled_wrapped(account, "spectrum", FALSE);
m_accounts.erase(account);
purple_accounts_delete_wrapped(account);
#ifndef WIN32
#if !defined(__FreeBSD__) && !defined(__APPLE__)
malloc_trim(0);
#endif
#endif
// VALGRIND_DO_LEAK_CHECK;
}
}
void handleStatusChangeRequest(const std::string &user, int status, const std::string &statusMessage) {
PurpleAccount *account = m_sessions[user];
if (account) {
int st;
switch(status) {
case pbnetwork::STATUS_AWAY: {
st = PURPLE_STATUS_AWAY;
if (!purple_account_get_status_type_with_primitive_wrapped(account, PURPLE_STATUS_AWAY))
st = PURPLE_STATUS_EXTENDED_AWAY;
else
st = PURPLE_STATUS_AWAY;
break;
}
case pbnetwork::STATUS_DND: {
st = PURPLE_STATUS_UNAVAILABLE;
break;
}
case pbnetwork::STATUS_XA: {
if (!purple_account_get_status_type_with_primitive_wrapped(account, PURPLE_STATUS_EXTENDED_AWAY))
st = PURPLE_STATUS_AWAY;
else
st = PURPLE_STATUS_EXTENDED_AWAY;
break;
}
case pbnetwork::STATUS_NONE: {
st = PURPLE_STATUS_OFFLINE;
break;
}
case pbnetwork::STATUS_INVISIBLE:
st = PURPLE_STATUS_INVISIBLE;
break;
default:
st = PURPLE_STATUS_AVAILABLE;
break;
}
gchar *_markup = purple_markup_escape_text_wrapped(statusMessage.c_str(), -1);
std::string markup(_markup);
g_free(_markup);
// we are already connected so we have to change status
const PurpleStatusType *status_type = purple_account_get_status_type_with_primitive_wrapped(account, (PurpleStatusPrimitive) st);
if (status_type != NULL) {
// send presence to legacy network
if (!markup.empty()) {
purple_account_set_status_wrapped(account, purple_status_type_get_id_wrapped(status_type), TRUE, "message", markup.c_str(), NULL);
}
else {
purple_account_set_status_wrapped(account, purple_status_type_get_id_wrapped(status_type), TRUE, NULL);
}
}
}
}
void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml, const std::string &id) {
PurpleAccount *account = m_sessions[user];
if (account) {
LOG4CXX_INFO(logger, "Sending message to '" << legacyName << "'");
PurpleConversation *conv = purple_find_conversation_with_account_wrapped(PURPLE_CONV_TYPE_CHAT, LegacyNameToName(account, legacyName).c_str(), account);
if (legacyName == adminLegacyName) {
// expect OAuth code
if (m_inputRequests.find(user) != m_inputRequests.end()) {
LOG4CXX_INFO(logger, "Updating token for '" << user << "'");
m_inputRequests[user]->ok_cb(m_inputRequests[user]->user_data, message.c_str());
m_inputRequests.erase(user);
}
return;
}
if (!conv) {
conv = purple_find_conversation_with_account_wrapped(PURPLE_CONV_TYPE_IM, LegacyNameToName(account, legacyName).c_str(), account);
if (!conv) {
conv = purple_conversation_new_wrapped(PURPLE_CONV_TYPE_IM, account, LegacyNameToName(account, legacyName).c_str());
}
}
if (xhtml.empty()) {
gchar *_markup = purple_markup_escape_text_wrapped(message.c_str(), -1);
if (purple_conversation_get_type_wrapped(conv) == PURPLE_CONV_TYPE_IM) {
purple_conv_im_send_with_flags_wrapped(PURPLE_CONV_IM_WRAPPED(conv), _markup, static_cast<PurpleMessageFlags>(PURPLE_MESSAGE_SPECTRUM2_ORIGINATED));
}
else if (purple_conversation_get_type_wrapped(conv) == PURPLE_CONV_TYPE_CHAT) {
purple_conv_chat_send_with_flags_wrapped(PURPLE_CONV_CHAT_WRAPPED(conv), _markup, static_cast<PurpleMessageFlags>(PURPLE_MESSAGE_SPECTRUM2_ORIGINATED));
}
g_free(_markup);
}
else {
if (purple_conversation_get_type_wrapped(conv) == PURPLE_CONV_TYPE_IM) {
purple_conv_im_send_with_flags_wrapped(PURPLE_CONV_IM_WRAPPED(conv), xhtml.c_str(), static_cast<PurpleMessageFlags>(PURPLE_MESSAGE_SPECTRUM2_ORIGINATED));
}
else if (purple_conversation_get_type_wrapped(conv) == PURPLE_CONV_TYPE_CHAT) {
purple_conv_chat_send_with_flags_wrapped(PURPLE_CONV_CHAT_WRAPPED(conv), xhtml.c_str(), static_cast<PurpleMessageFlags>(PURPLE_MESSAGE_SPECTRUM2_ORIGINATED));
}
}
}
}
void handleRoomSubjectChangedRequest(const std::string &user, const std::string &legacyName, const std::string &message) {
PurpleAccount *account = m_sessions[user];
if (account) {
PurpleConversation *conv = purple_find_conversation_with_account_wrapped(PURPLE_CONV_TYPE_CHAT, LegacyNameToName(account, legacyName).c_str(), account);
if (!conv) {
LOG4CXX_ERROR(logger, user << ": Cannot set room subject. There is now conversation " << legacyName);
return;
}
PurplePlugin *prpl = purple_find_prpl_wrapped(purple_account_get_protocol_id_wrapped(account));
PurplePluginProtocolInfo *prpl_info = PURPLE_PLUGIN_PROTOCOL_INFO(prpl);
bool support_set_chat_topic = prpl_info && prpl_info->set_chat_topic;
if (support_set_chat_topic) {
LOG4CXX_INFO(logger, user << ": Setting room subject for room " << legacyName);
prpl_info->set_chat_topic(purple_account_get_connection_wrapped(account),
purple_conv_chat_get_id(PURPLE_CONV_CHAT(conv)),
message.c_str());
}
}
}
void handleVCardRequest(const std::string &user, const std::string &legacyName, unsigned int id) {
PurpleAccount *account = m_sessions[user];
if (account) {
std::string name = legacyName;
if (CONFIG_STRING(config, "service.protocol") == "any" && legacyName.find("prpl-") == 0) {
name = name.substr(name.find(".") + 1);
}
m_vcards[user + name] = id;
PurplePlugin *prpl = purple_find_prpl_wrapped(purple_account_get_protocol_id_wrapped(account));
PurplePluginProtocolInfo *prpl_info = PURPLE_PLUGIN_PROTOCOL_INFO(prpl);
bool support_get_info = prpl_info && prpl_info->get_info;
if (!support_get_info || (CONFIG_BOOL(config, "backend.no_vcard_fetch") && name != purple_account_get_username_wrapped(account))) {
PurpleNotifyUserInfo *user_info = purple_notify_user_info_new_wrapped();
notify_user_info(purple_account_get_connection_wrapped(account), name.c_str(), user_info);
purple_notify_user_info_destroy_wrapped(user_info);
}
else {
serv_get_info_wrapped(purple_account_get_connection_wrapped(account), name.c_str());
}
}
}
void handleVCardUpdatedRequest(const std::string &user, const std::string &image, const std::string &nickname) {
PurpleAccount *account = m_sessions[user];
if (account) {
purple_account_set_alias_wrapped(account, nickname.c_str());
#if PURPLE_MAJOR_VERSION >= 2 && PURPLE_MINOR_VERSION >= 7
purple_account_set_public_alias_wrapped(account, nickname.c_str(), NULL, NULL);
#endif
gssize size = image.size();
// this will be freed by libpurple
guchar *photo = (guchar *) g_malloc(size * sizeof(guchar));
memcpy(photo, image.c_str(), size);
if (!photo)
return;
purple_buddy_icons_set_account_icon_wrapped(account, photo, size);
}
}
void handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups) {
PurpleAccount *account = m_sessions[user];
if (account) {
if (m_authRequests.find(user + buddyName) != m_authRequests.end()) {
m_authRequests[user + buddyName]->deny_cb(m_authRequests[user + buddyName]->user_data);
m_authRequests.erase(user + buddyName);
}
PurpleBuddy *buddy = purple_find_buddy_wrapped(account, buddyName.c_str());
if (buddy) {
purple_account_remove_buddy_wrapped(account, buddy, purple_buddy_get_group_wrapped(buddy));
purple_blist_remove_buddy_wrapped(buddy);
}
}
}
void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups_) {
PurpleAccount *account = m_sessions[user];
if (account) {
std::string groups = groups_.empty() ? "" : groups_[0];
if (m_authRequests.find(user + buddyName) != m_authRequests.end()) {
m_authRequests[user + buddyName]->authorize_cb(m_authRequests[user + buddyName]->user_data);
m_authRequests.erase(user + buddyName);
}
PurpleBuddy *buddy = purple_find_buddy_wrapped(account, buddyName.c_str());
if (buddy) {
if (getAlias(buddy) != alias) {
purple_blist_alias_buddy_wrapped(buddy, alias.c_str());
purple_blist_server_alias_buddy_wrapped(buddy, alias.c_str());
serv_alias_buddy_wrapped(buddy);
}
PurpleGroup *group = purple_find_group_wrapped(groups.c_str());
if (!group) {
group = purple_group_new_wrapped(groups.c_str());
}
purple_blist_add_contact_wrapped(purple_buddy_get_contact_wrapped(buddy), group ,NULL);
}
else {
PurpleBuddy *buddy = purple_buddy_new_wrapped(account, buddyName.c_str(), alias.c_str());
// Add newly created buddy to legacy network roster.
PurpleGroup *group = purple_find_group_wrapped(groups.c_str());
if (!group) {
group = purple_group_new_wrapped(groups.c_str());
}
purple_blist_add_buddy_wrapped(buddy, NULL, group ,NULL);
purple_account_add_buddy_wrapped(account, buddy);
LOG4CXX_INFO(logger, "Adding new buddy " << buddyName.c_str() << " to legacy network roster");
}
}
}
void handleBuddyBlockToggled(const std::string &user, const std::string &buddyName, bool blocked) {
if (CONFIG_BOOL(config, "service.enable_privacy_lists")) {
PurpleAccount *account = m_sessions[user];
if (account) {
if (blocked) {
purple_privacy_deny_wrapped(account, buddyName.c_str(), FALSE, FALSE);
}
else {
purple_privacy_allow_wrapped(account, buddyName.c_str(), FALSE, FALSE);
}
}
}
}
void updateConversationActivity(PurpleAccount *account, const std::string &buddyName) {
PurpleConversation *conv = purple_find_conversation_with_account_wrapped(PURPLE_CONV_TYPE_CHAT, buddyName.c_str(), account);
if (!conv) {
conv = purple_find_conversation_with_account_wrapped(PURPLE_CONV_TYPE_IM, buddyName.c_str(), account);
}
if (conv) {
purple_conversation_set_data_wrapped(conv, "unseen_count", 0);
purple_conversation_update_wrapped(conv, PURPLE_CONV_UPDATE_UNSEEN);
}
}
void handleTypingRequest(const std::string &user, const std::string &buddyName) {
PurpleAccount *account = m_sessions[user];
if (account) {
LOG4CXX_INFO(logger, user << ": sending typing notify to " << buddyName);
serv_send_typing_wrapped(purple_account_get_connection_wrapped(account), buddyName.c_str(), PURPLE_TYPING);
updateConversationActivity(account, buddyName);
}
}
void handleTypedRequest(const std::string &user, const std::string &buddyName) {
PurpleAccount *account = m_sessions[user];
if (account) {
serv_send_typing_wrapped(purple_account_get_connection_wrapped(account), buddyName.c_str(), PURPLE_TYPED);
updateConversationActivity(account, buddyName);
}
}
void handleStoppedTypingRequest(const std::string &user, const std::string &buddyName) {
PurpleAccount *account = m_sessions[user];
if (account) {
serv_send_typing_wrapped(purple_account_get_connection_wrapped(account), buddyName.c_str(), PURPLE_NOT_TYPING);
updateConversationActivity(account, buddyName);
}
}
void handleAttentionRequest(const std::string &user, const std::string &buddyName, const std::string &message) {
PurpleAccount *account = m_sessions[user];
if (account) {
purple_prpl_send_attention_wrapped(purple_account_get_connection_wrapped(account), buddyName.c_str(), 0);
}
}
std::string LegacyNameToName(PurpleAccount *account, const std::string &legacyName) {
std::string conversationName = legacyName;
BOOST_FOREACH(std::string _room, m_rooms[np->m_accounts[account]]) {
std::string lowercased_room = boost::locale::to_lower(_room);
if (lowercased_room.compare(conversationName) == 0) {
conversationName = _room;
break;
}
}
return conversationName;
}
std::string NameToLegacyName(PurpleAccount *account, const std::string &legacyName) {
std::string conversationName = legacyName;
BOOST_FOREACH(std::string _room, m_rooms[np->m_accounts[account]]) {
if (_room.compare(conversationName) == 0) {
conversationName = boost::locale::to_lower(legacyName);
break;
}
}
return conversationName;
}
void handleJoinRoomRequest(const std::string &user, const std::string &room, const std::string &nickname, const std::string &pasword) {
PurpleAccount *account = m_sessions[user];
if (!account) {
return;
}
PurpleConnection *gc = purple_account_get_connection_wrapped(account);
GHashTable *comps = NULL;
std::string roomName = LegacyNameToName(account, room);
// Check if the PurpleChat is not stored in buddy list
PurpleChat *chat = purple_blist_find_chat_wrapped(account, roomName.c_str());
if (chat) {
comps = purple_chat_get_components_wrapped(chat);
}
else if (PURPLE_PLUGIN_PROTOCOL_INFO(gc->prpl)->chat_info_defaults != NULL) {
if (CONFIG_STRING(config, "service.protocol") == "prpl-jabber") {
comps = PURPLE_PLUGIN_PROTOCOL_INFO(gc->prpl)->chat_info_defaults(gc, (roomName + "/" + nickname).c_str());
} else {
comps = PURPLE_PLUGIN_PROTOCOL_INFO(gc->prpl)->chat_info_defaults(gc, roomName.c_str());
}
}
if (CONFIG_STRING(config, "service.protocol") != "prpl-jabber") {
np->handleParticipantChanged(np->m_accounts[account], nickname, room, 0, pbnetwork::STATUS_ONLINE);
const char *disp;
if ((disp = purple_account_get_name_for_display(account)) == NULL) {
if ((disp = purple_connection_get_display_name(account->gc)) == NULL) {
disp = purple_account_get_username(account);
}
}
LOG4CXX_INFO(logger, user << ": Display name is " << disp << ", nickname is " << nickname);
if (nickname != disp) {
handleRoomNicknameChanged(np->m_accounts[account], room, disp);
np->handleParticipantChanged(np->m_accounts[account], nickname, room, 0, pbnetwork::STATUS_ONLINE, "", disp);
}
}
LOG4CXX_INFO(logger, user << ": Joining the room " << roomName);
if (comps) {
serv_join_chat_wrapped(gc, comps);
g_hash_table_destroy(comps);
}
}
void handleLeaveRoomRequest(const std::string &user, const std::string &room) {
PurpleAccount *account = m_sessions[user];
if (!account) {
return;
}
PurpleConversation *conv = purple_find_conversation_with_account_wrapped(PURPLE_CONV_TYPE_CHAT, LegacyNameToName(account, room).c_str(), account);
purple_conversation_destroy_wrapped(conv);
}
void handleFTStartRequest(const std::string &user, const std::string &buddyName, const std::string &fileName, unsigned long size, unsigned long ftID) {
PurpleXfer *xfer = m_unhandledXfers[user + fileName + buddyName];
if (xfer) {
m_unhandledXfers.erase(user + fileName + buddyName);
FTData *ftData = (FTData *) xfer->ui_data;
ftData->id = ftID;
m_xfers[ftID] = xfer;
purple_xfer_request_accepted_wrapped(xfer, fileName.c_str());
purple_xfer_ui_ready_wrapped(xfer);
}
}
void handleFTFinishRequest(const std::string &user, const std::string &buddyName, const std::string &fileName, unsigned long size, unsigned long ftID) {
PurpleXfer *xfer = m_unhandledXfers[user + fileName + buddyName];
if (xfer) {
m_unhandledXfers.erase(user + fileName + buddyName);
purple_xfer_request_denied_wrapped(xfer);
}
}
void handleFTPauseRequest(unsigned long ftID) {
PurpleXfer *xfer = m_xfers[ftID];
if (!xfer)
return;
FTData *ftData = (FTData *) xfer->ui_data;
ftData->paused = true;
}
void handleFTContinueRequest(unsigned long ftID) {
PurpleXfer *xfer = m_xfers[ftID];
if (!xfer)
return;
FTData *ftData = (FTData *) xfer->ui_data;
ftData->paused = false;
purple_xfer_ui_ready_wrapped(xfer);
}
void sendData(const std::string &string) {
#ifdef WIN32
::send(main_socket, string.c_str(), string.size(), 0);
#else
write(main_socket, string.c_str(), string.size());
#endif
if (writeInput == 0)
writeInput = purple_input_add_wrapped(main_socket, PURPLE_INPUT_WRITE, &transportDataReceived, NULL);
}
void readyForData() {
if (m_waitingXfers.empty())
return;
std::vector<PurpleXfer *> tmp;
tmp.swap(m_waitingXfers);
for (std::vector<PurpleXfer *>::const_iterator it = tmp.begin(); it != tmp.end(); it++) {
FTData *ftData = (FTData *) (*it)->ui_data;
if (ftData->timer == 0) {
ftData->timer = purple_timeout_add_wrapped(1, ft_ui_ready, *it);
}
// purple_xfer_ui_ready_wrapped(xfer);
}
}
std::map<std::string, PurpleAccount *> m_sessions;
std::map<PurpleAccount *, std::string> m_accounts;
std::map<std::string, unsigned int> m_vcards;
std::map<std::string, authRequest *> m_authRequests;
std::map<std::string, inputRequest *> m_inputRequests;
std::map<std::string, std::list<std::string> > m_rooms;
std::map<unsigned long, PurpleXfer *> m_xfers;
std::map<std::string, PurpleXfer *> m_unhandledXfers;
std::vector<PurpleXfer *> m_waitingXfers;
std::string adminLegacyName;
std::string adminAlias;
};
static bool getStatus(PurpleBuddy *m_buddy, pbnetwork::StatusType &status, std::string &statusMessage) {
PurplePresence *pres = purple_buddy_get_presence_wrapped(m_buddy);
if (pres == NULL)
return false;
PurpleStatus *stat = purple_presence_get_active_status_wrapped(pres);
if (stat == NULL)
return false;
int st = purple_status_type_get_primitive_wrapped(purple_status_get_type_wrapped(stat));
switch(st) {
case PURPLE_STATUS_AVAILABLE: {
status = pbnetwork::STATUS_ONLINE;
break;
}
case PURPLE_STATUS_AWAY: {
status = pbnetwork::STATUS_AWAY;
break;
}
case PURPLE_STATUS_UNAVAILABLE: {
status = pbnetwork::STATUS_DND;
break;
}
case PURPLE_STATUS_EXTENDED_AWAY: {
status = pbnetwork::STATUS_XA;
break;
}
case PURPLE_STATUS_OFFLINE: {
status = pbnetwork::STATUS_NONE;
break;
}
default:
status = pbnetwork::STATUS_ONLINE;
break;
}
const char *message = purple_status_get_attr_string_wrapped(stat, "message");
if (message != NULL) {
char *stripped = purple_markup_strip_html_wrapped(message);
statusMessage = std::string(stripped);
g_free(stripped);
}
else
statusMessage = "";
return true;
}
static std::string getIconHash(PurpleBuddy *m_buddy) {
char *avatarHash = NULL;
PurpleBuddyIcon *icon = purple_buddy_icons_find_wrapped(purple_buddy_get_account_wrapped(m_buddy), purple_buddy_get_name_wrapped(m_buddy));
if (icon) {
avatarHash = purple_buddy_icon_get_full_path_wrapped(icon);
purple_buddy_icon_unref_wrapped(icon);
}
if (avatarHash) {
// Check if it's patched libpurple which saves icons to directories
char *hash = strrchr(avatarHash,'/');
std::string h;
if (hash) {
char *dot;
hash++;
dot = strchr(hash, '.');
if (dot)
*dot = '\0';
std::string ret(hash);
g_free(avatarHash);
return ret;
}
else {