forked from EionRobb/purple-rocketchat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
librocketchat.c
4021 lines (3251 loc) · 146 KB
/
librocketchat.c
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
/*
* Rocket.Chat plugin for libpurple
* Copyright (C) 2016 Eion Robb
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Glib
#include <glib.h>
#if !GLIB_CHECK_VERSION(2, 32, 0)
#define g_hash_table_contains(hash_table, key) g_hash_table_lookup_extended(hash_table, key, NULL, NULL)
#endif /* 2.32.0 */
static gboolean
g_str_insensitive_equal(gconstpointer v1, gconstpointer v2)
{
return (g_ascii_strcasecmp(v1, v2) == 0);
}
static guint
g_str_insensitive_hash(gconstpointer v)
{
guint hash;
gchar *lower_str = g_ascii_strdown(v, -1);
hash = g_str_hash(lower_str);
g_free(lower_str);
return hash;
}
// GNU C libraries
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __GNUC__
#include <unistd.h>
#endif
#include <errno.h>
#include <json-glib/json-glib.h>
// Supress overzealous json-glib 'critical errors'
#define json_object_has_member(JSON_OBJECT, MEMBER) \
(JSON_OBJECT ? json_object_has_member(JSON_OBJECT, MEMBER) : FALSE)
#define json_object_get_int_member(JSON_OBJECT, MEMBER) \
(json_object_has_member(JSON_OBJECT, MEMBER) ? json_object_get_int_member(JSON_OBJECT, MEMBER) : 0)
#define json_object_get_string_member(JSON_OBJECT, MEMBER) \
(json_object_has_member(JSON_OBJECT, MEMBER) ? json_object_get_string_member(JSON_OBJECT, MEMBER) : NULL)
#define json_object_get_array_member(JSON_OBJECT, MEMBER) \
(json_object_has_member(JSON_OBJECT, MEMBER) ? json_object_get_array_member(JSON_OBJECT, MEMBER) : NULL)
#define json_object_get_object_member(JSON_OBJECT, MEMBER) \
(json_object_has_member(JSON_OBJECT, MEMBER) ? json_object_get_object_member(JSON_OBJECT, MEMBER) : NULL)
#define json_object_get_boolean_member(JSON_OBJECT, MEMBER) \
(json_object_has_member(JSON_OBJECT, MEMBER) ? json_object_get_boolean_member(JSON_OBJECT, MEMBER) : FALSE)
#define json_array_get_length(JSON_ARRAY) \
(JSON_ARRAY ? json_array_get_length(JSON_ARRAY) : 0)
// static void
// json_array_foreach_element_reverse (JsonArray *array,
// JsonArrayForeach func,
// gpointer data)
// {
// gint i;
// g_return_if_fail (array != NULL);
// g_return_if_fail (func != NULL);
// for (i = json_array_get_length(array) - 1; i >= 0; i--)
// {
// JsonNode *element_node;
// element_node = json_array_get_element(array, i);
// (* func) (array, i, element_node, data);
// }
// }
#include <purple.h>
#if PURPLE_VERSION_CHECK(3, 0, 0)
#include <http.h>
#endif
#ifndef PURPLE_PLUGINS
# define PURPLE_PLUGINS
#endif
#ifndef _
# define _(a) (a)
# define N_(a) (a)
#endif
#define ROCKETCHAT_PLUGIN_ID "prpl-eionrobb-rocketchat"
#ifndef ROCKETCHAT_PLUGIN_VERSION
#define ROCKETCHAT_PLUGIN_VERSION "0.1"
#endif
#define ROCKETCHAT_PLUGIN_WEBSITE "https://github.com/EionRobb/purple-rocketchat"
#define ROCKETCHAT_USERAGENT "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
#define ROCKETCHAT_BUFFER_DEFAULT_SIZE 40960
#define RC_DEFAULT_SERVER ""
#define RC_SERVER_SPLIT_CHAR '|'
// Purple2 compat functions
#if !PURPLE_VERSION_CHECK(3, 0, 0)
#define purple_connection_error purple_connection_error_reason
#define purple_connection_get_protocol purple_connection_get_prpl
#define PURPLE_CONNECTION_CONNECTING PURPLE_CONNECTING
#define PURPLE_CONNECTION_CONNECTED PURPLE_CONNECTED
#define PURPLE_CONNECTION_FLAG_HTML PURPLE_CONNECTION_HTML
#define PURPLE_CONNECTION_FLAG_NO_BGCOLOR PURPLE_CONNECTION_NO_BGCOLOR
#define PURPLE_CONNECTION_FLAG_NO_FONTSIZE PURPLE_CONNECTION_NO_FONTSIZE
#define PURPLE_CONNECTION_FLAG_NO_IMAGES PURPLE_CONNECTION_NO_IMAGES
#define purple_connection_set_flags(pc, f) ((pc)->flags = (f))
#define purple_connection_get_flags(pc) ((pc)->flags)
#define purple_blist_find_group purple_find_group
#define purple_protocol_get_id purple_plugin_get_id
#define PurpleProtocolChatEntry struct proto_chat_entry
#define PurpleChatConversation PurpleConvChat
#define PurpleIMConversation PurpleConvIm
static inline PurpleConvChat * purple_conversations_find_chat_with_account(const char * name, const PurpleAccount * account)
{
PurpleConversation * conv = purple_find_conversation_with_account(PURPLE_CONV_TYPE_CHAT, name, account);
return conv == NULL ? NULL : PURPLE_CONV_CHAT(conv);
}
#define purple_chat_conversation_has_left purple_conv_chat_has_left
#define PurpleConversationUpdateType PurpleConvUpdateType
#define PURPLE_CONVERSATION_UPDATE_UNSEEN PURPLE_CONV_UPDATE_UNSEEN
#define PURPLE_IS_IM_CONVERSATION(conv) (purple_conversation_get_type(conv) == PURPLE_CONV_TYPE_IM)
#define PURPLE_IS_CHAT_CONVERSATION(conv) (purple_conversation_get_type(conv) == PURPLE_CONV_TYPE_CHAT)
#define PURPLE_CONVERSATION(chatorim) ((chatorim) == NULL ? NULL : (chatorim)->conv)
#define PURPLE_IM_CONVERSATION(conv) PURPLE_CONV_IM(conv)
#define PURPLE_CHAT_CONVERSATION(conv) PURPLE_CONV_CHAT(conv)
#define purple_conversation_present_error purple_conv_present_error
#define purple_serv_got_joined_chat(pc, id, name) PURPLE_CONV_CHAT(serv_got_joined_chat(pc, id, name))
#define purple_conversations_find_chat(pc, id) PURPLE_CONV_CHAT(purple_find_chat(pc, id))
#define purple_serv_got_chat_in serv_got_chat_in
#define purple_chat_conversation_add_user purple_conv_chat_add_user
#define purple_chat_conversation_add_users purple_conv_chat_add_users
#define purple_chat_conversation_remove_user purple_conv_chat_remove_user
#define purple_chat_conversation_get_topic purple_conv_chat_get_topic
#define purple_chat_conversation_set_topic purple_conv_chat_set_topic
#define PurpleChatUserFlags PurpleConvChatBuddyFlags
#define PURPLE_CHAT_USER_NONE PURPLE_CBFLAGS_NONE
#define PURPLE_CHAT_USER_OP PURPLE_CBFLAGS_OP
#define PURPLE_CHAT_USER_FOUNDER PURPLE_CBFLAGS_FOUNDER
#define PURPLE_CHAT_USER_TYPING PURPLE_CBFLAGS_TYPING
#define PURPLE_CHAT_USER_AWAY PURPLE_CBFLAGS_AWAY
#define PURPLE_CHAT_USER_HALFOP PURPLE_CBFLAGS_HALFOP
#define PURPLE_CHAT_USER_VOICE PURPLE_CBFLAGS_VOICE
#define PURPLE_CHAT_USER_TYPING PURPLE_CBFLAGS_TYPING
#define PurpleChatUser PurpleConvChatBuddy
static inline PurpleChatUser *
purple_chat_conversation_find_user(PurpleChatConversation *chat, const char *name)
{
PurpleChatUser *cb = purple_conv_chat_cb_find(chat, name);
if (cb != NULL) {
g_dataset_set_data(cb, "chat", chat);
}
return cb;
}
#define purple_chat_user_get_flags(cb) purple_conv_chat_user_get_flags(g_dataset_get_data((cb), "chat"), (cb)->name)
#define purple_chat_user_set_flags(cb, f) purple_conv_chat_user_set_flags(g_dataset_get_data((cb), "chat"), (cb)->name, (f))
#define purple_chat_user_set_alias(cb, a) (g_free((cb)->alias), (cb)->alias = g_strdup(a))
#define PurpleIMTypingState PurpleTypingState
#define PURPLE_IM_NOT_TYPING PURPLE_NOT_TYPING
#define PURPLE_IM_TYPING PURPLE_TYPING
#define PURPLE_IM_TYPED PURPLE_TYPED
#define purple_conversation_get_connection purple_conversation_get_gc
#define purple_conversation_write_system_message(conv, message, flags) purple_conversation_write((conv), NULL, (message), ((flags) | PURPLE_MESSAGE_SYSTEM), time(NULL))
#define purple_chat_conversation_get_id purple_conv_chat_get_id
#define PURPLE_CMD_FLAG_PROTOCOL_ONLY PURPLE_CMD_FLAG_PRPL_ONLY
#define PURPLE_IS_BUDDY PURPLE_BLIST_NODE_IS_BUDDY
#define PURPLE_IS_CHAT PURPLE_BLIST_NODE_IS_CHAT
#define purple_chat_get_name_only purple_chat_get_name
#define purple_blist_find_buddy purple_find_buddy
#define purple_serv_got_alias serv_got_alias
#define purple_account_set_private_alias purple_account_set_alias
#define purple_account_get_private_alias purple_account_get_alias
#define purple_protocol_got_user_status purple_prpl_got_user_status
#define purple_serv_got_im serv_got_im
#define purple_serv_got_typing serv_got_typing
#define purple_conversations_find_im_with_account(name, account) \
PURPLE_CONV_IM(purple_find_conversation_with_account(PURPLE_CONV_TYPE_IM, name, account))
#define purple_im_conversation_new(account, from) PURPLE_CONV_IM(purple_conversation_new(PURPLE_CONV_TYPE_IM, account, from))
#define PurpleMessage PurpleConvMessage
#define purple_message_set_time(msg, time) ((msg)->when = (time))
#define purple_conversation_write_message(conv, msg) purple_conversation_write(conv, msg->who, msg->what, msg->flags, msg->when)
static inline PurpleMessage *
purple_message_new_outgoing(const gchar *who, const gchar *contents, PurpleMessageFlags flags)
{
PurpleMessage *message = g_new0(PurpleMessage, 1);
message->who = g_strdup(who);
message->what = g_strdup(contents);
message->flags = flags;
message->when = time(NULL);
return message;
}
static inline void
purple_message_destroy(PurpleMessage *message)
{
g_free(message->who);
g_free(message->what);
g_free(message);
}
#define purple_message_get_recipient(message) (message->who)
#define purple_message_get_contents(message) (message->what)
#define purple_account_privacy_deny_add purple_privacy_deny_add
#define purple_account_privacy_deny_remove purple_privacy_deny_remove
#define PurpleHttpConnection PurpleUtilFetchUrlData
#define purple_buddy_set_name purple_blist_rename_buddy
#else
// Purple3 helper functions
#define purple_conversation_set_data(conv, key, value) g_object_set_data(G_OBJECT(conv), key, value)
#define purple_conversation_get_data(conv, key) g_object_get_data(G_OBJECT(conv), key)
#define purple_message_destroy g_object_unref
#define purple_chat_user_set_alias(cb, alias) g_object_set((cb), "alias", (alias), NULL)
#define purple_chat_get_alias(chat) g_object_get_data(G_OBJECT(chat), "alias")
#endif
typedef struct {
PurpleAccount *account;
PurpleConnection *pc;
GHashTable *cookie_table;
gchar *session_token;
gchar *channel;
gchar *self_user;
gchar *self_user_id;
gint64 last_message_timestamp;
gint64 last_load_last_message_timestamp;
gchar *username;
gchar *server;
gchar *path;
PurpleSslConnection *websocket;
gboolean websocket_header_received;
gboolean sync_complete;
guchar packet_code;
gchar *frame;
guint64 frame_len;
guint64 frame_len_progress;
gint64 id; //incrementing counter
GHashTable *one_to_ones; // A store of known room_id's -> username's
GHashTable *one_to_ones_rev; // A store of known usernames's -> room_id's
GHashTable *group_chats; // A store of known multi-user room_id's -> room name's
GHashTable *group_chats_rev; // A store of known multi-user room name's -> room_id's
GHashTable *sent_message_ids; // A store of message id's that we generated from this instance
GHashTable *result_callbacks; // Result ID -> Callback function
GHashTable *usernames_to_ids; // username -> user id
GHashTable *ids_to_usernames; // user id -> username
GQueue *received_message_queue; // A store of the last 10 received message id's for de-dup
GSList *http_conns; /**< PurpleHttpConnection to be cancelled on logout */
gint frames_since_reconnect;
GSList *pending_writes;
} RocketChatAccount;
typedef void (*RocketChatProxyCallbackFunc)(RocketChatAccount *ya, JsonNode *node, gpointer user_data, JsonObject *error);
typedef struct {
RocketChatAccount *ya;
RocketChatProxyCallbackFunc callback;
gpointer user_data;
GDestroyNotify user_data_destroy_func;
} RocketChatProxyConnection;
//#include <mkdio.h>
extern char markdown_version[];
int mkd_line(char *, int, char **, int);
#define MKD_NOLINKS 0x00000001 /* don't do link processing, block <a> tags */
#define MKD_NOIMAGE 0x00000002 /* don't do image processing, block <img> */
#define MKD_NOPANTS 0x00000004 /* don't run smartypants() */
#define MKD_NOHTML 0x00000008 /* don't allow raw html through AT ALL */
#define MKD_STRICT 0x00000010 /* disable SUPERSCRIPT, RELAXED_EMPHASIS */
#define MKD_TAGTEXT 0x00000020 /* process text inside an html tag; no
* <em>, no <bold>, no html or [] expansion */
#define MKD_NO_EXT 0x00000040 /* don't allow pseudo-protocols */
#define MKD_NOEXT MKD_NO_EXT /* ^^^ (aliased for user convenience) */
#define MKD_CDATA 0x00000080 /* generate code for xml ![CDATA[...]] */
#define MKD_NOSUPERSCRIPT 0x00000100 /* no A^B */
#define MKD_NORELAXED 0x00000200 /* emphasis happens /everywhere/ */
#define MKD_NOTABLES 0x00000400 /* disallow tables */
#define MKD_NOSTRIKETHROUGH 0x00000800 /* forbid ~~strikethrough~~ */
#define MKD_TOC 0x00001000 /* do table-of-contents processing */
#define MKD_1_COMPAT 0x00002000 /* compatibility with MarkdownTest_1.0 */
#define MKD_AUTOLINK 0x00004000 /* make http://foo.com link even without <>s */
#define MKD_SAFELINK 0x00008000 /* paranoid check for link protocol */
#define MKD_NOHEADER 0x00010000 /* don't process header blocks */
#define MKD_TABSTOP 0x00020000 /* expand tabs to 4 spaces */
#define MKD_NODIVQUOTE 0x00040000 /* forbid >%class% blocks */
#define MKD_NOALPHALIST 0x00080000 /* forbid alphabetic lists */
#define MKD_NODLIST 0x00100000 /* forbid definition lists */
#define MKD_EXTRA_FOOTNOTE 0x00200000 /* enable markdown extra-style footnotes */
#define MKD_NOSTYLE 0x00400000 /* don't extract <style> blocks */
#define MKD_NODLDISCOUNT 0x00800000 /* disable discount-style definition lists */
#define MKD_DLEXTRA 0x01000000 /* enable extra-style definition lists */
#define MKD_FENCEDCODE 0x02000000 /* enabled fenced code blocks */
#define MKD_IDANCHOR 0x04000000 /* use id= anchors for TOC links */
#define MKD_GITHUBTAGS 0x08000000 /* allow dash and underscore in element names */
#define MKD_URLENCODEDANCHOR 0x10000000 /* urlencode non-identifier chars instead of replacing with dots */
#define MKD_LATEX 0x40000000 /* handle embedded LaTeX escapes */
#define MKD_EMBED MKD_NOLINKS|MKD_NOIMAGE|MKD_TAGTEXT
static gchar *
rc_markdown_to_html(const gchar *markdown)
{
static char *markdown_str = NULL;
int markdown_len;
int flags = MKD_NOPANTS | MKD_NODIVQUOTE | MKD_NODLIST;
static gboolean markdown_version_checked = FALSE;
static gboolean markdown_version_safe = FALSE;
if (markdown == NULL) {
return NULL;
}
if (!markdown_version_checked) {
gchar **markdown_version_split = g_strsplit_set( markdown_version, ". ", -1);
gchar *last_part;
guint i = 0;
do {
last_part = markdown_version_split[i++];
} while (markdown_version_split[i] != NULL);
if (!purple_strequal(last_part, "DEBUG")) {
markdown_version_safe = TRUE;
} else {
gint major, minor, micro;
major = atoi(markdown_version_split[0]);
if (major > 2) {
markdown_version_safe = TRUE;
} else if (major == 2) {
minor = atoi(markdown_version_split[1]);
if (minor > 2) {
markdown_version_safe = TRUE;
} else if (minor == 2) {
micro = atoi(markdown_version_split[2]);
if (micro > 2) {
markdown_version_safe = TRUE;
}
}
}
}
g_strfreev(markdown_version_split);
markdown_version_checked = TRUE;
}
if (markdown_str != NULL) {
// if libmarkdown is pre-2.2.2 and we're using amalloc, don't free()
if (markdown_version_safe) {
free(markdown_str);
}
}
markdown_len = mkd_line((char *)markdown, strlen(markdown), &markdown_str, flags);
if (markdown_len < 0) {
return NULL;
}
return g_strndup(markdown_str, markdown_len);
}
static void
rc_markup_anchor_parse_text(GMarkupParseContext *context, const gchar *text, gsize text_len, gpointer user_data, GError **error)
{
GString *output = user_data;
g_string_prepend_len(output, text, text_len);
}
static GMarkupParser rc_markup_anchor_parser = {
NULL,
NULL,
rc_markup_anchor_parse_text,
NULL,
NULL
};
static void
rc_markdown_parse_start_element(GMarkupParseContext *context, const gchar *element_name, const gchar **attribute_names, const gchar **attribute_values, gpointer user_data, GError **error)
{
GString *output = user_data;
switch(g_str_hash(element_name)) {
case 0x2b607: case 0x2b5e7: //B
g_string_append(output, "**");
break;
case 0x2b60e: case 0x2b5ee: //I
case 0x5977b7: case 0x597377: //EM
g_string_append_c(output, '_');
break;
case 0x597759: case 0x597319: //BR
g_string_append_c(output, '\n');
break;
case 0xb8869ba: case 0xb87dd5a: //DEL
case 0x2b618: case 0x2b5f8: //S
case 0x1c93af97: case 0xcf9972d7: //STRIKE
g_string_append(output, "~~");
break;
case 0x2b606: case 0x2b5e6: //A
{
const gchar **name_cursor = attribute_names;
const gchar **value_cursor = attribute_values;
GString *href_string = g_string_new("](");
while (*name_cursor) {
if (g_ascii_strncasecmp(*name_cursor, "href", -1) == 0) {
g_string_append(href_string, *value_cursor);
break;
}
name_cursor++;
value_cursor++;
}
g_string_append_c(output, '[');
g_markup_parse_context_push(context, &rc_markup_anchor_parser, href_string);
break;
}
}
}
static void
rc_markdown_parse_end_element(GMarkupParseContext *context, const gchar *element_name, gpointer user_data, GError **error)
{
GString *output = user_data;
switch(g_str_hash(element_name)) {
case 0x2b607: case 0x2b5e7: //B
g_string_append(output, "**");
break;
case 0x2b60e: case 0x2b5ee: //I
case 0x5977b7: case 0x597377: //EM
g_string_append_c(output, '_');
break;
case 0xb8869ba: case 0xb87dd5a: //DEL
case 0x2b618: case 0x2b5f8: //S
case 0x1c93af97: case 0xcf9972d7: //STRIKE
g_string_append(output, "~~");
break;
case 0x2b606: case 0x2b5e6: //A
{
GString *href_string = g_markup_parse_context_pop(context);
g_string_append_printf(output, "%s)", href_string->str);
g_string_free(href_string, TRUE);
break;
}
}
}
static void
rc_markdown_parse_text(GMarkupParseContext *context, const gchar *text, gsize text_len, gpointer user_data, GError **error)
{
GString *output = user_data;
g_string_append_len(output, text, text_len);
}
static GMarkupParser rc_markup_markdown_parser = {
rc_markdown_parse_start_element,
rc_markdown_parse_end_element,
rc_markdown_parse_text,
NULL,
NULL
};
static gchar *
rc_html_to_markdown(const gchar *html)
{
GString *output = g_string_new(NULL);
GMarkupParseContext *context;
context = g_markup_parse_context_new(&rc_markup_markdown_parser, G_MARKUP_TREAT_CDATA_AS_TEXT, output, NULL);
g_markup_parse_context_parse(context, "<html>", -1, NULL);
g_markup_parse_context_parse(context, html, -1, NULL);
g_markup_parse_context_parse(context, "</html>", -1, NULL);
g_markup_parse_context_end_parse(context, NULL);
g_markup_parse_context_free(context);
return g_string_free(output, FALSE);
}
// static gchar *
// purple_base32_encode(const guchar *data, gsize len)
// {
// static const char base32_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
// char *out, *rv;
// guchar work[5];
// g_return_val_if_fail(data != NULL, NULL);
// g_return_val_if_fail(len > 0, NULL);
// rv = out = g_malloc(((len / 5) + 1) * 8 + 1);
// for (; len; len -= MIN(5, len))
// {
// memset(work, 0, 5);
// memcpy(work, data, MIN(5, len));
// *out++ = base32_alphabet[work[0] >> 3];
// *out++ = base32_alphabet[((work[0] & 0x07) << 2) | (work[1] >> 6)];
// *out++ = base32_alphabet[(work[1] >> 1) & 0x1f];
// *out++ = base32_alphabet[((work[1] & 0x01) << 4) | (work[2] >> 4)];
// *out++ = base32_alphabet[((work[2] & 0x0f) << 1) | (work[3] >> 7)];
// *out++ = base32_alphabet[(work[3] >> 2) & 0x1f];
// *out++ = base32_alphabet[((work[3] & 0x03) << 3) | (work[4] >> 5)];
// *out++ = base32_alphabet[work[4] & 0x1f];
// data += MIN(5, len);
// }
// *out = '\0';
// return rv;
// }
static const gchar *
rc_get_next_id_str(RocketChatAccount *ya) {
static gchar *next_id = NULL;
g_free(next_id);
next_id = g_strdup_printf("%" G_GINT64_FORMAT, ya->id++);
return next_id;
}
static const gchar *
rc_get_next_id_str_callback(RocketChatAccount *ya, RocketChatProxyCallbackFunc callback, gpointer user_data, GDestroyNotify user_data_destroy_func)
{
const gchar *id = rc_get_next_id_str(ya);
RocketChatProxyConnection *proxy = g_new0(RocketChatProxyConnection, 1);
proxy->ya = ya;
proxy->callback = callback;
proxy->user_data = user_data;
proxy->user_data_destroy_func = user_data_destroy_func;
g_hash_table_insert(ya->result_callbacks, g_strdup(id), proxy);
return id;
}
gchar *
rc_string_get_chunk(const gchar *haystack, gsize len, const gchar *start, const gchar *end)
{
const gchar *chunk_start, *chunk_end;
g_return_val_if_fail(haystack && start && end, NULL);
if (len > 0) {
chunk_start = g_strstr_len(haystack, len, start);
} else {
chunk_start = strstr(haystack, start);
}
g_return_val_if_fail(chunk_start, NULL);
chunk_start += strlen(start);
if (len > 0) {
chunk_end = g_strstr_len(chunk_start, len - (chunk_start - haystack), end);
} else {
chunk_end = strstr(chunk_start, end);
}
g_return_val_if_fail(chunk_end, NULL);
return g_strndup(chunk_start, chunk_end - chunk_start);
}
#if PURPLE_VERSION_CHECK(3, 0, 0)
static void
rc_update_cookies(RocketChatAccount *ya, const GList *cookie_headers)
{
const gchar *cookie_start;
const gchar *cookie_end;
gchar *cookie_name;
gchar *cookie_value;
const GList *cur;
for (cur = cookie_headers; cur != NULL; cur = g_list_next(cur))
{
cookie_start = cur->data;
cookie_end = strchr(cookie_start, '=');
cookie_name = g_strndup(cookie_start, cookie_end-cookie_start);
cookie_start = cookie_end + 1;
cookie_end = strchr(cookie_start, ';');
cookie_value= g_strndup(cookie_start, cookie_end-cookie_start);
cookie_start = cookie_end;
g_hash_table_replace(ya->cookie_table, cookie_name, cookie_value);
}
}
#else
static void
rc_update_cookies(RocketChatAccount *ya, const gchar *headers)
{
const gchar *cookie_start;
const gchar *cookie_end;
gchar *cookie_name;
gchar *cookie_value;
int header_len;
g_return_if_fail(headers != NULL);
header_len = strlen(headers);
/* look for the next "Set-Cookie: " */
/* grab the data up until ';' */
cookie_start = headers;
while ((cookie_start = strstr(cookie_start, "\r\nSet-Cookie: ")) && (cookie_start - headers) < header_len)
{
cookie_start += 14;
cookie_end = strchr(cookie_start, '=');
cookie_name = g_strndup(cookie_start, cookie_end-cookie_start);
cookie_start = cookie_end + 1;
cookie_end = strchr(cookie_start, ';');
cookie_value= g_strndup(cookie_start, cookie_end-cookie_start);
cookie_start = cookie_end;
g_hash_table_replace(ya->cookie_table, cookie_name, cookie_value);
}
}
#endif
static void
rc_cookie_foreach_cb(gchar *cookie_name, gchar *cookie_value, GString *str)
{
g_string_append_printf(str, "%s=%s;", cookie_name, cookie_value);
}
static gchar *
rc_cookies_to_string(RocketChatAccount *ya)
{
GString *str;
str = g_string_new(NULL);
g_hash_table_foreach(ya->cookie_table, (GHFunc)rc_cookie_foreach_cb, str);
return g_string_free(str, FALSE);
}
static void
rc_response_callback(PurpleHttpConnection *http_conn,
#if PURPLE_VERSION_CHECK(3, 0, 0)
PurpleHttpResponse *response, gpointer user_data)
{
gsize len;
const gchar *url_text = purple_http_response_get_data(response, &len);
const gchar *error_message = purple_http_response_get_error(response);
#else
gpointer user_data, const gchar *url_text, gsize len, const gchar *error_message)
{
#endif
const gchar *body;
gsize body_len;
RocketChatProxyConnection *conn = user_data;
JsonParser *parser = json_parser_new();
conn->ya->http_conns = g_slist_remove(conn->ya->http_conns, http_conn);
#if !PURPLE_VERSION_CHECK(3, 0, 0)
rc_update_cookies(conn->ya, url_text);
body = g_strstr_len(url_text, len, "\r\n\r\n");
body = body ? body + 4 : body;
body_len = len - (body - url_text);
#else
rc_update_cookies(conn->ya, purple_http_response_get_headers_by_name(response, "Set-Cookie"));
body = url_text;
body_len = len;
#endif
if (body == NULL && error_message != NULL) {
//connection error - unersolvable dns name, non existing server
gchar *error_msg_formatted = g_strdup_printf(_("Connection error: %s."), error_message);
purple_connection_error(conn->ya->pc, PURPLE_CONNECTION_ERROR_NETWORK_ERROR, error_msg_formatted);
g_free(error_msg_formatted);
g_object_unref(parser);
g_free(conn);
return;
}
if (body != NULL && !json_parser_load_from_data(parser, body, body_len, NULL)) {
//purple_debug_error("rocketchat", "Error parsing response: %s\n", body);
if (conn->callback) {
JsonNode *dummy_node = json_node_new(JSON_NODE_OBJECT);
JsonObject *dummy_object = json_object_new();
json_node_set_object(dummy_node, dummy_object);
json_object_set_string_member(dummy_object, "body", body);
json_object_set_int_member(dummy_object, "len", body_len);
g_dataset_set_data(dummy_node, "raw_body", (gpointer) body);
conn->callback(conn->ya, dummy_node, conn->user_data, NULL);
g_dataset_destroy(dummy_node);
json_node_free(dummy_node);
json_object_unref(dummy_object);
}
} else {
JsonNode *root = json_parser_get_root(parser);
purple_debug_misc("rocketchat", "Got response: %s\n", body);
if (conn->callback) {
conn->callback(conn->ya, root, conn->user_data, NULL);
}
}
g_object_unref(parser);
g_free(conn);
}
static void
rc_fetch_url(RocketChatAccount *ya, const gchar *url, const gchar *postdata, RocketChatProxyCallbackFunc callback, gpointer user_data)
{
PurpleAccount *account;
RocketChatProxyConnection *conn;
gchar *cookies;
PurpleHttpConnection *http_conn;
account = ya->account;
if (purple_account_is_disconnected(account)) return;
conn = g_new0(RocketChatProxyConnection, 1);
conn->ya = ya;
conn->callback = callback;
conn->user_data = user_data;
cookies = rc_cookies_to_string(ya);
purple_debug_info("rocketchat", "Fetching url %s\n", url);
#if PURPLE_VERSION_CHECK(3, 0, 0)
PurpleHttpRequest *request = purple_http_request_new(url);
purple_http_request_header_set(request, "Accept", "*/*");
purple_http_request_header_set(request, "User-Agent", ROCKETCHAT_USERAGENT);
purple_http_request_header_set(request, "Cookie", cookies);
if (ya->session_token && *ya->session_token) {
purple_http_request_header_set(request, "X-Auth-Token", ya->session_token);
}
if (ya->self_user_id && *ya->self_user_id) {
purple_http_request_header_set(request, "X-User-Id", ya->self_user_id);
}
if (postdata) {
purple_debug_info("rocketchat", "With postdata %s\n", postdata);
if (postdata[0] == '{') {
purple_http_request_header_set(request, "Content-Type", "application/json");
} else {
purple_http_request_header_set(request, "Content-Type", "application/x-www-form-urlencoded");
}
purple_http_request_set_contents(request, postdata, -1);
}
http_conn = purple_http_request(ya->pc, request, rc_response_callback, conn);
purple_http_request_unref(request);
if (http_conn != NULL)
ya->http_conns = g_slist_prepend(ya->http_conns, http_conn);
#else
GString *headers;
gchar *host = NULL, *path = NULL, *user = NULL, *password = NULL;
int port;
purple_url_parse(url, &host, &port, &path, &user, &password);
headers = g_string_new(NULL);
//Use the full 'url' until libpurple can handle path's longer than 256 chars
g_string_append_printf(headers, "%s /%s HTTP/1.0\r\n", (postdata ? "POST" : "GET"), path);
//g_string_append_printf(headers, "%s %s HTTP/1.0\r\n", (postdata ? "POST" : "GET"), url);
g_string_append_printf(headers, "Connection: close\r\n");
g_string_append_printf(headers, "Host: %s\r\n", host);
g_string_append_printf(headers, "Accept: */*\r\n");
g_string_append_printf(headers, "User-Agent: " ROCKETCHAT_USERAGENT "\r\n");
g_string_append_printf(headers, "Cookie: %s\r\n", cookies);
if (ya->session_token && *ya->session_token) {
g_string_append_printf(headers, "X-Auth-Token: %s\r\n", ya->session_token);
}
if (ya->self_user_id && *ya->self_user_id) {
g_string_append_printf(headers, "X-User-Id: %s\r\n", ya->self_user_id);
}
if (postdata) {
purple_debug_info("rocketchat", "With postdata %s\n", postdata);
if (postdata[0] == '{') {
g_string_append(headers, "Content-Type: application/json\r\n");
} else {
g_string_append(headers, "Content-Type: application/x-www-form-urlencoded\r\n");
}
g_string_append_printf(headers, "Content-Length: %" G_GSIZE_FORMAT "\r\n", strlen(postdata));
g_string_append(headers, "\r\n");
g_string_append(headers, postdata);
} else {
g_string_append(headers, "\r\n");
}
g_free(host);
g_free(path);
g_free(user);
g_free(password);
http_conn = purple_util_fetch_url_request_len_with_account(ya->account, url, FALSE, ROCKETCHAT_USERAGENT, TRUE, headers->str, TRUE, 6553500, rc_response_callback, conn);
if (http_conn != NULL)
ya->http_conns = g_slist_prepend(ya->http_conns, http_conn);
g_string_free(headers, TRUE);
#endif
g_free(cookies);
}
static void rc_join_room(RocketChatAccount *ya, const gchar *room_id);
static void rc_socket_write_json(RocketChatAccount *ya, JsonObject *data);
static GHashTable *rc_chat_info_defaults(PurpleConnection *pc, const char *chatname);
static void rc_mark_room_messages_read(RocketChatAccount *ya, const gchar *room_id);
static void rc_account_connected(RocketChatAccount *ya, JsonNode *node, gpointer user_data, JsonObject *error);
static void rc_login_response(RocketChatAccount *ya, JsonNode *node, gpointer user_data, JsonObject *error);
static void rc_got_users_presence(RocketChatAccount *ya, JsonNode *node, gpointer user_data, JsonObject *error);
static void
rc_set_two_factor_auth_code_cb(gpointer data, const gchar *twofactorcode)
{
RocketChatAccount *ya = data;
if (twofactorcode && *twofactorcode) {
//re-login, slightly different format to regular login
JsonArray *params = json_array_new();
JsonObject *param = json_object_new();
JsonObject *totp = json_object_new();
JsonObject *login = json_object_new();
JsonObject *user = json_object_new();
JsonObject *password = json_object_new();
JsonObject *response = json_object_new();
gchar *digest;
// Start a brand new login
if (strchr(ya->username, '@')) {
json_object_set_string_member(user, "email", ya->username);
} else {
json_object_set_string_member(user, "username", ya->username);
}
digest = g_compute_checksum_for_string(G_CHECKSUM_SHA256, purple_connection_get_password(ya->pc), -1);
json_object_set_string_member(password, "digest", digest);
json_object_set_string_member(password, "algorithm", "sha-256");
g_free(digest);
json_object_set_object_member(login, "user", user);
json_object_set_object_member(login, "password", password);
json_object_set_object_member(totp, "login", login);
json_object_set_string_member(totp, "code", twofactorcode);
json_object_set_object_member(param, "totp", totp);
json_array_add_object_element(params, param);
json_object_set_string_member(response, "msg", "method");
json_object_set_string_member(response, "method", "login");
json_object_set_array_member(response, "params", params);
json_object_set_string_member(response, "id", rc_get_next_id_str_callback(ya, rc_login_response, NULL, NULL));
rc_socket_write_json(ya, response);
} else {
purple_connection_error_reason(ya->pc, PURPLE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
"Could not authenticate two-factor code.");
}
}
static void
rc_login_response(RocketChatAccount *ya, JsonNode *node, gpointer user_data, JsonObject *error)
{
JsonObject *response;
if (node == NULL) {
const gchar *error_msg = json_object_get_string_member(error, "error");
if (purple_strequal(error_msg, "totp-required")) {
// needs a 2fa code
purple_request_input(ya->pc, NULL, _("Two-factor authentication"),
_("Open your authentication app and enter the code. You can also use one of your backup codes."), NULL,
FALSE, FALSE, "Two-Factor Auth Code", _("Verify"),
G_CALLBACK(rc_set_two_factor_auth_code_cb), _("Cancel"),
G_CALLBACK(rc_set_two_factor_auth_code_cb), ya->account,
NULL, NULL, ya);
return;
}
purple_debug_error("rocketchat", "Error during login: %s\n", error_msg);
purple_connection_error(ya->pc, PURPLE_CONNECTION_ERROR_AUTHENTICATION_FAILED, "Bad username/password");
return;
}
if (ya->session_token && *ya->session_token && ya->self_user != NULL) {
// Resubscribe if we're reestablishing a session
rc_account_connected(ya, NULL, NULL, NULL);
}
response = json_node_get_object(node);
if (json_object_has_member(response, "token")) {
g_free(ya->session_token);
ya->session_token = g_strdup(json_object_get_string_member(response, "token"));
}
if (!ya->self_user_id && json_object_has_member(response, "id")) {
ya->self_user_id = g_strdup(json_object_get_string_member(response, "id"));
}
//a["{\"msg\":\"result\",\"id\":\"1\",\"result\":{\"id\":\"hZKg86uJavE6jYLya\",\"token\":\"OvG63dE9x79demZnrmBv4vnYYlGMMB-wRKVWFcTxQbv\",\"tokenExpires\":{\"$date\":1485062242977}}}"]
//a["{\"msg\":\"result\",\"id\":\"5\",\"error\":{\"error\":403,\"reason\":\"User has no password set\",\"message\":\"User has no password set [403]\",\"errorType\":\"Meteor.Error\"}}"]
// Download all user presence (requires the session_token)
gchar *url = g_strconcat("https://", ya->server, ya->path, "/api/v1/users.presence", NULL);
rc_fetch_url(ya, url, NULL, rc_got_users_presence, NULL);
g_free(url);
}
static void
rc_got_available_channels(RocketChatAccount *ya, JsonNode *node, gpointer user_data, JsonObject *error)
{
//a["{\"msg\":\"result\",\"id\":\"21\",\"result\":{\"results\":[{\"_id\":\"GENERAL\",\"ts\":{\"$date\":1452986191014},\"name\":\"general\",\"topic\":\"This is a place for discussing open stuff in general. \",\"usersCount\":133},{\"_id\":\"eDKdsqHvNS8daAuht\",\"name\":\"social\",\"ts\":{\"$date\":1481323183876},\"topic\":\"Mastodon is a go! https://mastodon.nzoss.nz\",\"usersCount\":88},{\"_id\":\"MrmrBzkct44AHR2mm\",\"name\":\"random\",\"ts\":{\"$date\":1494728486364},\"usersCount\":83},{\"_id\":\"RBon2Y8FvbM6ekSK4\",\"name\":\"cacophony\",\"ts\":{\"$date\":1504150149829},\"usersCount\":23},{\"_id\":\"EqssvQgYZ9HEFsJ7g\",\"name\":\"technical\",\"ts\":{\"$date\":1455571771183},\"usersCount\":15},{\"_id\":\"GzxgcmSRcCoSg3tmJ\",\"name\":\"meetupchch\",\"ts\":{\"$date\":1459925099523},\"usersCount\":10},{\"_id\":\"eeiXN389SQY9Zfxsr\",\"name\":\"education\",\"ts\":{\"$date\":1481674049811},\"usersCount\":10},{\"_id\":\"DprfYgDrFE3smzgLh\",\"name\":\"constitution\",\"ts\":{\"$date\":1530834056707},\"topic\":\"NZOSS Constitution Reboot\",\"usersCount\":9},{\"_id\":\"4o3kKcoh6JXDvKm2a\",\"name\":\"openhardware\",\"ts\":{\"$date\":1480623613032},\"usersCount\":8},{\"_id\":\"rzBavTjFG4QyGhacE\",\"name\":\"python\",\"ts\":{\"$date\":1494728119751},\"archived\":true,\"usersCount\":8},{\"_id\":\"ALaF23Thjoff3JHSF\",\"name\":\"opengovt\",\"ts\":{\"$date\":1494728230237},\"usersCount\":6},{\"_id\":\"3AXn9yFRELQiuFezB\",\"name\":\"opengis\",\"ts\":{\"$date\":1494728257761},\"usersCount\":5},{\"_id\":\"C4CKsmoxK9dKKqDb3\",\"name\":\"wossat\",\"ts\":{\"$date\":1519946805422},\"usersCount\":5},{\"_id\":\"wdLQs8W84zug82beC\",\"name\":\"javascript\",\"ts\":{\"$date\":1494728110540},\"archived\":true,\"usersCount\":4},{\"_id\":\"s84SH5mL5844qbdrh\",\"name\":\"opendata\",\"ts\":{\"$date\":1494728221034},\"usersCount\":4},{\"_id\":\"PJiokbJ7mymoiu6we\",\"name\":\"openbusiness\",\"ts\":{\"$date\":1494728465740},\"usersCount\":4},{\"_id\":\"EhrKSwyuR4ZjD2xx3\",\"name\":\"jibberjabber\",\"ts\":{\"$date\":1505082070434},\"usersCount\":4},{\"_id\":\"Fu3uA8cMFvaBi67ji\",\"name\":\"infosec\",\"ts\":{\"$date\":1519595381043},\"usersCount\":4},{\"_id\":\"FbbsdW8kdKkF2gTYz\",\"name\":\"r\",\"ts\":{\"$date\":1494728249585},\"usersCount\":3},{\"_id\":\"HWrmJN4CD2sPH42NM\",\"name\":\"meetupakl\",\"ts\":{\"$date\":1494728288813},\"usersCount\":3},{\"_id\":\"ENvJ2XWgorCMrNvxs\",\"name\":\"openphilosophy\",\"ts\":{\"$date\":1494728475274},\"usersCount\":3},{\"_id\":\"Ko5jBjfdFDpY6m4TY\",\"name\":\"support\",\"ts\":{\"$date\":1501634583459},\"usersCount\":3},{\"_id\":\"WuPdbAKoLrxL26efT\",\"name\":\"fab.city\",\"ts\":{\"$date\":1517261907226},\"usersCount\":3}],\"total\":30}}"]
if (node != NULL) {
JsonObject *result = json_node_get_object(node);
JsonArray *results = json_object_get_array_member(result, "results");
gint i, len = json_array_get_length(results);
for (i = 0; i < len; i++) {
JsonObject *room_info = json_array_get_object_element(results, i);
const gchar *room_id = json_object_get_string_member(room_info, "_id");
const gchar *topic = json_object_get_string_member(room_info, "topic");
const gchar *room_name = json_object_get_string_member(room_info, "name");
PurpleChatConversation *chatconv = purple_conversations_find_chat_with_account(room_name, ya->account);
if (chatconv == NULL) {
chatconv = purple_conversations_find_chat_with_account(room_id, ya->account);
}
if (chatconv != NULL && topic != NULL) {
gchar *html_topic = rc_markdown_to_html(topic);
purple_chat_conversation_set_topic(chatconv, NULL, html_topic);
g_free(html_topic);
}
g_hash_table_replace(ya->group_chats, g_strdup(room_id), g_strdup(room_name));
g_hash_table_replace(ya->group_chats_rev, g_strdup(room_name), g_strdup(room_id));
}
}
}
static void
rc_got_open_rooms(RocketChatAccount *ya, JsonNode *node, gpointer user_data, JsonObject *error)