/
MSN.pm
1448 lines (1240 loc) · 53.2 KB
/
MSN.pm
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
package AnyEvent::MSN 0.001;
{
use lib '../../lib';
use 5.012;
use Moose;
use Moose::Util::TypeConstraints;
use AnyEvent qw[];
use AnyEvent::Handle qw[];
use AnyEvent::HTTP qw[];
use Try::Tiny;
use XML::Twig;
use AnyEvent::MSN::Protocol;
use MIME::Base64 qw[];
#
our $DEBUG = 0;
sub DEBUG {$DEBUG}
# XXX - During dev only
#use Data::Dump;
sub DEMOLISH {
my $s = shift;
$s->handle->destroy if $s->_has_handle && $s->handle;
$s->_clear_soap_requests;
}
# Basic connection info
has host => (is => 'ro',
writer => '_set_host',
isa => 'Str',
default => 'messenger.hotmail.com'
);
has port => (is => 'ro',
writer => '_set_port',
isa => 'Int',
default => 1863
);
# Authentication info from user
has passport => (
is => 'ro',
isa => subtype(
as 'Str' => where {
my $atom = qr{[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+};
my $dot_atom = qr{$atom(?:\.$atom)*};
my $quoted = qr{"(?:\\[^\r\n]|[^\\"])*"};
my $local = qr{(?:$dot_atom|$quoted)};
my $quotedpair = qr{\\[\x00-\x09\x0B-\x0c\x0e-\x7e]};
my $domain_lit =
qr{\[(?:$quotedpair|[\x21-\x5a\x5e-\x7e])*\]};
my $domain = qr{(?:$dot_atom|$domain_lit)};
my $addr_spec = qr{$local\@$domain};
$_ =~ $addr_spec;
} => message {
'An MSN Passport looks like an email address: you@hotmail.com';
}
),
required => 1,
handles => {
username => sub { shift->passport =~ m[^(.+)\@.+$]; $1 },
userhost => sub { shift->passport =~ m[^.+\@(.+)$]; $1 }
}
);
has password => (is => 'ro', isa => 'Str', required => 1);
# User defined extras
has [qw[friendlyname personalmessage]] =>
(is => 'ro', isa => 'Str', default => '');
has status => (
is => 'ro',
isa => enum([qw[NLN FLN BSY IDL BRB AWY PHN LUN]]),
default => 'NLN',
writer => 'set_status' # exposed publicly
);
# Client info for MSNP21
has protocol_version => (
is => 'ro',
isa => subtype(
as 'Str' => where {m[^(?:MSNP\d+\s*)+$]} => message {
'Protocol versions look like: MSNP18 MSNP21';
}
),
writer => '_set_protocol_version',
clearer => '_reset_protocol_version',
default => 'MSNP21',
lazy => 1
);
map { has $_->[0] => (is => 'ro', isa => 'Str', default => $_->[1]) }
[qw[product_id PROD0120PW!CCV9@]],
[qw[product_key C1BX{V4W}Q3*10SM]],
[qw[locale_id 0x0409]],
[qw[os_type winnt]],
[qw[os_ver 6.1.1]],
[qw[arch i386]],
[qw[client_name MSNMSGR]],
[qw[client_version 15.4.3508.1109]],
[qw[client_string MSNMSGR]];
has guid => (
is => 'ro',
=> isa => subtype(
as 'Str' => where {
my $hex = qr[[\da-f]];
m[{$hex{8}(?:-$hex{4}){3}-$hex{12}}$];
} => message {
'Malformed GUID. Should look like: {12345678-abcd-1234-abcd-123456789abc}';
}
),
builder => '_build_guid'
);
sub _build_guid {
state $r //= sub {
join '', map { ('a' .. 'f', 0 .. 9)[rand 15] } 1 .. shift;
};
sprintf '{%8s-%4s-%4s-%4s-%12s}', $r->(8), $r->(4), $r->(4), $r->(4),
$r->(12);
}
has location =>
(is => 'ro', isa => 'Str', default => 'Perl/AnyEvent::MSN');
# Internals
has handle => (
is => 'ro',
isa => 'Object',
# weak_ref => 1,
predicate => '_has_handle',
writer => '_set_handle',
clearer => '_reset_handle',
handles => {
send => sub {
my $s = shift;
$s->handle->push_write('AnyEvent::MSN::Protocol' => @_)
if $s->_has_handle; # XXX - Else mention it...
}
}
);
has tid => (is => 'ro',
isa => 'Int',
lazy => 1,
clearer => '_reset_tid',
builder => '_build_tid',
traits => ['Counter'],
handles => {'_inc_tid' => 'inc'}
);
sub _build_tid {0}
after tid => sub { shift->_inc_tid }; # Auto inc
has ping_timer => (is => 'ro',
isa => 'ArrayRef', # AE::timer
writer => '_set_ping_timer'
);
# Server configuration
has policies => (
is => 'bare',
isa => 'HashRef',
clearer => '_reset_policies',
writer => '_set_policies',
traits => ['Hash'],
handles => {_add_policy => 'set',
_del_policy => 'delete',
policy => 'get',
policies => 'kv' # XXX - Really?
}
);
# SOAP
has SSOsites => (
is => 'ro', # Single Sign On
isa => 'ArrayRef[ArrayRef]',
traits => ['Array'],
default => sub {
[['http://Passport.NET/tb', ''],
['messengerclear.live.com', 'MBI_KEY_OLD'],
['messenger.msn.com', '?id=507'],
['messengersecure.live.com', 'MBI_SSL'],
['contacts.msn.com', 'MBI'],
['storage.msn.com', 'MBI'],
['sup.live.com', 'MBI']
];
}
);
has auth_tokens => (is => 'bare',
isa => 'HashRef',
clearer => '_reset_auth_tokens',
writer => '_set_auth_tokens',
traits => ['Hash'],
handles => {_add_auth_token => 'set',
_del_auth_token => 'delete',
auth_token => 'get',
auth_tokens => 'kv'
}
);
has contacts => (is => 'ro',
isa => 'HashRef',
clearer => '_reset_contacts',
writer => '_set_contacts',
traits => ['Hash'],
);
# Simple callbacks
has 'on_' . $_ => (
traits => ['Code'],
is => 'ro',
isa => 'CodeRef',
default => sub {
sub {1}
},
handles => {'trigger_' . $_ => 'execute_method'},
)
for qw[
im nudge
error fatal_error connect
addressbook_update
buddylist_update
user_notification
];
has connected => (
is => 'rw',
isa => 'Bool',
traits => ['Bool'],
default => 0,
handles => {_set_connected => 'set', _unset_connected => 'unset'}
);
# Auto connect
sub BUILD {
my ($s, $p) = @_;
return if $p->{no_autoconnect};
$s->connect;
}
sub connect {
my ($s, $r) = @_;
$r = " $r" if length $r;
$s->_unset_connected;
$s->_set_handle(
AnyEvent::Handle->new(
connect => [$s->host, $s->port],
on_connect => sub {
# Get ready to read data from server
$s->handle->push_read(
'AnyEvent::MSN::Protocol' => sub {
my ($cmd, $tid, @data) = @_;
my $method =
$s->can('_handle_packet_' . lc($cmd));
$method ||= sub {
$s->trigger_error(
'Unhandled command type: ' . $cmd,
0);
};
if ($cmd =~ m[^(?:GCF|MSG|NFY|NOT|SDG|UBX)$])
{ # payload types
$s->handle->unshift_read(
chunk => $data[-1] // $tid, # GFC:0, MSG:2
sub {
my ($_h, $_c) = @_;
$s->$method(
$tid, @data,
$cmd =~ m[GCF]
? $s->_parse_xml($_c)
: $cmd =~ m[(?:MSG|NFY|SDG)]
? AnyEvent::MSN::Protocol::__parse_msn_headers(
$_c)
: $_c
);
}
);
}
elsif ($cmd =~ m[^\d+$]) { # Error!
$s->trigger_error(
AnyEvent::MSN::Protocol::err2str(
$cmd, @data
)
);
}
else {
$s->$method($tid, @data);
}
}
);
# Send version negotiation and basic client info
$s->send('VER %d %s CVR0', $s->tid, $s->protocol_version);
$s->send('CVR %d %s %s %s %s %s %s %s %s%s',
$s->tid,
$s->locale_id,
$s->os_type,
$s->os_ver,
$s->arch,
$s->client_name,
$s->client_version,
$s->client_string,
$s->passport,
($r // ' 0')
);
# Schedule first PNG in two mins
$s->_set_ping_timer(AE::timer 120,
180, sub { $s->send('PNG') });
},
on_connect_error => sub { $s->trigger_fatal_error(shift) },
on_error => sub {
my $h = shift;
$s->trigger_fatal_error(reverse @_);
$h->destroy;
},
on_eof => sub {
$_[0]->destroy;
$s->cleanup('connection closed');
}
)
);
}
# Commands from notification server
sub _handle_packet_adl {
my $s = shift;
# ACK for outgoing ADL
# $s->send('BLP %d AL', $s->tid);
}
sub _handle_packet_chl { # Official client challenge
my ($s, $tid, @data) = @_;
my $data =
AnyEvent::MSN::Protocol::CreateQRYHash($data[0], $s->product_id,
$s->product_key);
$s->send("QRY %d %s %d\r\n%s",
$s->tid, $s->product_id, length($data), $data);
}
sub _handle_packet_cvr { # Client version recommendation
my ($s, $tid, $r, $min_a, $min_b, $url_dl, $url_info) = @_;
# We don't do anything with this yet but...
# The first parameter is a recommended version of
# the client for you to use, or "1.0.0000" if your
# client information is not recognised.
# The second parameter is identical to the first.
# The third parameter is the minimum version of the
# client it's safe for you to use, or the current
# version if your client information is not
# recognised.
# The fourth parameter is a URL you can download the
# recommended version of the client from.
# The fifth parameter is a URL the user can go to to
# get more information about the client.
$s->send('USR %d SSO I %s', $s->tid, $s->passport);
}
sub _handle_packet_gcf { # Get config
my ($s, $tid, $len, $r) = @_;
if ($tid == 0) { # probably Policy list
$s->_set_policies($r->{Policy});
#for (@{$s->policy('SHIELDS')->{config}{block}{regexp}{imtext}}) {
# my $regex = MIME::Base64::decode_base64($_);
# warn 'Blocking ' . qr[$regex];
#}
}
else {
...;
}
}
sub _handle_packet_msg {
my ($s, $from, $about, $len, $head, $body) = @_;
given ($head->{'Content-Type'}) {
when (m[text/x-msmsgsprofile]) {
#
# http://msnpiki.msnfanatic.com/index.php/MSNP8:Messages#Profile_Messages
# My profile message. Expect no body.
}
when (m[text/x-msmsgsinitialmdatanotification]) { # Expect no body
}
when (m[text/x-msmsgsoimnotification]) {
# Offline Message Waiting.
# Expect no body
# XXX - How do I request it?
}
when (m[text/x-msmsgsactivemailnotification]) {
warn 'You\'ve got mail!/aol'
}
when (m[text/x-msmsgsinitialmdatanotification]) {
warn 'You\'ve got mail!/aol'
}
default { $s->trigger_error('Unknown message type: ' . $_) }
}
}
sub _handle_packet_nfy {
my ($s, $type, $len, $headers, $data) = @_;
use Data::Dump;
ddx $type, $len, $headers, $data;
ddx $s->_parse_xml($data);
given ($type) {
when ('PUT') {
my $xml = $s->_parse_xml($data);
if ((!defined $headers->{By})
&& $headers->{From} eq '1:' . $s->passport)
{ # Without guid
$s->trigger_connect;
$s->_set_connected();
$s->set_status($s->status); # XXX - Yeah, this is odd
}
else {
$s->trigger_user_notification($headers, $xml);
}
#
}
when ('DEL') {
# Remove from list
}
default {...}
}
}
sub _handle_packet_not { my $s = shift; }
sub _handle_packet_put {
}
sub _handle_packet_qng {
my ($s, $next) = @_;
# PONG in reply to our PNG
$s->_set_ping_timer(AE::timer $next, $next, sub { $s->send('PNG') });
}
sub _handle_packet_qry {
my ($s, $tid) = @_;
#
my $token =
$s->auth_token('contacts.msn.com')
->{'wst:RequestedSecurityToken'}{'wsse:BinarySecurityToken'}
{content};
$token =~ s/&/&/sg;
$token =~ s/</</sg;
$token =~ s/>/>/sg;
$token =~ s/"/"/sg;
# Reply to good challenge. Expect no body.
$s->soap_request(
'https://contacts.msn.com:443/abservice/SharingService.asmx',
{ 'content-type' => 'text/xml; charset=utf-8',
SOAPAction =>
'"http://www.msn.com/webservices/AddressBook/FindMembership"'
},
sprintf(<<'XML', $token),
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
<ApplicationId>CFE80F9D-180F-4399-82AB-413F33A1FA11</ApplicationId>
<IsMigration>false</IsMigration>
<PartnerScenario>Initial</PartnerScenario>
</ABApplicationHeader>
<ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
<TicketToken>%s</TicketToken>
<ManagedGroupRequest>false</ManagedGroupRequest>
</ABAuthHeader>
</soap:Header>
<soap:Body>
<FindMembership xmlns="http://www.msn.com/webservices/AddressBook">
<ServiceFilter>
<Types>
<Space></Space>
<SocialNetwork></SocialNetwork>
<Profile></Profile>
<Invitation></Invitation>
<Messenger></Messenger>
</Types>
</ServiceFilter>
</FindMembership>
</soap:Body>
</soap:Envelope>
XML
sub {
my $contacts = shift;
# XXX - Do something with these contacts
#...
}
);
$s->soap_request(
'https://contacts.msn.com/abservice/abservice.asmx',
{ 'content-type' => 'text/xml; charset=utf-8',
'SOAPAction' =>
'"http://www.msn.com/webservices/AddressBook/ABFindContactsPaged"'
},
sprintf(<<'XML', $token),
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
<ApplicationId>3794391A-4816-4BAC-B34B-6EC7FB5046C6</ApplicationId>
<CacheKey>14r2;Y+G87laDsL3ATl8gJ3C4pPjoMLk5J/tyZUSb1cwTnKI1GlRcRHu65X3d3uqDPuH2pkfTOntU7zMUk9k2dFQwYcre4UXElvfdhjc5KYfm8oZftprkw69TgDuQLTZg4mMoayTnE388tJx4Z8Cx0iLxP/HvZHwsVnrC9RQ6k4aJ8wM=</CacheKey>
<IsMigration>false</IsMigration>
<PartnerScenario>Initial</PartnerScenario>
</ABApplicationHeader>
<ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
<TicketToken>%s</TicketToken>
<ManagedGroupRequest>false</ManagedGroupRequest>
</ABAuthHeader>
</soap:Header>
<soap:Body>
<ABFindall xmlns="http://www.msn.com/webservices/AddressBook">
<abID>00000000-0000-0000-0000-000000000000</abID>
</ABFindall>
<ABFindContactsPaged xmlns="http://www.msn.com/webservices/AddressBook">
<extendedContent>AB AllGroups CircleResult</extendedContent>
<abView>MessengerClient8</abView>
<filterOptions>
<DeltasOnly>false</DeltasOnly>
<ContactFilter>
<IncludeShellContacts>true</IncludeShellContacts>
<IncludeHiddenContacts>true</IncludeHiddenContacts>
</ContactFilter>
<LastChanged>0001-01-01T00:00:00.00-08:00</LastChanged>
</filterOptions>
<pageContext>
<PageSize>1500</PageSize>
<Direction>Forward</Direction>
</pageContext>
</ABFindContactsPaged>
</soap:Body>
</soap:Envelope>
XML
sub {
my $contacts = shift;
# XXX - Do something with these contacts
$s->_set_contacts($contacts);
my $ticket = __html_unescape(
$s->contacts->{'soap:Body'}{'ABFindContactsPagedResponse'}
{'ABFindContactsPagedResult'}{'CircleResult'}
{'CircleTicket'});
$s->send('USR %d SHA A %s',
$s->tid, MIME::Base64::encode_base64($ticket, ''));
#
my $x = # XML modules get it wrong if we only have 1 buddy
$s->contacts->{'soap:Body'}{'ABFindContactsPagedResponse'}
{'ABFindContactsPagedResult'}{'Contacts'}{'Contact'};
$x = [$x] if ref $x ne 'ARRAY';
$s->add_buddy(map { $_->{contactInfo}{passportName} } @$x);
}
);
}
sub _handle_packet_rml {
my ($s, $tid, $ok) = @_;
use Data::Dump;
ddx \@_;
...;
}
sub _handle_packet_sbs {
my $s = shift;
# No one seems to know what this is. Official client ignores it?
}
sub _handle_packet_sdg {
my ($s, $tid, $size, $head, $body) = @_;
#ddx [$head, $body];
given ($head->{'Message-Type'}) {
when ('Text') {
given ($head->{'Service-Channel'}) {
$s->trigger_im($head, $body) when 'IM/Online';
$s->trigger_im($head, $body) when undef;
warn 'Offline Msg!' when 'IM/Offline';
default {
warn 'unknown IM!!!!!'
}
}
}
$s->trigger_nudge($head) when 'Nudge';
when ('Wink') { warn 'Wink' }
when ('CustomEmoticon') { warn 'Custom Emoticon' }
when ('Control/Typing') { warn 'Typing!' }
when ('Data') {
my ($header, $packet, $footer);
if ($head->{To} !~ m[{.+}]) {
# 0 1 2 3 4 5
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | SID | ID | Data Offset | Total Size |Length | Flags | AckID |AckUID | Ack Data Size |DATA....
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# The 48-byte binary header consists of 6 DWORDs and 3 QWORDS, which are all in little endian (little end first) order, where a DWORD is a 32-bit (4 byte) unsigned integer and QWORD is 64 bits (8 bytes).
#
# 1 0 DWORD SessionID The SessionID, which is zero when the Clients are negotiating about the session.
# 2 4 DWORD Identifier The first message you receive from the other client is the BaseIndentifier, the other messages contains a number near the BaseIdentifier.
# 3 8 QWORD Data offset Explained under Splitting big messages. Most often the messages are not split, and this value is 0.
# 4 16 QWORD Total data size Case 1: The byte size of all data sent between the header and footer of all of the message parts. This is the same independent of how many pieces the message is split in. Case 2: If this is an acknowledgement, this field is a copy of the same field in the message acknowledged. Sending acknowledgements
# 5 24 DWORD Message length The byte size of the data between the header and footer of this particular message.
# 6 28 DWORD Flag Identifies the message type. See the flags section
# 7 32 DWORD Acknowledged identifier In case the message is an acknowledgement, this is a copy of the Identifier of the acknowledged message. Else this is some random generated number.
# 8 36 DWORD Acknowledged unique ID In case the message is an acknowledgement, this is a copy of the previous field of the acknowledged message. Else this is 0.
# 9 40 QWORD Acknowledged data size In case the message is an acknowledgement, this is a copy of the Total data size field of the acknowledged message. Else this is 0.
sub _quad {
state $little//= unpack 'C', pack 'S', 1;
my $str = shift;
my $big;
if (!eval { $big = unpack('Q', $str); 1; }) {
my ($lo, $hi) = unpack 'LL', $str;
($hi, $lo) = ($lo, $hi) if !$little;
$big = $lo + $hi * (1 + ~0);
if ($big + 1 == $big) {
warn 'A-pprox-i-mate!';
}
}
return $big;
}
(my ($sessionid, $identifier, $offset,
$total_size, $msg_len, $flag,
$ack_id, $ack_uid, $ack_data_size
),
$packet
) = unpack 'NNa8a8NNNNa8a*', $body;
($packet, $footer) =
unpack 'a' . (_quad($total_size)) . ' a', $packet;
$header = {sessionid => $sessionid,
identifier => $identifier,
offset => _quad($offset),
total_size => _quad($total_size),
msg_len => $msg_len,
flag => $flag,
ack_id => $ack_id,
ack_uid => $ack_uid,
ack_data_size => _quad($ack_data_size)
};
}
else {
# 0 1 2 3
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |L|O|Len|Base ID|if L>8 then TLVs = read(L - 8) else skip ....
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | if Len > 0 then Payload = (DH and D) else skip ....
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# For all of them - (DWORD is a 32-bit, 4 byte, unsigned integer and QWORD is 64 bits, 8 bytes.)
#
# 1 BYTE HL Length of header.
# 2 BYTE OP Operation code. 0: None, 2: Ack, 3: Init session.
# 3 WORD ML Message length without header length. (but included the header's message length)
# 4 DWORD BaseID Initially random (?) To get the next one add the payload length.
# TLVs BYTE[HL-8] TLV Data TLV list consists of TLV-encoded pairs (type, length, value). A whole TLV list is padded with zeros to fit 4-byte boundary. TLVs: T=0x1(1) L=0xc(12): IPv6 address of sender/receiver. T=0x2(2) L=0x4(4): ACK identifier.
# DH DHL Data Header
# BYTE DHL: Data header length
# BYTE TFCombination: 0x1=First, 0x4=Msn object (display picture, emoticon etc), 0x6=File transfer
# WORD PackageNumber: Package number
# DWORD SessionID: Session Identifier
# BYTE[DHL-8] Data packets TLVs: if (DHL>8) then read bytes(DHL - 8). T=0x1(1) L=0x8(8): Data remaining.
# D ML-DHL Data Packet SLP messsage or data packet
# F DWORD Footer The footer.
#ddx $body;
my ($hl, $op, $ml, $baseid, $etc) = unpack 'CCnNa*',
$body;
warn sprintf 'HL = %d', $hl;
warn sprintf 'OP = %d (%s)', $op,
( $op == 0 ? 'None'
: $op == 2 ? 'Ack'
: $op == 3 ? 'Init'
: 'BROKEN'
);
warn sprintf 'ML = %d', $ml;
warn sprintf 'BaseID = %s', $baseid;
#
my $_tlv_len = $hl - 8;
$_tlv_len += $_tlv_len % 8;
my ($tlv, $moar) = unpack "a$_tlv_len a*", $etc;
warn sprintf 'TLV = %s', $tlv;
sub _tlv {
my ($t, $v, $m) = unpack 'CC/a', shift;
{ shift // (), t => $t, v => $v, $m ? _tlv($m) : () }
}
my ($dhlen, $tf_combo, $pac, $ses, $XXX) =
unpack 'CCnNa*', $moar;
warn length($moar);
($packet, $footer) = unpack 'a' . ($ml - $dhlen) . 'a*',
$XXX
if $XXX;
$header = {tlv => ($tlv ? _tlv($tlv) : ()),
header_len => $hl,
operation => $op,
( $op == 0 ? 'None'
: $op == 2 ? 'Ack'
: $op == 3 ? 'Init'
: 'BROKEN'
),
base_id => $baseid,
msg_len => $ml
};
#
}
#ddx $header;
#ddx($packet =~ m[^(.+?)\r\n(.+)\r\n\r\n(.)$]s);
my ($p2p_action, $p2p_head, $p2p_body) =
($packet =~ m[^(.+?)\r\n(.+)\r\n\r\n(.)$]s);
#ddx $head, $p2p_action,
# AnyEvent::MSN::Protocol::__parse_msn_headers($p2p_head),
# $p2p_body;
#warn 'Data'
# XXX - trigger a callback of some sort
}
when ('Signal/P2P') { warn 'P2P' }
when ('Signal/ForceAbchSync') { }
when ('Signal/CloseIMWindow') { }
when ('Signal/MarkIMWindowRead') { }
when ('Signal/Turn') { };
when ('Signal/AudioMeta') { }
when ('Signal/AudioTunnel') { }
default {...}
}
}
sub _handle_packet_usr {
my ($s, $tid, $subtype, $_s, $policy, $nonce) = @_;
if ($subtype eq 'OK') {
# Sent after we send ADL command. Lastcommand in the logon?
}
elsif ($subtype eq 'SSO') {
my $x = 1;
my @tokens = map {
sprintf <<'TOKEN', $x++, $_->[0], $_->[1] } @{$s->SSOsites};
<wst:RequestSecurityToken Id="RST%d">
<wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
<wsp:AppliesTo>
<wsa:EndpointReference>
<wsa:Address>%s</wsa:Address>
</wsa:EndpointReference>
</wsp:AppliesTo>
<wsse:PolicyReference URI="%s"></wsse:PolicyReference>
</wst:RequestSecurityToken>
TOKEN
$s->soap_request(
($s->passport =~ m[\@msn.com$]i
? 'https://msnia.login.live.com/pp550/RST.srf'
: 'https://login.live.com/RST.srf'
),
{}, # headers
sprintf(<<'XML', $s->password, $s->passport, join '', @tokens),
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsse="http://schemas.xmlsoap.org/ws/2003/06/secext" xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" xmlns:wsp="http://schemas.xmlsoap.org/ws/2002/12/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/03/addressing" xmlns:wssc="http://schemas.xmlsoap.org/ws/2004/04/sc" xmlns:wst="http://schemas.xmlsoap.org/ws/2004/04/trust">
<Header>
<wsse:Security>
<wsse:UsernameToken Id="user">
<wsse:Password>%s</wsse:Password>
<wsse:Username>%s</wsse:Username>
</wsse:UsernameToken>
</wsse:Security>
<ps:AuthInfo Id="PPAuthInfo" xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL">
<ps:Cookies></ps:Cookies>
<ps:UIVersion>1</ps:UIVersion>
<ps:HostingApp>{7108E71A-9926-4FCB-BCC9-9A9D3F32E423}</ps:HostingApp>
<ps:BinaryVersion>4</ps:BinaryVersion>
<ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams>
</ps:AuthInfo>
</Header>
<Body>
<ps:RequestMultipleSecurityTokens Id="RSTS" xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL">
%s </ps:RequestMultipleSecurityTokens>
</Body>
</Envelope>
XML
sub {
my $d = shift;
for my $token (
@{ $d->{'S:Body'}{
'wst:RequestSecurityTokenResponseCollection'}
{'wst:RequestSecurityTokenResponse'}
}
)
{ $s->_add_auth_token(
$token->{'wsp:AppliesTo'}{'wsa:EndpointReference'}
{'wsa:Address'},
$token
);
}
#
if ($policy =~ m[MBI]) {
my $token = $s->auth_token('messengerclear.live.com')
; # or http://Passport.NET/tb
my $token_ = __html_escape(
$token->{'wst:RequestedSecurityToken'}
{'wsse:BinarySecurityToken'}{'content'});
$s->send('USR %d SSO S %s %s %s',
$s->tid,
$token->{'wst:RequestedSecurityToken'}
{'wsse:BinarySecurityToken'}{'content'},
AnyEvent::MSN::Protocol::SSO(
$nonce,
$token->{'wst:RequestedProofToken'}
{'wst:BinarySecret'}
),
$s->guid
);
}
elsif ($policy =~ m[^\?]) {
...;
}
}
);
}
elsif ($subtype eq 'OK') {
# XXX - logged in okay. What now?
}
else {
...;
}
}
sub _handle_packet_ubx { # Buddy has changed something
my ($s, $passport, $len, $payload) = @_;
my $xml = $s->_parse_xml($payload);
if ($len == 0 && $passport eq '1:' . $s->passport) {
}
else {
#ddx $xml;
my ($user) = ($passport =~ m[:(.+)$]);
$s->_add_contact($user, $xml);
}
}
sub _handle_packet_uux { # ACK for UUX
}
sub _handle_packet_ver { # Negotiated protocol version
my ($s, $tid, $r) = @_;
$s->_set_protocol_version($r);
}
sub _handle_packet_xfr { # Transver to another switchboard
my $s = shift;
my ($tid, $type, $addr, $u, $d, $redirect) = @_;
$s->send('OUT');
$s->handle->destroy;
my ($host, $port) = ($addr =~ m[^(.+):(\d+)$]);
$s->_set_host($host);
$s->_set_port($port);
$s->connect($redirect);
}
# SOAP client
has soap_requests => (isa => 'HashRef[AnyEvent::Util::guard]',
traits => ['Hash'],
handles => {_add_soap_request => 'set',
_del_soap_request => 'delete',
_clear_soap_requests => 'clear'
}
);
sub soap_request {
my ($s, $uri, $headers, $content, $cb) = @_;
my %headers = ('user-agent' => 'MSNPM 1.0',
'content-type' =>
'application/soap+xml; charset=utf-8; action=""',
'Expect' => '100-continue',
'connection' => 'Keep-Alive'
);
@headers{keys %$headers} = values %$headers;
$s->_add_soap_request(
$uri,
AnyEvent::HTTP::http_request(
POST => $uri,
headers => \%headers,
timeout => 15,
persistent => 1,
body => $content,
sub {
my ($body, $hdr) = @_;
my $xml = $s->_parse_xml($body);
$s->_del_soap_request($uri);
return $cb->($xml)
if $hdr->{Status} =~ /^2/
&& !defined $xml->{'S:Fault'};
#ddx $hdr;
$s->trigger_fatal_error(
$xml->{'S:Fault'}{'soap:Reason'}{'soap:Text'}
{'content'} // $xml->{'S:Fault'}{'faultstring'}
// $hdr->{Reason}
);
}
)
);
}
# Methods exposed publicly
sub disconnect { # cleanly disconnect from switchboard
my $s = shift;
$s->send('OUT');
$s->handle->on_drain(
sub {
$s->handle->destroy;
}
);
}
sub send_message {
my ($s, $to, $msg, $format) = @_;
$to = '1:' . $to if $to !~ m[^\d+:];
$format //= 'FN=Segoe%20UI; EF=; CO=0; CS=1; PF=0';
# FN: Font name (url safe)
# EF: String containing...
# - B for Bold
# - U for Underline
# - I for Italics
# - S for Strikethrough
# CO: Color (hex without #)
my $data =
sprintf
qq[Routing: 1.0\r\nTo: %s\r\nFrom: 1:%s;epid=%s\r\n\r\nReliability: 1.0\r\n\r\nMessaging: 2.0\r\nMessage-Type: Text\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Length: %d\r\nX-MMS-IM-Format: %s\r\n\r\n%s],
$to, $s->passport, $s->guid, length($msg), $format, $msg;
$s->send(qq'SDG 0 %d\r\n%s', length($data), $data);
}
sub nudge {
my ($s, $to) = @_;
$to = '1:' . $to if $to !~ m[^\d+:];
my $data =
sprintf
qq[Routing: 1.0\r\nTo: %s\r\nFrom: 1:%s;epid=%s\r\n\r\nReliability: 1.0\r\n\r\nMessaging: 2.0\r\nMessage-Type: Nudge\r\nService-Channel: IM/Online\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Length: 0\r\n\r\n],
$to, $s->passport, $s->guid;
$s->send("SDG 0 %d\r\n%s", length($data), $data);
}
sub add_buddy {
my $s = shift;
my %contacts;
for my $contact (@_) {
my ($user, $domain) = split /\@/, $contact, 2;
push @{$contacts{$domain}}, $user;
}
my $data = sprintf '<ml%s>%s</ml>', ($s->connected ? '' : ' l="1"'),
join '', map {
sprintf '<d n="%s">%s</d>', $_, join '', map {
sprintf '<c n="%s" t="1">%s</c>', $_, join '',
map {"<s l='3' n='$_' />"}
qw[IM PE PF]
} sort @{$contacts{$_}}
} sort keys %contacts;
my $tid = $s->tid;
$s->send("ADL %d %d\r\n%s", $tid, length($data), $data);
$tid;
}
sub remove_buddy {
my $s = shift;
my $data = sprintf <<'', reverse split '@', shift, 2;
<ml>
<d n="%s">
<c n="%s" t="1">
<s l="3" n="IM" />
<s l="3" n="PE" />
<s l="3" n="PF" />
</c>
</d>
</ml>
my $tid = $s->tid;
$s->send("RML %d %d\r\n%s", $tid, length($data), $data);
$tid;
}
after set_status => sub {
my ($s, $status) = @_;
my $body = sprintf '<user>' . '<s n="PE">
<UserTileLocation>0</UserTileLocation><FriendlyName>%s</FriendlyName><PSM>%s</PSM><RUM></RUM><RLT>0</RLT></s>'
. '<s n="IM"><Status>%s</Status><CurrentMedia></CurrentMedia></s>'
. '<sep n="PD"><ClientType>1</ClientType><EpName>%s</EpName><Idle>false</Idle><State>%s</State></sep>'
. '<sep n="PE" epid="%s"><VER>MSNMSGR:15.4.3508.1109</VER><TYP>1</TYP><Capabilities>2952790016:557056</Capabilities></sep>'
. '<sep n="IM"><Capabilities>2953838624:132096</Capabilities></sep>'
. '</user>', __html_escape($s->friendlyname),
__html_escape($s->personalmessage),
$status,
__html_escape($s->location), $status, $s->guid;
my $out =
sprintf
qq[To: 1:%s\r\nRouting: 1.0\r\nFrom: 1:%s;epid=%s\r\n\r\nStream: 1\r\nFlags: ACK\r\nReliability: 1.0\r\n\r\nContent-Length: %d\r\nContent-Type: application/user+xml\r\nPublication: 1.0\r\nUri: /user\r\n\r\n%s],