forked from phinze/tircd
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tircd.pl
executable file
·2038 lines (1725 loc) · 76.4 KB
/
tircd.pl
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
#!/usr/bin/perl
# tircd - An ircd proxy to the Twitter API
# Copyright (c) 2009 Chris Nelson <[email protected]>
# Copyright (c) 2010-2011 Tim Sogard <[email protected]>
# tircd is free software; you can redistribute it and/or modify it under the terms of either:
# a) the GNU General Public License as published by the Free Software Foundation
# b) the "Artistic License"
use strict;
use JSON::Any;
use Net::Twitter::Lite::WithAPIv1_1 0.12000;
use Time::Local;
use File::Glob ':glob';
use IO::File;
use LWP::UserAgent;
use Storable;
use POE qw(Component::Server::TCP Filter::Stackable Filter::Map Filter::IRCD);
use URI qw/host/;
use List::Util 'shuffle';
# @Olatho - issue 45
use HTML::Entities;
use Digest::SHA qw(sha1_base64);
my $VERSION = 20141220;
# consumer key/secret in the executable instead of config because it should not be edited by user
# Only uncomment one copy of the keys! By default the original API keys are used
# these keys belong to the original tircd app
my $tw_oauth_con_key = "4AQca4GFiWWaifUknq35Q";
my $tw_oauth_con_sec = "VB0exmHlErkx4GUUsXvoR4bqaXi56Rl43NL1Z9Q";
# these keys are registered as tircd-nuxi just in case the above ever broke
#my $tw_oauth_con_key = "Tw9E0lMl7CF0feka42B5SA";
#my $tw_oauth_con_sec = "iHaFHHEXcxEvLCItHRiIbc0XC9eWl29fSOdOXJ39dvM";
# I have no idea what the minimum Net::Twitter::Lite version is
#Do some sanity checks on the environment and warn if not what we want
#if ($Net::Twitter::Lite::VERSION < 2.10) {
# print "Warning: Your system has an old version of Net::Twitter::Lite. Please upgrade to the current version.\n";
#}
my $j = JSON::Any->new;
if ($j->handlerType eq 'JSON::Syck') {
print "Warning: Your system is using JSON::Syck. This will cause problems with character encoding. Please install JSON::PP or JSON::XS.\n";
}
#load and parse our own very simple config file
#didn't want to introduce another module requirement to parse XML or a YAML file
my $config_file = '/etc/tircd.cfg';
if ($ARGV[0]) {
$config_file = $ARGV[0];
} elsif (-e 'tircd.cfg') {
$config_file = 'tircd.cfg';
} elsif (-e bsd_glob('~',GLOB_TILDE | GLOB_ERR).'/.tircd') {
$config_file = bsd_glob('~',GLOB_TILDE | GLOB_ERR).'/.tircd';
}
open(C,$config_file) || die("$0: Unable to load config file ($config_file): $!\n");
my %config = ();
while (<C>) {
chomp;
next if /^#/ || /^$/;
my ($key,$value) = split(/\s/,$_,2);
$config{$key} = $value;
}
close(C);
#config file backwards compatibility
$config{'timeline_count'} = 20 if !exists $config{'timeline_count'};
$config{'storage_path'} =~ s/~/$ENV{'HOME'}/ if ($config{'storage_path'} =~ /~/);
#storage for connected users
my %users;
#setup our filter to process the IRC messages, jacked from the Filter::IRCD docs
my $filter = POE::Filter::Stackable->new();
$filter->push( POE::Filter::Line->new( InputRegexp => '\015?\012', OutputLiteral => "\015\012" ));
#twitter's json feed escapes < and >, let's fix that
$filter->push( POE::Filter::Map->new(Code => sub {
local $_ = shift;
# @Olatho - Issue 45 - see also issue 50
decode_entities($_);
return $_;
}));
if ($config{'debug'} > 1) {
$filter->push(POE::Filter::IRCD->new(debug => 1));
} else {
$filter->push(POE::Filter::IRCD->new(debug => 0));
}
# if configured to use SSL, and no env vars yet defined, set to config settings
if ($config{'use_ssl'} == 1 && !($ENV{'HTTPS_CA_FILE'} || $ENV{'HTTPS_CA_DIR'})) {
if ($config{'https_ca_file'} and -e $config{'https_ca_file'}) {
$ENV{'HTTPS_CA_FILE'} = $config{'https_ca_file'};
} elsif ($config{'https_ca_dir'} && -d $config{'https_ca_dir'}) {
$ENV{'HTTPS_CA_DIR'} = $config{'https_ca_dir'};
}
}
#if needed setup our logging sesstion
if ($config{'logtype'} ne 'none') {
POE::Session->create(
inline_states => {
_start => \&logger_setup,
log => \&logger_log
},
args => [$config{'logtype'},$config{'logfile'}]
);
}
#setup our 'irc server'
POE::Component::Server::TCP->new(
Alias => "tircd",
Address => $config{'address'},
Port => $config{'port'},
InlineStates => {
PASS => \&irc_pass,
NICK => \&irc_nick,
USER => \&irc_user,
MOTD => \&irc_motd,
MODE => \&irc_mode,
JOIN => \&irc_join,
PART => \&irc_part,
WHO => \&irc_who,
WHOIS => \&irc_whois,
PRIVMSG => \&irc_privmsg,
STATS => \&irc_stats,
INVITE => \&irc_invite,
KICK => \&irc_kick,
QUIT => \&irc_quit,
PING => \&irc_ping,
AWAY => \&irc_away,
TOPIC => \&irc_topic,
'#twitter' => \&channel_twitter,
server_reply => \&irc_reply,
user_msg => \&irc_user_msg,
handle_command => \&irc_twitterbot_command,
twitter_post_tweet => \&twitter_post_tweet,
twitter_retweet_tweet => \&twitter_retweet_tweet,
twitter_favorite_tweet => \&twitter_favorite_tweet,
twitter_reply_to_tweet => \&twitter_reply_to_tweet,
twitter_send_dm => \&twitter_send_dm,
twitter_conversation => \&twitter_conversation,
twitter_conversation_r => \&twitter_conversation_r,
twitter_conversation_related => \&twitter_conversation_related,
twitter_api_error => \&twitter_api_error,
twitter_timeline => \&twitter_timeline,
twitter_direct_messages => \&twitter_direct_messages,
twitter_search => \&twitter_search,
login => \&tircd_login,
getfriend => \&tircd_getfriend,
remfriend => \&tircd_remfriend,
updatefriend => \&tircd_updatefriend,
getfollower => \&tircd_getfollower,
verify_ssl => \&tircd_verify_ssl,
basicauth_login => \&twitter_basic_login,
setup_authenticated_user => \&tircd_setup_authenticated_user,
oauth_login_begin => \&twitter_oauth_login_begin,
oauth_login_finish => \&twitter_oauth_login_finish,
oauth_pin_ask => \&twitter_oauth_pin_ask,
oauth_pin_entry => \&twitter_oauth_pin_entry,
no_pin_received => \&tircd_oauth_no_pin_received,
save_config => \&tircd_save_config,
get_message_parts => \&tircd_get_message_parts,
},
ClientFilter => $filter,
ClientInput => \&irc_line,
ClientConnected => \&tircd_connect,
ClientDisconnected => \&tircd_cleanup,
Started => \&tircd_setup
);
$poe_kernel->run();
exit 0;
########## STARTUP FUNCTIONS BEGIN
sub tircd_setup {
$_[KERNEL]->call('logger','log',"tircd $VERSION started, using config from: $config_file.");
$_[KERNEL]->call('logger','log',"Listening on: $config{'address'}:$config{'port'}.");
if ($config{'debug'}) {
$_[KERNEL]->call('logger','log',"Using Net::Twitter::Lite version: $Net::Twitter::Lite::VERSION");
$_[KERNEL]->call('logger','log',"Using LWP::UserAgent version: $LWP::UserAgent::VERSION");
$_[KERNEL]->call('logger','log',"Using POE::Filter::IRCD version: $POE::Filter::IRCD::VERSION");
}
}
#setup our logging session
sub logger_setup {
my ($kernel, $heap, $type, $file) = @_[KERNEL, HEAP, ARG0, ARG1];
$_[KERNEL]->alias_set('logger');
my $handle = 0;
if ($type eq 'file') {
$handle = IO::File->new(">>$file");
} elsif ($type eq 'stdout') {
$handle = \*STDOUT;
} elsif ($type eq 'stderr') {
$handle = \*STDERR;
}
if ($handle) {
#Win32 seems to blow up when trying to set FIONBIO on STDOUT/ERR
$heap->{'file'} = ($^O eq 'MSWin32' && $type ne 'file') ? $handle : POE::Wheel::ReadWrite->new( Handle => $handle );
}
}
########## 'INTERNAL' UTILITY FUNCTIONS
#log a message
sub logger_log {
my ($heap, $msg, $from) = @_[HEAP, ARG0, ARG1];
return if ! $heap->{'file'};
$from = "[$from] " if defined $from;
my $stamp = '['.localtime().'] ';
if (ref $heap->{'file'} eq 'POE::Wheel::ReadWrite') {
$heap->{'file'}->put("$stamp$from$msg");
} else {
$heap->{'file'}->print("$stamp$from$msg\n");
}
}
#trap twitter api errors
sub twitter_api_error {
my ($kernel,$heap, $msg, $error) = @_[KERNEL, HEAP, ARG0, ARG1];
if ($config{'debug'}) {
$kernel->post('logger','log',$error->message().' '.$error->code().' '.$error,'debug/twitter_api_error');
}
if ($error) {
$kernel->post('logger','log',$msg.' ('.$error->code() .' from Twitter API).',$heap->{'username'});
if ($error->code() == 429) {
$msg .= ' Twitter API limit reached.';
} else {
$msg .= ' Twitter Fail Whale.';
}
}
else {
$kernel->post('logger','log',$msg.' (Unknown error from Twitter API).',$heap->{'username'});
}
$kernel->yield('server_reply',461,'#twitter',$msg);
}
#update a friend's info in the heap
sub tircd_updatefriend {
my ($heap, $new) = @_[HEAP, ARG0];
foreach my $friend (@{$heap->{'friends'}}) {
if ($friend->{'id'} == $new->{'id'}) {
$friend = $new;
return 1;
}
}
return 0;
}
#check to see if a given friend exists, and return it
sub tircd_getfriend {
my ($heap, $target) = @_[HEAP, ARG0];
foreach my $friend (@{$heap->{'friends'}}) {
if ($friend->{'screen_name'} eq $target) {
return $friend;
}
}
return 0;
}
sub tircd_getfollower {
my ($heap, $target) = @_[HEAP, ARG0];
foreach my $follower (@{$heap->{'followers'}}) {
if ($follower->{'screen_name'} eq $target) {
return $follower;
}
}
return 0;
}
sub tircd_remfriend {
my ($heap, $target) = @_[HEAP, ARG0];
my @tmp = ();
foreach my $friend (@{$heap->{'friends'}}) {
if ($friend->{'screen_name'} ne $target) {
push(@tmp,$friend);
}
}
$heap->{'friends'} = \@tmp;
}
#called once we have a user/pass, attempts to auth with twitter
sub tircd_login {
my ($kernel, $heap, $data) = @_[KERNEL, HEAP, ARG0];
if ($heap->{'twitter'}) { #make sure we aren't called twice
return;
}
$heap->{'nt_params'}{'source'} = "tircd";
# use SSL?
if ($config{'use_ssl'}) {
$heap->{'nt_params'}{'ssl'} = 1;
# verify_ssl will drop user if SSL checks fail
return unless($kernel->call($_[SESSION],'verify_ssl'));
}
# begin oauth authentication flow
return $kernel->call($_[SESSION],'oauth_login_begin');
}
# oauth login flow
sub twitter_oauth_login_begin {
my ($kernel, $heap) = @_[KERNEL, HEAP];
$heap->{'nt_params'}{'consumer_key'} = $tw_oauth_con_key;
$heap->{'nt_params'}{'consumer_secret'} = $tw_oauth_con_sec;
eval "use Net::OAuth 0.16";
if ($@) {
$kernel->yield('server_reply',463,'Net::OAuth >= 0.16 is not installed');
$kernel->yield('server_reply',463,'OAuth authentication requires Net::OAuth version 0.16 or greater.');
$kernel->yield('shutdown');
}
$kernel->yield('server_reply',463,'OAuth authentication beginning.');
$heap->{'twitter'} = Net::Twitter::Lite::WithAPIv1_1->new(%{$heap->{'nt_params'}});
# load user config from disk for reusing tokens
if (-d $config{'storage_path'}) {
if (-f $config{'storage_path'} . '/' . lc($heap->{'username'}) . '.config') {
$heap->{'config'} = eval {retrieve($config{'storage_path'} . '/' . lc($heap->{'username'}) . '.config');};
} else {
$heap->{'config'} = eval {retrieve($config{'storage_path'} . '/' . $heap->{'username'} . '.config');};
}
}
if ($heap->{'config'}->{'username'}) {
$heap->{'username'} = $heap->{'config'}->{'username'};
}
# if tokens exist in users config, attempt to re-use
if ($heap->{'config'}->{'access_token'} && $heap->{'config'}->{'access_token_secret'}) {
# If password is set in user state - check that is is correct
if ($heap->{'config'}->{'password'} =~ m#[a-zA-Z0-9+/]{27}# ) {
if ($heap->{'password'} ne $heap->{'config'}->{'password'}) {
$kernel->post('logger','log','Connection refused with the supplied credentials.',$heap->{'username'});
$kernel->yield('server_reply',464,'Connection refused with the supplied credentials.');
$kernel->yield('shutdown'); #disconnect 'em if we cant verify password
return;
}
}
$heap->{'twitter'}->access_token($heap->{'config'}->{'access_token'});
$heap->{'twitter'}->access_token_secret($heap->{'config'}->{'access_token_secret'});
return if $kernel->call($_[SESSION],'oauth_login_finish');
}
unless($heap->{'twitter'}->authorized) {
$kernel->call($_[SESSION],'oauth_pin_ask');
}
return 1;
}
# direct user to pin site
sub twitter_oauth_pin_ask {
my ($kernel, $heap) = @_[KERNEL,HEAP];
$@=undef;
my $authorization_url = eval { $heap->{'twitter'}->get_authorization_url() };
if ($@) {
$kernel->yield('server_reply',599,"Unable to retrieve authentication URL from Twitter.");
$kernel->yield('server_reply',599,"$@");
$kernel->yield('server_reply',599,"The Twitter API seems to be experiencing problems. Try again momentarily.");
$kernel->yield('shutdown');
return 1;
}
$kernel->yield('server_reply',463,"Please authorize this connection at:");
$kernel->yield('server_reply',463,$authorization_url);
$kernel->yield('server_reply',463,"To continue connecting, type /stats pin <PIN>, where <PIN> is the PIN returned by the twitter authorize page.");
$kernel->yield('server_reply',463,"Some clients require you to use /quote stats pin <PIN>");
# half an hour until disconnect
$kernel->alarm('no_pin_received',time() + 1800);
return 1;
}
# received pin msg
sub twitter_oauth_pin_entry {
my ($kernel, $pin) = @_[KERNEL, ARG0];
# clear ask timeout alarm
$kernel->alarm('no_pin_received');
return $kernel->call($_[SESSION],'oauth_login_finish',$pin);
}
sub twitter_oauth_login_finish {
my ($kernel, $heap, $pin) = @_[KERNEL, HEAP, ARG0];
# make token ask if pin provided
if ($pin) {
my ($access_token, $access_token_secret, $user_id, $username) = eval { $heap->{'twitter'}->request_access_token(verifier=>$pin) };
if ($@) {
if ($@ =~ m/401/) {
$kernel->yield('server_reply',510,'Unable to authorize with this PIN. Please try again.');
} else {
$kernel->yield('server_reply',511,'Unknown error while authorizing. Please try again.');
}
$kernel->yield('oauth_pin_ask');
return;
}
# check if already logged in
if (exists $users{$username}) {
$kernel->yield('server_reply',436,$username,'You are already connected to Twitter with this username.');
$kernel->yield('shutdown');
return 1;
}
# store tokens and user info in config for later use.
$heap->{'config'}->{'access_token'} = $access_token;
$heap->{'config'}->{'access_token_secret'} = $access_token_secret;
$heap->{'config'}->{'user_id'} = $user_id;
$heap->{'config'}->{'username'} = $username;
$heap->{'username'} = $username;
}
# make sure we're happy, otherwise re-try PIN ask
unless($heap->{'twitter'}->authorized) {
$kernel->post('logger','log','Unable to retrieve access tokens for entered PIN.');
$kernel->yield('server_reply',462,'Invalid PIN. Re-check PIN and try again.');
$kernel->yield('oauth_pin_ask');
return;
}
$kernel->yield('server_reply',399,'PIN accepted.');
$kernel->yield('setup_authenticated_user');
return 1;
}
sub tircd_setup_authenticated_user {
my ($kernel, $heap) = @_[KERNEL, HEAP];
#load our configs from disk if they exist
if (-d $config{'storage_path'}) {
if (-f $config{'storage_path'} . '/' . lc($heap->{'username'}) . '.channels') {
$heap->{'channels'} = eval {retrieve($config{'storage_path'} . '/' . lc($heap->{'username'}) . '.channels');};
} else {
$heap->{'channels'} = eval {retrieve($config{'storage_path'} . '/' . $heap->{'username'} . '.channels');};
}
}
my @user_settings = qw(update_timeline update_directs timeline_count long_messages min_length max_splits join_silent filter_self shorten_urls convert_irc_replies store_access_tokens access_token access_token_secret auto_post display_ticker_slots show_realname expand_urls password);
# update users config to contain all necessary settings, weed out unnecessary
foreach my $s (@user_settings) {
unless (exists($heap->{'config'}->{$s})) {
$heap->{'config'}->{$s} = $config{$s};
}
}
foreach my $k (keys %{$heap->{'config'}}) {
if (!grep($_ eq $k, @user_settings)) {
delete $heap->{'config'}->{$k};
}
}
# If the client has connected with a password, and is authorized by twitter,
# encrypt and store password if it is not already stored
if ($heap->{'password'} && !($heap->{'config'}->{'password'})) {
$heap->{'config'}->{'password'} = $heap->{'password'};
$kernel->yield('save_config');
}
if (!$heap->{'channels'}) {
$heap->{'channels'} = {};
}
if (defined($heap->{'channels'}->{'__STATE'})){
$heap->{'timeline_since_id'} = $heap->{'channels'}->{'__STATE'}->{'timeline_since_id'} || 0;
$heap->{'replies_since_id'} = $heap->{'channels'}->{'__STATE'}->{'replies_since_id'} || 0;
$heap->{'direct_since_id'} = $heap->{'channels'}->{'__STATE'}->{'direct_since_id'} || 0;
}
#we need this for the tinyurl support and others
$heap->{'ua'} = LWP::UserAgent->new;
$heap->{'ua'}->timeout(10);
$heap->{'ua'}->env_proxy();
# allow channel joining
$heap->{'authenticated'} = 1;
#stash the username in a list to keep 'em from rejoining
$users{$heap->{'username'}} = 1;
#some clients need this shit
$kernel->yield('server_reply','001',"Welcome to tircd $heap->{'username'}");
$kernel->yield('server_reply','002',"Your host is tircd running version $VERSION");
$kernel->yield('server_reply','003',"This server was created just for you!");
$kernel->yield('server_reply','004',"tircd $VERSION");
#show 'em the motd
$kernel->yield('MOTD');
}
sub tircd_oauth_no_pin_received {
my ($kernel, $heap) = @_[KERNEL, HEAP];
# we didn't receive a pin in time
$kernel->post('logger','log','No PIN entered, disconnecting user: ',$heap->{'username'});
$kernel->yield('server_reply',532,'Never received a PIN. Disconnecting');
$kernel->yield('shutdown'); #disconnect 'em if we cant
return;
}
sub tircd_verify_ssl {
my($kernel) = @_[KERNEL];
# unless we have a bundle or directory of certs to verify against, ssl is b0rked
unless($ENV{'HTTPS_CA_FILE'} or $ENV{'HTTPS_CA_DIR'}) {
$kernel->yield('logger','log',"You must provide the environment variable HTTPS_CA_FILE or HTTPS_CA_DIR before starting tircd.pl in order to verify SSL certificates.");
$kernel->yield('server_reply',462,'Unable to verify SSL certificate');
$kernel->yield('shutdown'); #disconnect 'em if we cant
return;
}
# check ssl cert using LWP
my $api_check = Net::Twitter::Lite::WithAPIv1_1->new(('ssl' => 1 ));
my $sslcheck = LWP::UserAgent->new;
my $apiurl = URI->new($api_check->{'apiurl'});
# second level domain, aka domain.tld. if this is present in the certificate, we are happy
my $SLD = $apiurl->host;
$SLD =~ s/.*\.([^.]*\.[^.]*)/$1/;;
# if-ssl-cert-subject causes the certificate subject line to be checked against the regex in its value
# upon checking the certificate, it will cancel the request and set the HTTP::Response is_error to 1 for us
$sslcheck->default_header("If-SSL-Cert-Subject" => "CN=(.*\.){0,1}$SLD");
# knock politely
my $sslresp = $sslcheck->get($apiurl);
# cert failed to verify against local bundle/ca_dir
if( $sslresp->header('client-ssl-warning') ) {
$kernel->yield('logger','log',"Unable to verify server certificate against local authority.");
$kernel->yield('server_reply',462,'Unable to verify SSL certificate.');
$kernel->yield('shutdown');
return;
}
# cert response failed to be for expected domain
if( $sslresp->is_error && $sslresp->code == 500 ) {
$kernel->yield('logger','log',"Hostname (CN) of SSL certificate did not match domain being accessed, someone is doing something nasty!");
$kernel->yield('server_reply',462,'SSL certificate has invalid Common Name (CN).');
$kernel->yield('shutdown');
return;
}
# all SLL checks passed
return 1;
}
sub tircd_connect {
my ($kernel, $heap) = @_[KERNEL, HEAP];
$kernel->post('logger','log',$heap->{'remote_ip'}.' connected.');
}
sub tircd_cleanup {
my ($kernel, $heap) = @_[KERNEL, HEAP];
$kernel->post('logger','log',$heap->{'remote_ip'}.' disconnected.',$heap->{'username'});
# stop the oauth no pin entry alarm
$kernel->alarm('no_pin_received');
#delete the username
delete $users{$heap->{'username'}};
#remove our timers so the session will die
$kernel->delay('twitter_timeline');
$kernel->delay('twitter_direct_messages');
#mark all channels as not joined for the next reload
foreach my $chan (keys %{$heap->{'channels'}}) {
$heap->{'channels'}->{$chan}->{'joined'} = 0;
}
$kernel->yield('save_config');
$kernel->yield('shutdown');
}
# Save config
sub tircd_save_config {
my ($kernel, $heap) = @_[KERNEL, HEAP];
# if storage_path directory doesn't exist, attempt to create
unless ( -e $config{'storage_path'} && -d $config{'storage_path'} ) {
unless (mkdir ($config{'storage_path'})) {
$kernel->post('logger','log','Was unable to create storage_path at ' . $config{'storage_path'} . ' .' . $!);
return 0;
}
}
#if we can, save user_settings and state for next time
if ($config{'storage_path'} && -d $config{'storage_path'} && -w $config{'storage_path'}) {
# save incoming tweet state in hidden channel
$heap->{'channels'}->{'__STATE'}->{'timeline_since_id'} = $heap->{'timeline_since_id'};
$heap->{'channels'}->{'__STATE'}->{'replies_since_id'} = $heap->{'replies_since_id'};
$heap->{'channels'}->{'__STATE'}->{'direct_since_id'} = $heap->{'direct_since_id'};
# clip out tokens if requested
my $store_config = $heap->{'config'};
if ($heap->{'config'}->{'store_access_tokens'} == 0) {
delete $store_config->{'access_token'};
delete $store_config->{'access_token_secret'};
}
eval {store($heap->{'config'},$config{'storage_path'} . '/' . lc($heap->{'username'}) . '.config');};
eval {store($heap->{'channels'},$config{'storage_path'} . '/' . lc($heap->{'username'}) . '.channels');};
$kernel->post('logger','log','Saving configuration.',$heap->{'username'});
return 1;
} else {
$kernel->post('logger','log','storage_path is not set or is not writable, not saving configuration.',$heap->{'username'});
return 0;
}
}
########## 'INTERNAL' IRC I/O FUNCTIONS
#called everytime we get a line from an irc server
#trigger an event and move on, the ones we care about will get trapped
sub irc_line {
my ($kernel, $data) = @_[KERNEL, ARG0];
if ($config{'debug'}) {
if (!$data->{'params'}) {
$data->{'params'} = [];
}
$kernel->post('logger','log',$data->{'prefix'}.' '.$data->{'command'}.' '.join(' ',@{$data->{'params'}}),'debug/irc_line');
}
$kernel->yield($data->{'command'},$data);
}
#send a message that looks like it came from a user
sub irc_user_msg {
my ($kernel, $heap, $code, $username, @params) = @_[KERNEL, HEAP, ARG0, ARG1, ARG2..$#_];
foreach my $p (@params) { #fix multiline tweets, submitted a patch to Filter::IRCD to fix this in the long term
$p =~ s/\n/ /g;
}
if ($config{'debug'}) {
$kernel->post('logger','log',$username.' '.$code.' '.join(' ',@params),'debug/irc_user_msg');
}
$heap->{'client'}->put({
command => $code,
prefix => "$username!$username\@twitter",
params => \@params
});
}
#send a message that comes from the server
sub irc_reply {
my ($kernel, $heap, $code, @params) = @_[KERNEL, HEAP, ARG0, ARG1..$#_];
foreach my $p (@params) {
$p =~ s/\n/ /g;
}
if ($code ne 'PONG' && $code ne 'MODE' && $code != 436) {
unshift(@params,$heap->{'username'}); #prepend the target username to the message;
}
if ($config{'debug'}) {
$kernel->post('logger','log',':tircd '.$code.' '.join(' ',@params),'debug/irc_reply');
}
$heap->{'client'}->put({
command => $code,
prefix => 'tircd',
params => \@params
});
}
########### IRC EVENT FUNCTIONS
sub irc_pass {
my ($heap, $data) = @_[HEAP, ARG0];
$heap->{'password'} = sha1_base64($data->{'params'}[0]); #encrypt stash the password for later
}
sub irc_nick {
my ($kernel, $heap, $data) = @_[KERNEL, HEAP, ARG0];
if ($heap->{'username'}) { #if we've already got their nick, don't let them change it
$kernel->yield('server_reply',433,'Changing nicks once connected is not currently supported.');
return;
}
$heap->{'username'} = lc($data->{'params'}[0]); #stash the username for later
if (!$heap->{'twitter'}) {
$kernel->yield('login');
}
}
sub irc_user {
my ($kernel, $heap, $data) = @_[KERNEL, HEAP, ARG0];
# proceed to login if we have the nick and no connection
if ($heap->{'username'} && !$heap->{'twitter'}) {
$kernel->yield('login');
}
}
#return the MOTD
sub irc_motd {
my ($kernel, $heap, $data) = @_[KERNEL, HEAP, ARG0];
$kernel->yield('server_reply',375,'- tircd Message of the Day -');
my $ua = LWP::UserAgent->new;
$ua->timeout(5);
$ua->env_proxy();
my $res = $ua->get('http://vault24.org/cgit/~nuxi/tircd.git/plain/motd.txt');
if (!$res->is_success) {
$kernel->yield('server_reply',372,"- Unable to get the MOTD.");
} else {
my @lines = split(/\n/,$res->content);
foreach my $line (@lines) {
$kernel->yield('server_reply',372,"- $line");
}
}
$kernel->yield('server_reply',376,'End of /MOTD command.');
}
sub irc_join {
my ($kernel, $heap, $data) = @_[KERNEL, HEAP, ARG0];
unless($heap->{'authenticated'}) {
$kernel->yield('server_reply',508,"Unable to join ", $data->{'params'}[0],".");
$kernel->yield('server_reply',509,"Connection not yet authorized.");
return;
}
my @chans = split(/\,/,$data->{'params'}[0]);
foreach my $chan (@chans) {
$chan =~ s/\s//g;
#see if we've registered an event handler for a 'special channel' (currently only #twitter)
if ($kernel->call($_[SESSION],$chan,$chan)) {
next;
}
#we might have something saved already, if not prep a new channel
if (!exists $heap->{'channels'}->{$chan} ) {
$heap->{'channels'}->{$chan} = {};
$heap->{'channels'}->{$chan}->{'names'}->{$heap->{'username'}} = '@';
}
$heap->{'channels'}->{$chan}->{'joined'} = 1;
#otherwise, prep a blank channel
$kernel->yield('user_msg','JOIN',$heap->{'username'},$chan);
$kernel->yield('server_reply',332,$chan,"$chan");
$kernel->yield('server_reply',333,$chan,'tircd!tircd@tircd',time());
#send the /NAMES info
my $all_users = '';
foreach my $name (keys %{$heap->{'channels'}->{$chan}->{'names'}}) {
$all_users .= $heap->{'channels'}->{$chan}->{'names'}->{$name} . $name .' ';
}
$kernel->yield('server_reply',353,'=',$chan,$all_users);
$kernel->yield('server_reply',366,$chan,'End of /NAMES list');
#restart the searching
if ($heap->{'channels'}->{$chan}->{'topic'}) {
$kernel->yield('user_msg','TOPIC',$heap->{'username'},$chan,$heap->{'channels'}->{$chan}->{'topic'});
# Searching is started when topic is set so this is redundant and causes frequent errors from twitter
# $kernel->yield('twitter_search',$chan);
# $kernel->post('logger','log','Started search after rejoin - ' . $heap->{'channels'}->{$chan}->{'topic'} . ' - ' . $heap->{'channels'}->{$chan}->{'search_since_id'});
}
}
}
sub irc_part {
my ($kernel, $heap, $data) = @_[KERNEL, HEAP, ARG0];
my $chan = $data->{'params'}[0];
if ($heap->{'channels'}->{$chan}->{'joined'}) {
delete $heap->{'channels'}->{$chan};
$kernel->yield('user_msg','PART',$heap->{'username'},$chan);
} else {
$kernel->yield('server_reply',442,$chan,"You're not on that channel");
}
}
sub irc_mode { #ignore all mode requests except ban which is a block (send back the appropriate message to keep the client happy)
#this whole thing is messy as hell, need to refactor this function
my ($kernel, $heap, $data) = @_[KERNEL, HEAP, ARG0];
my $target = $data->{'params'}[0];
my $mode = $data->{'params'}[1];
my $opts = $data->{'params'}[2];
#extract the nick from the banmask
my ($nick,$host) = split(/\!/,$opts,2);
$nick =~ s/\*//g;
if (!$nick) {
$host =~ s/\*//g;
if ($host =~ /(.*)\@twitter/) {
$nick = $1;
}
}
if ($target =~ /^\#/) {
if ($mode eq 'b') {
$kernel->yield('server_reply',368,$target,'End of channel ban list');
return;
}
if ($target eq '#twitter') {
if ($mode eq '+b' && $target eq '#twitter') {
my $user = eval { $heap->{'twitter'}->create_block($nick) };
my $error = $@;
if ($user) {
$kernel->yield('user_msg','MODE',$heap->{'username'},$target,$mode,$opts);
} else {
if (ref $error && $error->isa("Net::Twitter::Lite::Error") && $error->code() >= 400) {
$kernel->call($_[SESSION],'twitter_api_error','Unable to block user.',$error);
} else {
$kernel->yield('server_reply',401,$nick,'No such nick/channel');
}
}
return;
} elsif ($mode eq '-b' && $target eq '#twitter') {
my $user = eval { $heap->{'twitter'}->destroy_block($nick) };
my $error = $@;
if ($user) {
$kernel->yield('user_msg','MODE',$heap->{'username'},$target,$mode,$opts);
} else {
if (ref $error && $error->isa("Net::Twitter::Lite::Error") && $error->code() >= 400) {
$kernel->call($_[SESSION],'twitter_api_error','Unable to unblock user.',$error);
} else {
$kernel->yield('server_reply',401,$nick,'No such nick/channel');
}
}
return;
}
}
if (!$mode) {
$kernel->yield('server_reply',324,$target,"+t");
}
return;
}
$kernel->yield('user_msg','MODE',$heap->{'username'},$target,'+i');
}
sub irc_who {
my ($kernel, $heap, $data) = @_[KERNEL, HEAP, ARG0];
my $target = $data->{'params'}[0];
if ($target =~ /^\#/) {
if (exists $heap->{'channels'}->{$target}) {
foreach my $name (keys %{$heap->{'channels'}->{$target}->{'names'}}) {
if (my $friend = $kernel->call($_[SESSION],'getfriend',$name)) {
$kernel->yield('server_reply',352,$target,$name,'twitter','tircd',$name,'G'.$heap->{'channels'}->{$target}->{'names'}->{$name},"0 $friend->{'name'}");
}
}
}
} else { #only support a ghetto version of /who right now, /who ** and what not won't work
if (my $friend = $kernel->call($_[SESSION],'getfriend',$target)) {
$kernel->yield('server_reply',352,'*',$friend->{'screen_name'},'twitter','tircd',$friend->{'screen_name'}, "G","0 $friend->{'name'}");
}
}
$kernel->yield('server_reply',315,$target,'End of /WHO list');
}
sub irc_whois {
my ($kernel, $heap, $data) = @_[KERNEL, HEAP, ARG0];
my $target = $data->{'params'}[0];
my $friend = $kernel->call($_[SESSION],'getfriend',$target);
my $isfriend = 1;
my $error;
if (!$friend) {#if we don't have their info already try to get it from twitter, and track it for the end of this function
$friend = eval { $heap->{'twitter'}->show_user({screen_name => $target}) };
$error = $@;
$isfriend = 0;
}
if (ref $error && $error->isa("Net::Twitter::Lite::Error") && $error->code() == 404) {
$kernel->yield('server_reply',402,$target,'No such server');
return;
}
if (!$friend && ref $error && $error->isa("Net::Twitter::Lite::Error") && $error->code() >= 400) {
$kernel->call($_[SESSION],'twitter_api_error','Unable to get user information.',$error);
return;
}
if ($friend) {
$kernel->post('logger','log',"Received user information for $target from Twitter.",$heap->{'username'});
$kernel->yield('server_reply',311,$target,$target,'twitter','*',$friend->{'name'});
#send a bunch of 301s to convey all the twitter info, not sure if this is totally legit, but the clients I tested with seem ok with it
if ($friend->{'location'}) {
$kernel->yield('server_reply',301,$target,"Location: $friend->{'location'}");
}
if ($friend->{'url'}) {
$kernel->yield('server_reply',301,$target,"Web: $friend->{'url'}");
}
if ($friend->{'description'}) {
$kernel->yield('server_reply',301,$target,"Bio: $friend->{'description'}");
}
if ($friend->{'status'}->{'text'}) {
$kernel->yield('server_reply',301,$target,"Last Update: ".$friend->{'status'}->{'text'});
}
if ($target eq $heap->{'username'}) { #if it's us, then add the rate limit info to
my $rate = eval { $heap->{'twitter'}->rate_limit_status() };
$kernel->yield('server_reply',301,$target,'API Usage: '.($rate->{'hourly_limit'}-$rate->{'remaining_hits'})." of $rate->{'hourly_limit'} calls used.");
$kernel->post('logger','log','Current API usage: '.($rate->{'hourly_limit'}-$rate->{'remaining_hits'})." of $rate->{'hourly_limit'}",$heap->{'username'});
}
#treat their twitter client as the server
my $server; my $info;
# if ($friend->{'status'}->{'source'} =~ /\<a href="(.*)"\>(.*)\<\/a\>/) { #not sure this regex will work in all cases
# Fix for issue 87
if ($friend->{'status'}->{'source'} =~ /\<a href="([^"]*)".*\>(.*)\<\/a\>/) {
$server = $2;
$info = $1;
} else {
$server = 'web';
$info = 'http://www.twitter.com/';
}
$kernel->yield('server_reply',312,$target,$server,$info);
#set their idle time, to the time since last message (if we have one, the api won't return the most recent message for users who haven't updated in a long time)
my $diff = 0;
my %mon2num = qw(Jan 0 Feb 1 Mar 2 Apr 3 May 4 Jun 5 Jul 6 Aug 7 Sep 8 Oct 9 Nov 10 Dec 11);
if ($friend->{'status'}->{'created_at'} =~ /\w+ (\w+) (\d+) (\d+):(\d+):(\d+) [+|-]\d+ (\d+)/) {
my $date = timegm($5,$4,$3,$2,$mon2num{$1},$6);
$diff = time()-$date;
}
$kernel->yield('server_reply',317,$target,$diff,'seconds idle');
my $all_chans = '';
foreach my $chan (keys %{$heap->{'channels'}}) {
if (exists $heap->{'channels'}->{$chan}->{'names'}->{$friend->{'screen_name'}}) {
$all_chans .= $heap->{'channels'}->{$chan}->{'names'}->{$friend->{'screen_name'}}."$chan ";
}
}
if ($all_chans ne '') {
$kernel->yield('server_reply',319,$target,$all_chans);
}
}
$kernel->yield('server_reply',318,$target,'End of /WHOIS list');
}
sub irc_stats {
my ($kernel, $heap, $data) = @_[KERNEL, HEAP, ARG0];
my $key = lc($data->{'params'}[0]);
my $val = $data->{'params'}[1];
$key = '--' if (!$key || $key eq 'm');
if ($key eq '--') {
$kernel->yield('server_reply',212,$key,"Current config settings:");
foreach my $k (sort keys %{$heap->{'config'}}) {
$kernel->yield('server_reply',212,$key," $k: ".$heap->{'config'}->{$k});
}
$kernel->yield('server_reply',212,$key,"Use '/stats <key> <value>' to change a setting.");
$kernel->yield('server_reply',212,$key,"Example: /stats join_silent 1");
} elsif ($key =~ m/pin/i) {
$kernel->yield('oauth_pin_entry',$val);
return;
} else {
if (exists $heap->{'config'}->{$key}) {