-
Notifications
You must be signed in to change notification settings - Fork 445
Expand file tree
/
Copy pathProtocolHandler.cs
More file actions
1329 lines (1255 loc) · 55.6 KB
/
ProtocolHandler.cs
File metadata and controls
1329 lines (1255 loc) · 55.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using DnsClient;
using MinecraftClient.Protocol.Handlers;
using MinecraftClient.Protocol.Handlers.Forge;
using MinecraftClient.Protocol.Session;
using MinecraftClient.Proxy;
using static MinecraftClient.Settings;
using static MinecraftClient.Settings.MainConfigHelper.MainConfig.GeneralConfig;
namespace MinecraftClient.Protocol
{
/// <summary>
/// Handle login, session, server ping and provide a protocol handler for interacting with a minecraft server.
/// </summary>
/// <remarks>
/// Typical update steps for marking a new Minecraft version as supported:
/// - Add protocol ID in GetProtocolHandler()
/// - Add 1.X.X case in MCVer2ProtocolVersion()
/// </remarks>
public static class ProtocolHandler
{
/// <summary>
/// Perform a DNS lookup for a Minecraft Service using the specified domain name
/// </summary>
/// <param name="domain">Input domain name, updated with target host if any, else left untouched</param>
/// <param name="port">Updated with target port if any, else left untouched</param>
/// <returns>TRUE if a Minecraft Service was found.</returns>
public static bool MinecraftServiceLookup(ref string domain, ref ushort port)
{
bool foundService = false;
string domainVal = domain;
ushort portVal = port;
if (!String.IsNullOrEmpty(domain) && domain.Any(c => char.IsLetter(c)))
{
AutoTimeout.Perform(() =>
{
try
{
ConsoleIO.WriteLine(string.Format(Translations.mcc_resolve, domainVal));
var lookupClient = new LookupClient();
var response =
lookupClient.Query(new DnsQuestion($"_minecraft._tcp.{domainVal}", QueryType.SRV));
if (response.HasError != true && response.Answers.SrvRecords().Any())
{
//Order SRV records by priority and weight, then randomly
var result = response.Answers.SrvRecords()
.OrderBy(record => record.Priority)
.ThenByDescending(record => record.Weight)
.ThenBy(record => Guid.NewGuid())
.First();
string target = result.Target.Value.Trim('.');
ConsoleIO.WriteLineFormatted("§8" + string.Format(Translations.mcc_found, target,
result.Port, domainVal));
domainVal = target;
portVal = result.Port;
foundService = true;
}
}
catch (Exception e)
{
ConsoleIO.WriteLineFormatted("§8" + string.Format(Translations.mcc_not_found, domainVal,
e.GetType().FullName, e.Message));
}
},
TimeSpan.FromSeconds(Config.Main.Advanced.ResolveSrvRecords ==
MainConfigHelper.MainConfig.AdvancedConfig.ResolveSrvRecordType.fast
? 10
: 30));
}
domain = domainVal;
port = portVal;
return foundService;
}
/// <summary>
/// Retrieve information about a Minecraft server
/// </summary>
/// <param name="serverIP">Server IP to ping</param>
/// <param name="serverPort">Server Port to ping</param>
/// <param name="protocolversion">Will contain protocol version, if ping successful</param>
/// <returns>TRUE if ping was successful</returns>
public static bool GetServerInfo(string serverIP, ushort serverPort, ref int protocolversion,
ref ForgeInfo? forgeInfo)
{
bool success = false;
int protocolversionTmp = 0;
ForgeInfo? forgeInfoTmp = null;
if (AutoTimeout.Perform(() =>
{
try
{
if (Protocol18Handler.DoPing(serverIP, serverPort, ref protocolversionTmp, ref forgeInfoTmp)
|| Protocol16Handler.DoPing(serverIP, serverPort, ref protocolversionTmp))
{
success = true;
}
else
ConsoleIO.WriteLineFormatted("§8" + Translations.error_unexpect_response,
acceptnewlines: true);
}
catch (Exception e)
{
ConsoleIO.WriteLineFormatted(string.Format("§8{0}: {1}", e.GetType().FullName, e.Message));
}
},
TimeSpan.FromSeconds(Config.Main.Advanced.ResolveSrvRecords ==
MainConfigHelper.MainConfig.AdvancedConfig.ResolveSrvRecordType.fast
? 10
: 30)))
{
if (protocolversion != 0 && protocolversion != protocolversionTmp)
ConsoleIO.WriteLineFormatted("§8" + Translations.error_version_different, acceptnewlines: true);
if (protocolversion == 0 && protocolversionTmp <= 1)
ConsoleIO.WriteLineFormatted("§8" + Translations.error_no_version_report, acceptnewlines: true);
if (protocolversion == 0)
protocolversion = protocolversionTmp;
forgeInfo = forgeInfoTmp;
return success;
}
else
{
ConsoleIO.WriteLineFormatted("§8" + Translations.error_connection_timeout, acceptnewlines: true);
return false;
}
}
/// <summary>
/// Get a protocol handler for the specified Minecraft version
/// </summary>
/// <param name="client">Tcp Client connected to the server</param>
/// <param name="protocolVersion">Protocol version to handle</param>
/// <param name="forgeInfo">Forge info</param>
/// <param name="handler">Handler with the appropriate callbacks</param>
/// <returns></returns>
public static IMinecraftCom GetProtocolHandler(TcpClient client, int protocolVersion, ForgeInfo? forgeInfo,
IMinecraftComHandler handler)
{
int normalizedVersion = NormalizeSnapshotProtocol(protocolVersion);
int[] suppoertedVersionsProtocol16 = { 51, 60, 61, 72, 73, 74, 78 };
if (Array.IndexOf(suppoertedVersionsProtocol16, normalizedVersion) > -1)
return new Protocol16Handler(client, normalizedVersion, handler);
int[] suppoertedVersionsProtocol18 =
{
4, 5, 47, 107, 108, 109, 110, 210, 315, 316, 335, 338, 340, 393, 401, 404, 477, 480, 485, 490, 498, 573,
575, 578, 735, 736, 751, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768,
769, 770, 771, 772, 773, 774, 775
};
if (Array.IndexOf(suppoertedVersionsProtocol18, normalizedVersion) > -1)
return new Protocol18Handler(client, normalizedVersion, handler, forgeInfo, protocolVersion);
throw new NotSupportedException(string.Format(Translations.exception_version_unsupport, protocolVersion));
}
/// <summary>
/// Convert a human-readable Minecraft version number to network protocol version number
/// </summary>
/// <param name="MCVersion">The Minecraft version number</param>
/// <returns>The protocol version number or 0 if could not determine protocol version: error, unknown, not supported</returns>
public static int MCVer2ProtocolVersion(string mcVersion)
{
if (mcVersion.Contains('.'))
{
switch (mcVersion.Split(' ')[0].Trim())
{
case "1.0":
case "1.0.0":
case "1.0.1":
return 22;
case "1.1":
case "1.1.0":
return 23;
case "1.2":
case "1.2.0":
case "1.2.1":
case "1.2.2":
case "1.2.3":
return 28;
case "1.2.4":
case "1.2.5":
return 29;
case "1.3":
case "1.3.0":
case "1.3.1":
case "1.3.2":
return 39;
case "1.4":
case "1.4.0":
case "1.4.1":
case "1.4.2":
return 48; // 47 conflicts with 1.8
case "1.4.3":
return 48;
case "1.4.4":
case "1.4.5":
return 49;
case "1.4.6":
case "1.4.7":
return 51;
case "1.5":
case "1.5.0":
case "1.5.1":
return 60;
case "1.5.2":
return 61;
case "1.6":
case "1.6.0":
return 72;
case "1.6.1":
return 73;
case "1.6.2":
return 74;
case "1.6.3":
return 77;
case "1.6.4":
return 78;
case "1.7":
case "1.7.0":
case "1.7.1":
return 3;
case "1.7.2":
case "1.7.3":
case "1.7.4":
case "1.7.5":
return 4;
case "1.7.6":
case "1.7.7":
case "1.7.8":
case "1.7.9":
case "1.7.10":
return 5;
case "1.8":
case "1.8.0":
case "1.8.1":
case "1.8.2":
case "1.8.3":
case "1.8.4":
case "1.8.5":
case "1.8.6":
case "1.8.7":
case "1.8.8":
case "1.8.9":
return 47;
case "1.9":
case "1.9.0":
return 107;
case "1.9.1":
return 108;
case "1.9.2":
return 109;
case "1.9.3":
case "1.9.4":
return 110;
case "1.10":
case "1.10.0":
case "1.10.1":
case "1.10.2":
return 210;
case "1.11":
case "1.11.0":
return 315;
case "1.11.1":
case "1.11.2":
return 316;
case "1.12":
case "1.12.0":
return 335;
case "1.12.1":
return 338;
case "1.12.2":
return 340;
case "1.13":
case "1.13.0":
return 393;
case "1.13.1":
return 401;
case "1.13.2":
return 404;
case "1.14":
case "1.14.0":
return 477;
case "1.14.1":
return 480;
case "1.14.2":
return 485;
case "1.14.3":
return 490;
case "1.14.4":
return 498;
case "1.15":
case "1.15.0":
return 573;
case "1.15.1":
return 575;
case "1.15.2":
return 578;
case "1.16":
case "1.16.0":
return 735;
case "1.16.1":
return 736;
case "1.16.2":
return 751;
case "1.16.3":
return 753;
case "1.16.4":
case "1.16.5":
return 754;
case "1.17":
case "1.17.0":
return 755;
case "1.17.1":
return 756;
case "1.18":
case "1.18.0":
case "1.18.1":
return 757;
case "1.18.2":
return 758;
case "1.19":
case "1.19.0":
return 759;
case "1.19.1":
case "1.19.2":
return 760;
case "1.19.3":
return 761;
case "1.19.4":
return 762;
case "1.20":
case "1.20.1":
return 763;
case "1.20.2":
return 764;
case "1.20.3":
case "1.20.4":
return 765;
case "1.20.5":
case "1.20.6":
return 766;
case "1.21":
case "1.21.1":
return 767;
case "1.21.2":
return 768;
case "1.21.3":
return 768;
case "1.21.4":
return 769;
case "1.21.5":
return 770;
case "1.21.6":
return 771;
case "1.21.7":
case "1.21.8":
return 772;
case "1.21.9":
case "1.21.10":
return 773;
case "1.21.11":
return 774;
case "26.1":
return 775;
default:
return 0;
}
}
try
{
return int.Parse(mcVersion, NumberStyles.Any, CultureInfo.CurrentCulture);
}
catch
{
return 0;
}
}
/// <summary>
/// Convert a network protocol version number to human-readable Minecraft version number
/// </summary>
/// <remarks>Some Minecraft versions share the same protocol number. In that case, the lowest version for that protocol is returned.</remarks>
/// <param name="protocol">The Minecraft protocol version number</param>
/// <returns>The 1.X.X version number, or 0.0 if could not determine protocol version</returns>
public static string ProtocolVersion2MCVer(int protocol)
{
return protocol switch
{
22 => "1.0",
23 => "1.1",
28 => "1.2.3",
29 => "1.2.5",
39 => "1.3.2",
// case 47: return "1.4.2";
48 => "1.4.3",
49 => "1.4.5",
51 => "1.4.6",
60 => "1.5.1",
62 => "1.5.2",
72 => "1.6",
73 => "1.6.1",
3 => "1.7.1",
4 => "1.7.2",
5 => "1.7.6",
47 => "1.8",
107 => "1.9",
108 => "1.9.1",
109 => "1.9.2",
110 => "1.9.3",
210 => "1.10",
315 => "1.11",
316 => "1.11.1",
335 => "1.12",
338 => "1.12.1",
340 => "1.12.2",
393 => "1.13",
401 => "1.13.1",
404 => "1.13.2",
477 => "1.14",
480 => "1.14.1",
485 => "1.14.2",
490 => "1.14.3",
498 => "1.14.4",
573 => "1.15",
575 => "1.15.1",
578 => "1.15.2",
735 => "1.16",
736 => "1.16.1",
751 => "1.16.2",
753 => "1.16.3",
754 => "1.16.5",
755 => "1.17",
756 => "1.17.1",
757 => "1.18.1",
758 => "1.18.2",
759 => "1.19",
760 => "1.19.2",
761 => "1.19.3",
762 => "1.19.4",
763 => "1.20",
764 => "1.20.2",
765 => "1.20.4",
766 => "1.20.6",
767 => "1.21",
768 => "1.21.2",
769 => "1.21.4",
770 => "1.21.5",
771 => "1.21.6",
772 => "1.21.7",
773 => "1.21.9",
774 => "1.21.11",
775 => "26.1",
_ => "0.0"
};
}
/// <summary>
/// Normalize snapshot/pre-release protocol numbers (0x40000000 | data_version) to the
/// corresponding release protocol number. Unknown snapshot versions pass through unchanged.
/// </summary>
public static int NormalizeSnapshotProtocol(int protocol)
{
if ((protocol & 0x40000000) == 0)
return protocol;
return protocol switch
{
0x4000012E => 775, // 26.1-rc-2 → 26.1
_ => protocol
};
}
/// <summary>
/// Check if we can force-enable Forge support for a Minecraft version without using server Ping
/// </summary>
/// <param name="protocol">Minecraft protocol version</param>
/// <returns>TRUE if we can force-enable Forge support without using server Ping</returns>
public static bool ProtocolMayForceForge(int protocol)
{
return Protocol18Forge.ServerMayForceForge(protocol);
}
/// <summary>
/// Server Info: Consider Forge to be enabled regardless of server Ping
/// </summary>
/// <param name="protocol">Minecraft protocol version</param>
/// <returns>ForgeInfo item stating that Forge is enabled</returns>
public static ForgeInfo ProtocolForceForge(int protocol)
{
return Protocol18Forge.ServerForceForge(protocol);
}
public enum LoginResult
{
OtherError,
ServiceUnavailable,
SSLError,
Success,
WrongPassword,
AccountMigrated,
NotPremium,
LoginRequired,
InvalidToken,
InvalidResponse,
NullError,
UserCancel,
WrongSelection
};
public enum AccountType
{
Mojang,
Microsoft
};
/// <summary>
/// Allows to login to a premium Minecraft account using the Yggdrasil authentication scheme.
/// </summary>
/// <param name="user">Login</param>
/// <param name="pass">Password</param>
/// <param name="session">In case of successful login, will contain session information for multiplayer</param>
/// <returns>Returns the status of the login (Success, Failure, etc.)</returns>
public static LoginResult GetLogin(string user, string pass, LoginType type, out SessionToken session)
{
if (type == LoginType.microsoft)
{
if (Config.Main.General.Method == LoginMethod.mcc)
return MicrosoftMCCLogin(user, pass, out session);
else
return MicrosoftBrowserLogin(out session, user);
}
else if (type == LoginType.mojang)
{
return MojangLogin(user, pass, out session);
}
else if (type == LoginType.yggdrasil)
{
return YggdrasiLogin(user, pass, out session);
}
else
throw new InvalidOperationException(
"Account type must be Mojang or Microsoft or valid authlib 3rd Servers!");
}
/// <summary>
/// Login using Mojang account. Will be outdated after account migration
/// </summary>
/// <param name="user"></param>
/// <param name="pass"></param>
/// <param name="session"></param>
/// <returns></returns>
private static LoginResult MojangLogin(string user, string pass, out SessionToken session)
{
session = new SessionToken() { ClientID = Guid.NewGuid().ToString().Replace("-", "") };
try
{
string result = "";
string json_request = "{\"agent\": { \"name\": \"Minecraft\", \"version\": 1 }, \"username\": \"" +
JsonEncode(user) + "\", \"password\": \"" + JsonEncode(pass) +
"\", \"clientToken\": \"" + JsonEncode(session.ClientID) + "\" }";
int code = DoHTTPSPost("authserver.mojang.com", 443, "/authenticate", json_request, ref result);
if (code == 200)
{
if (result.Contains("availableProfiles\":[]}"))
{
return LoginResult.NotPremium;
}
else
{
var loginResponse = Json.ParseJson(result);
if (loginResponse?["accessToken"] is not null
&& loginResponse["selectedProfile"]?["id"] is not null
&& loginResponse["selectedProfile"]?["name"] is not null)
{
session.ID = loginResponse["accessToken"]!.GetStringValue();
session.PlayerID = loginResponse["selectedProfile"]!["id"]!.GetStringValue();
session.PlayerName = loginResponse["selectedProfile"]!["name"]!
.GetStringValue();
return LoginResult.Success;
}
else return LoginResult.InvalidResponse;
}
}
else if (code == 403)
{
if (result.Contains("UserMigratedException"))
{
return LoginResult.AccountMigrated;
}
else return LoginResult.WrongPassword;
}
else if (code == 503)
{
return LoginResult.ServiceUnavailable;
}
else
{
ConsoleIO.WriteLineFormatted("§8" + string.Format(Translations.error_http_code, code));
return LoginResult.OtherError;
}
}
catch (System.Security.Authentication.AuthenticationException e)
{
if (Settings.Config.Logging.DebugMessages)
{
ConsoleIO.WriteLineFormatted("§8" + e.ToString());
}
return LoginResult.SSLError;
}
catch (System.IO.IOException e)
{
if (Settings.Config.Logging.DebugMessages)
{
ConsoleIO.WriteLineFormatted("§8" + e.ToString());
}
if (e.Message.Contains("authentication"))
{
return LoginResult.SSLError;
}
else return LoginResult.OtherError;
}
catch (Exception e)
{
if (Settings.Config.Logging.DebugMessages)
{
ConsoleIO.WriteLineFormatted("§8" + e.ToString());
}
return LoginResult.OtherError;
}
}
private static LoginResult YggdrasiLogin(string user, string pass, out SessionToken session)
{
session = new SessionToken() { ClientID = Guid.NewGuid().ToString().Replace("-", "") };
try
{
string result = "";
string json_request = "{\"agent\": { \"name\": \"Minecraft\", \"version\": 1 }, \"username\": \"" +
JsonEncode(user) + "\", \"password\": \"" + JsonEncode(pass) +
"\", \"clientToken\": \"" + JsonEncode(session.ClientID) + "\" }";
int code = DoHTTPSPost(Config.Main.General.AuthServer.Host, Config.Main.General.AuthServer.Port,
Config.Main.General.AuthServer.AuthlibInjectorAPIPath + "/authserver/authenticate", json_request,
Config.Main.General.AuthServer.UseHttps, ref result);
if (code == 200)
{
if (result.Contains("availableProfiles\":[]}"))
{
return LoginResult.NotPremium;
}
else
{
var loginResponse = Json.ParseJson(result);
if (loginResponse?["accessToken"] is not null)
{
session.ID = loginResponse["accessToken"]!.GetStringValue();
if (loginResponse["selectedProfile"]?["id"] is not null
&& loginResponse["selectedProfile"]?["name"] is not null)
{
session.PlayerID = loginResponse["selectedProfile"]!["id"]!
.GetStringValue();
session.PlayerName = loginResponse["selectedProfile"]!["name"]!
.GetStringValue();
return LoginResult.Success;
}
else
{
string availableProfiles = "";
foreach (var profile in loginResponse["availableProfiles"]!.AsArray())
{
availableProfiles += " " + profile!["name"]!.GetStringValue();
}
ConsoleIO.WriteLine(Translations.mcc_avaliable_profiles + availableProfiles);
string selectedProfileName;
if (String.IsNullOrEmpty(Config.Main.General.AuthUser) || String.IsNullOrWhiteSpace(Config.Main.General.AuthUser))
{
ConsoleIO.WriteLine(Translations.mcc_select_profile);
selectedProfileName = ConsoleIO.ReadLine();
}
else selectedProfileName = Config.Main.General.AuthUser;
ConsoleIO.WriteLine(Translations.mcc_selected_profile + " " + selectedProfileName);
System.Text.Json.Nodes.JsonNode? selectedProfile = null;
foreach (var profile in loginResponse["availableProfiles"]!.AsArray())
{
selectedProfile = profile!["name"]!.GetStringValue() == selectedProfileName
? profile
: selectedProfile;
}
if (selectedProfile is not null)
{
session.PlayerID = selectedProfile["id"]!.GetStringValue();
session.PlayerName = selectedProfile["name"]!.GetStringValue();
SessionToken currentsession = session;
return GetNewYggdrasilToken(currentsession, out session);
}
else
{
return LoginResult.WrongSelection;
}
}
}
else return LoginResult.InvalidResponse;
}
}
else if (code == 403)
{
if (result.Contains("UserMigratedException"))
{
return LoginResult.AccountMigrated;
}
else return LoginResult.WrongPassword;
}
else if (code == 503)
{
return LoginResult.ServiceUnavailable;
}
else
{
ConsoleIO.WriteLineFormatted("§8" + string.Format(Translations.error_http_code, code));
return LoginResult.OtherError;
}
}
catch (System.Security.Authentication.AuthenticationException e)
{
if (Settings.Config.Logging.DebugMessages)
{
ConsoleIO.WriteLineFormatted("§8" + e.ToString());
}
return LoginResult.SSLError;
}
catch (System.IO.IOException e)
{
if (Settings.Config.Logging.DebugMessages)
{
ConsoleIO.WriteLineFormatted("§8" + e.ToString());
}
if (e.Message.Contains("authentication"))
{
return LoginResult.SSLError;
}
else return LoginResult.OtherError;
}
catch (Exception e)
{
if (Settings.Config.Logging.DebugMessages)
{
ConsoleIO.WriteLineFormatted("§8" + e.ToString());
}
return LoginResult.OtherError;
}
}
/// <summary>
/// Sign-in to Microsoft Account without using browser. Only works if 2FA is disabled.
/// Might not work well in some rare cases.
/// </summary>
/// <param name="email"></param>
/// <param name="password"></param>
/// <param name="session"></param>
/// <returns></returns>
private static LoginResult MicrosoftMCCLogin(string email, string password, out SessionToken session)
{
try
{
var msaResponse = XboxLive.UserLogin(email, password, XboxLive.PreAuth());
// Remove refresh token for MCC sign method
msaResponse.RefreshToken = string.Empty;
return MicrosoftLogin(msaResponse, out session);
}
catch (Exception e)
{
session = new SessionToken() { ClientID = Guid.NewGuid().ToString().Replace("-", "") };
ConsoleIO.WriteLineFormatted("§cMicrosoft authenticate failed: " + e.Message);
if (Settings.Config.Logging.DebugMessages)
{
ConsoleIO.WriteLineFormatted("§c" + e.StackTrace);
}
return LoginResult.WrongPassword; // Might not always be wrong password
}
}
/// <summary>
/// Sign-in to Microsoft Account by asking user to open sign-in page using browser.
/// </summary>
/// <remarks>
/// The downside is this require user to copy and paste lengthy content from and to console.
/// Sign-in page: 218 chars
/// Response URL: around 1500 chars
/// </remarks>
/// <param name="session"></param>
/// <returns></returns>
public static LoginResult MicrosoftBrowserLogin(out SessionToken session, string loginHint = "")
{
if (string.IsNullOrEmpty(loginHint))
Microsoft.OpenBrowser(Microsoft.SignInUrl);
else
Microsoft.OpenBrowser(Microsoft.GetSignInUrlWithHint(loginHint));
ConsoleIO.WriteLine(Translations.mcc_browser_open);
ConsoleIO.WriteLine("\n" + Microsoft.SignInUrl + "\n");
ConsoleIO.WriteLine(Translations.mcc_browser_login_code);
string code = ConsoleIO.ReadLine();
ConsoleIO.WriteLine(string.Format(Translations.mcc_connecting, "Microsoft"));
var msaResponse = Microsoft.RequestAccessToken(code);
return MicrosoftLogin(msaResponse, out session);
}
public static LoginResult MicrosoftLoginRefresh(string refreshToken, out SessionToken session)
{
var msaResponse = Microsoft.RefreshAccessToken(refreshToken);
return MicrosoftLogin(msaResponse, out session);
}
private static LoginResult MicrosoftLogin(Microsoft.LoginResponse msaResponse, out SessionToken session)
{
session = new SessionToken() { ClientID = Guid.NewGuid().ToString().Replace("-", "") };
try
{
var xblResponse = XboxLive.XblAuthenticate(msaResponse);
var xsts = XboxLive.XSTSAuthenticate(xblResponse); // Might throw even password correct
string accessToken = MinecraftWithXbox.LoginWithXbox(xsts.UserHash, xsts.Token);
bool hasGame = MinecraftWithXbox.UserHasGame(accessToken);
if (hasGame)
{
var profile = MinecraftWithXbox.GetUserProfile(accessToken);
session.PlayerName = profile.UserName;
session.PlayerID = profile.UUID;
session.ID = accessToken;
session.RefreshToken = msaResponse.RefreshToken;
InternalConfig.Account.Login = msaResponse.Email;
return LoginResult.Success;
}
else
{
return LoginResult.NotPremium;
}
}
catch (Exception e)
{
ConsoleIO.WriteLineFormatted("§cMicrosoft authenticate failed: " + e.Message);
if (Settings.Config.Logging.DebugMessages)
{
ConsoleIO.WriteLineFormatted("§c" + e.StackTrace);
}
return LoginResult.WrongPassword; // Might not always be wrong password
}
}
/// <summary>
/// Validates whether accessToken must be refreshed
/// </summary>
/// <param name="session">Session token to validate</param>
/// <returns>Returns the status of the token (Valid, Invalid, etc.)</returns>
public static LoginResult GetTokenValidation(SessionToken session)
{
var payload = JwtPayloadDecode.GetPayload(session.ID);
var json = Json.ParseJson(payload);
var expTimestamp = long.Parse(json!["exp"]!.GetStringValue(), NumberStyles.Any,
CultureInfo.CurrentCulture);
var now = DateTime.Now;
var tokenExp = UnixTimeStampToDateTime(expTimestamp);
if (Settings.Config.Logging.DebugMessages)
{
ConsoleIO.WriteLine("Access token expiration time is " + tokenExp.ToString());
}
if (now < tokenExp)
{
// Still valid
return LoginResult.Success;
}
else
{
// Token expired
return LoginResult.LoginRequired;
}
}
/// <summary>
/// Refreshes invalid token
/// </summary>
/// <param name="user">Login</param>
/// <param name="session">In case of successful token refresh, will contain session information for multiplayer</param>
/// <returns>Returns the status of the new token request (Success, Failure, etc.)</returns>
public static LoginResult GetNewToken(SessionToken currentsession, out SessionToken session)
{
session = new SessionToken();
try
{
string result = "";
string json_request = "{ \"accessToken\": \"" + JsonEncode(currentsession.ID) +
"\", \"clientToken\": \"" + JsonEncode(currentsession.ClientID) +
"\", \"selectedProfile\": { \"id\": \"" + JsonEncode(currentsession.PlayerID) +
"\", \"name\": \"" + JsonEncode(currentsession.PlayerName) + "\" } }";
int code = DoHTTPSPost("authserver.mojang.com", 443, "/refresh", json_request, ref result);
if (code == 200)
{
if (result == null)
{
return LoginResult.NullError;
}
else
{
var loginResponse = Json.ParseJson(result);
if (loginResponse?["accessToken"] is not null
&& loginResponse["selectedProfile"]?["id"] is not null
&& loginResponse["selectedProfile"]?["name"] is not null)
{
session.ID = loginResponse["accessToken"]!.GetStringValue();
session.PlayerID = loginResponse["selectedProfile"]!["id"]!.GetStringValue();
session.PlayerName = loginResponse["selectedProfile"]!["name"]!
.GetStringValue();
return LoginResult.Success;
}
else return LoginResult.InvalidResponse;
}
}
else if (code == 403 && result.Contains("InvalidToken"))
{
return LoginResult.InvalidToken;
}
else
{
ConsoleIO.WriteLineFormatted("§8" + string.Format(Translations.error_auth, code));
return LoginResult.OtherError;
}
}
catch
{
return LoginResult.OtherError;
}
}
public static LoginResult GetNewYggdrasilToken(SessionToken currentsession, out SessionToken session)
{
session = new SessionToken();
try
{
string result = "";
string json_request = "{ \"accessToken\": \"" + JsonEncode(currentsession.ID) +
"\", \"clientToken\": \"" + JsonEncode(currentsession.ClientID) +
"\", \"selectedProfile\": { \"id\": \"" + JsonEncode(currentsession.PlayerID) +
"\", \"name\": \"" + JsonEncode(currentsession.PlayerName) + "\" } }";
int code = DoHTTPSPost(Config.Main.General.AuthServer.Host, Config.Main.General.AuthServer.Port,
Config.Main.General.AuthServer.AuthlibInjectorAPIPath + "/authserver/refresh", json_request,
Config.Main.General.AuthServer.UseHttps, ref result);
if (code == 200)
{
if (result == null)
{
return LoginResult.NullError;
}
else
{
var loginResponse = Json.ParseJson(result);
if (loginResponse?["accessToken"] is not null
&& loginResponse["selectedProfile"]?["id"] is not null
&& loginResponse["selectedProfile"]?["name"] is not null)
{
session.ID = loginResponse["accessToken"]!.GetStringValue();
session.PlayerID = loginResponse["selectedProfile"]!["id"]!.GetStringValue();
session.PlayerName = loginResponse["selectedProfile"]!["name"]!
.GetStringValue();
return LoginResult.Success;
}
else return LoginResult.InvalidResponse;
}
}
else if (code == 403 && result.Contains("InvalidToken"))
{