├── PRMasterServer
├── Images
│ └── search.ico
├── x64
│ └── SQLite.Interop.dll
├── x86
│ └── SQLite.Interop.dll
├── External
│ └── Reality.Net.dll
├── Data
│ ├── AddressInfo.cs
│ ├── GeoIP.cs
│ ├── GameServer.cs
│ └── LoginDatabase.cs
├── Properties
│ └── AssemblyInfo.cs
├── packages.config
├── app.manifest
├── app.config
├── Program.cs
├── Servers
│ ├── CDKeyServer.cs
│ ├── ServerListReport.cs
│ ├── LoginServerMessages.cs
│ ├── LoginServer.cs
│ └── ServerListRetrieve.cs
├── PRMasterServer.csproj
└── Utils
│ └── SQLMethods.cs
├── .version
└── GlobalAssemblyInfo.cs
├── PRMasterServer.sln
├── README.md
├── .gitignore
└── LICENSE
/PRMasterServer/Images/search.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/realitymod/PRMasterServer/HEAD/PRMasterServer/Images/search.ico
--------------------------------------------------------------------------------
/PRMasterServer/x64/SQLite.Interop.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/realitymod/PRMasterServer/HEAD/PRMasterServer/x64/SQLite.Interop.dll
--------------------------------------------------------------------------------
/PRMasterServer/x86/SQLite.Interop.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/realitymod/PRMasterServer/HEAD/PRMasterServer/x86/SQLite.Interop.dll
--------------------------------------------------------------------------------
/PRMasterServer/External/Reality.Net.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/realitymod/PRMasterServer/HEAD/PRMasterServer/External/Reality.Net.dll
--------------------------------------------------------------------------------
/PRMasterServer/Data/AddressInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Net;
2 |
3 | namespace PRMasterServer.Data
4 | {
5 | internal class AddressInfo
6 | {
7 | public IPAddress Address;
8 | public ushort Port;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/PRMasterServer/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | [assembly: AssemblyTitle("Project Reality: BF2 Master Server")]
5 | [assembly: AssemblyDescription("Project Reality: BF2 Master Server")]
6 | [assembly: AssemblyCulture("")]
7 |
8 | [assembly: ComVisible(false)]
9 |
10 | [assembly: Guid("21aff3e3-55e6-4188-9933-2e3446f65293")]
--------------------------------------------------------------------------------
/PRMasterServer/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.version/GlobalAssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.34014
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | [assembly: System.Reflection.AssemblyCompany("Project Reality")]
12 | [assembly: System.Reflection.AssemblyProduct("Project Reality")]
13 | [assembly: System.Reflection.AssemblyCopyright("Copyright © Project Reality 2013-2014")]
14 | [assembly: System.Reflection.AssemblyVersion("1.1.0.0")]
15 | [assembly: System.Reflection.AssemblyFileVersion("1.1.98.1187")]
16 | [assembly: System.Reflection.AssemblyInformationalVersion("1.1.98.1187")]
17 |
18 |
19 |
--------------------------------------------------------------------------------
/PRMasterServer.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.30110.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PRMasterServer", "PRMasterServer\PRMasterServer.csproj", "{64BC01A8-FCD2-4AB7-8811-3200F83AE124}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {64BC01A8-FCD2-4AB7-8811-3200F83AE124}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {64BC01A8-FCD2-4AB7-8811-3200F83AE124}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {64BC01A8-FCD2-4AB7-8811-3200F83AE124}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {64BC01A8-FCD2-4AB7-8811-3200F83AE124}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/PRMasterServer/app.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/PRMasterServer/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/PRMasterServer/Data/GeoIP.cs:
--------------------------------------------------------------------------------
1 | using MaxMind.GeoIP2;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.IO;
5 | using System.Linq;
6 | using System.Text;
7 |
8 | namespace PRMasterServer.Data
9 | {
10 | public class GeoIP : IDisposable
11 | {
12 | public readonly DatabaseReader Reader;
13 |
14 | private static GeoIP _instance;
15 |
16 | public GeoIP(DatabaseReader reader)
17 | {
18 | Reader = reader;
19 | }
20 |
21 | public void Dispose()
22 | {
23 | Dispose(true);
24 | GC.SuppressFinalize(this);
25 | }
26 |
27 | protected virtual void Dispose(bool disposing)
28 | {
29 | try {
30 | if (disposing) {
31 | if (Reader != null) {
32 | Reader.Dispose();
33 | }
34 | _instance = null;
35 |
36 | if (_instance != null) {
37 | _instance.Dispose();
38 | _instance = null;
39 | }
40 | }
41 | } catch (Exception) {
42 | }
43 | }
44 |
45 | ~GeoIP()
46 | {
47 | Dispose(false);
48 | }
49 |
50 | public static void Initialize(Action log, string category)
51 | {
52 | DatabaseReader reader;
53 |
54 | if (File.Exists("GeoIP2-Country.mmdb")) {
55 | reader = new DatabaseReader("GeoIP2-Country.mmdb");
56 | log(category, "Loaded GeoIP2-Country.mmdb");
57 | } else if (File.Exists("GeoLite2-Country.mmdb")) {
58 | reader = new DatabaseReader("GeoLite2-Country.mmdb");
59 | log(category, "Loaded GeoLite2-Country.mmdb");
60 | } else {
61 | reader = null;
62 | }
63 |
64 | _instance = new GeoIP(reader);
65 | }
66 |
67 | public static GeoIP Instance
68 | {
69 | get
70 | {
71 | if (_instance == null) {
72 | throw new ArgumentNullException("Instance", "Initialize() must be called first");
73 | }
74 |
75 | return _instance;
76 | }
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/PRMasterServer/Program.cs:
--------------------------------------------------------------------------------
1 | using PRMasterServer.Data;
2 | using PRMasterServer.Servers;
3 | using System;
4 | using System.Globalization;
5 | using System.Net;
6 | using System.Threading;
7 |
8 | namespace PRMasterServer
9 | {
10 | class Program
11 | {
12 | private static readonly object _lock = new object();
13 |
14 | static void Main(string[] args)
15 | {
16 | Action log = (category, message) => {
17 | lock (_lock) {
18 | Log(String.Format("[{0}] {1}", category, message));
19 | }
20 | };
21 |
22 | Action logError = (category, message) => {
23 | lock (_lock) {
24 | LogError(String.Format("[{0}] {1}", category, message));
25 | }
26 | };
27 |
28 | IPAddress bind = IPAddress.Any;
29 | if (args.Length >= 1) {
30 | for (int i = 0; i < args.Length; i++) {
31 | if (args[i].Equals("+bind")) {
32 | if ((i >= args.Length - 1) || !IPAddress.TryParse(args[i + 1], out bind)) {
33 | LogError("+bind value must be a valid IP Address to bind to!");
34 | }
35 | } else if (args[i].Equals("+db")) {
36 | if ((i >= args.Length - 1)) {
37 | LogError("+db value must be a path to the database");
38 | } else {
39 | LoginDatabase.Initialize(args[i + 1], log, logError);
40 | }
41 | }
42 | }
43 | }
44 |
45 | if (!LoginDatabase.IsInitialized()) {
46 | LogError("Error initializing database, please confirm parameter +db is valid");
47 | LogError("Press any key to continue");
48 | Console.ReadKey();
49 | return;
50 | }
51 |
52 | CDKeyServer cdKeyServer = new CDKeyServer(bind, 29910, log, logError);
53 | ServerListReport serverListReport = new ServerListReport(bind, 27900, log, logError);
54 | ServerListRetrieve serverListRetrieve = new ServerListRetrieve(bind, 28910, serverListReport, log, logError);
55 | LoginServer loginServer = new LoginServer(bind, 29900, 29901, log, logError);
56 |
57 | while (true) {
58 | Thread.Sleep(1000);
59 | }
60 | }
61 |
62 | private static void Log(string message)
63 | {
64 | Console.WriteLine(String.Format("[{0}] {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture), message));
65 | }
66 |
67 | private static void LogError(string message)
68 | {
69 | ConsoleColor c = Console.ForegroundColor;
70 | Console.ForegroundColor = ConsoleColor.Red;
71 | Console.Error.WriteLine(String.Format("[{0}] {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture), message));
72 | Console.ForegroundColor = c;
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/PRMasterServer/Data/GameServer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace PRMasterServer.Data
4 | {
5 | internal class NonFilterAttribute : Attribute
6 | {
7 | }
8 |
9 | internal class GameServer
10 | {
11 | [NonFilter]
12 | public bool Valid { get; set; }
13 |
14 | [NonFilter]
15 | public string IPAddress { get; set; }
16 |
17 | [NonFilter]
18 | public int QueryPort { get; set; }
19 |
20 | [NonFilter]
21 | public DateTime LastRefreshed { get; set; }
22 |
23 | [NonFilter]
24 | public DateTime LastPing { get; set; }
25 |
26 |
27 | [NonFilter]
28 | public string localip0 { get; set; }
29 |
30 | [NonFilter]
31 | public string localip1 { get; set; }
32 |
33 | [NonFilter]
34 | public int localport { get; set; }
35 |
36 | [NonFilter]
37 | public bool natneg { get; set; }
38 |
39 | [NonFilter]
40 | public int statechanged { get; set; }
41 |
42 | public string country { get; set; }
43 | public string hostname { get; set; }
44 | public string gamename { get; set; }
45 | public string gamever { get; set; }
46 | public string mapname { get; set; }
47 | public string gametype { get; set; }
48 | public string gamevariant { get; set; }
49 | public int numplayers { get; set; }
50 | public int maxplayers { get; set; }
51 | public string gamemode { get; set; }
52 | public bool password { get; set; }
53 | public int timelimit { get; set; }
54 | public int roundtime { get; set; }
55 | public int hostport { get; set; }
56 | public bool bf2_dedicated { get; set; }
57 | public bool bf2_ranked { get; set; }
58 | public bool bf2_anticheat { get; set; }
59 | public string bf2_os { get; set; }
60 | public bool bf2_autorec { get; set; }
61 | public string bf2_d_idx { get; set; }
62 | public string bf2_d_dl { get; set; }
63 | public bool bf2_voip { get; set; }
64 | public bool bf2_autobalanced { get; set; }
65 | public bool bf2_friendlyfire { get; set; }
66 | public string bf2_tkmode { get; set; }
67 | public double bf2_startdelay { get; set; }
68 | public double bf2_spawntime { get; set; }
69 | public string bf2_sponsortext { get; set; }
70 | public string bf2_sponsorlogo_url { get; set; }
71 | public string bf2_communitylogo_url { get; set; }
72 | public int bf2_scorelimit { get; set; }
73 | public double bf2_ticketratio { get; set; }
74 | public double bf2_teamratio { get; set; }
75 | public string bf2_team1 { get; set; }
76 | public string bf2_team2 { get; set; }
77 | public bool bf2_bots { get; set; }
78 | public bool bf2_pure { get; set; }
79 | public int bf2_mapsize { get; set; }
80 | public bool bf2_globalunlocks { get; set; }
81 | public double bf2_fps { get; set; }
82 | public bool bf2_plasma { get; set; }
83 | public int bf2_reservedslots { get; set; }
84 | public double bf2_coopbotratio { get; set; }
85 | public int bf2_coopbotcount { get; set; }
86 | public int bf2_coopbotdiff { get; set; }
87 | public bool bf2_novehicles { get; set; }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | PRMasterServer
2 | ==============
3 |
4 | A GameSpy replacement Master Server for [Project Reality: BF2](http://www.realitymod.com). This emulates the GameSpy API in order to keep PR:BF2 playable after the Battlefield 2 GameSpy shutdown.
5 |
6 | Features
7 | ---------------------
8 | Supports **Battlefield 2**'s GameSpy implementation. No other games are supported (yet?). If you wish to modify the code and add support for your game, or add any additional features, please feel free to make a **fork** and submit a [pull request](https://help.github.com/articles/using-pull-requests).
9 |
10 | - Login Server (Uses SQLite for the database)
11 | - Creating Accounts
12 | - Retrieving accounts by username/email (allows multiple accounts per email)
13 | - Log in
14 | - Server Browser
15 | - Server Reporting (Game Server registering with Master Server)
16 | - Server Retrieval (Client requesting a server list)
17 | - Supports filters
18 | - GeoIP
19 | - CD Key Authentication
20 | - Accepts all CD Keys with no further checks.
21 |
22 | Setting up the project
23 | ---------------------
24 | 1. Be sure to have [Visual Studio 2013](http://www.microsoft.com/en-us/download/details.aspx?id=40787) installed. You might be able to compile it using previous versions of Visual Studio or using Mono, but this is untested and may not work.
25 |
26 | 2. Open **PRMasterServer.sln**, and build. This should download via NuGet any extra packages required.
27 |
28 | 3. Grab the latest [MaxMind GeoIP2 Country](https://www.maxmind.com/en/country) database, or use the free [GeoLite2 Country](http://dev.maxmind.com/geoip/geoip2/geolite2/) database. Put it in the same folder as **PRMasterServer.exe**.
29 |
30 | 4. Create a **modwhitelist.txt** file containing line separated mod names (i.e. bf2, pr, fh2) to allow servers running these mods to register with the master server. Or, just use **%** to allow all mods. If you don't have a **modwhitelist.txt** file, it will default to Project Reality: BF2 mod names (*pr* and *pr!_%*).
31 | > **Tip:** % is wildcard, _ is placeholder, ! is escape, # at the start of the line is a comment, empty lines are ignored.
32 |
33 | 5. Run **PRMasterServer.exe +db LoginDatabase.db3** and it should start up with no errors. You can use an optional **+bind xxx.xxx.xxx.xxx** paramter to bind the server to a specific network interface, or by default it will bind to all available interfaces.
34 |
35 | 6. If there's issues, unlucky, I'm sure you'll be able to figure them out :).
36 |
37 | Stuff to do
38 | ---------------------
39 | Of course, no project is ever really *complete*, there's plenty of other stuff that could be done. Maybe in the future it just might happen.
40 |
41 | - Comment the code so you poor folk can understand the black magic.
42 | - Manage account protocol (delete accounts, change password, change email).
43 | - Maybe support some other games than just Battlefield 2. But isn't that the point of open sourcing and putting it on GitHub? If you want it, make a fork and do it ;).
44 |
45 | Credits
46 | ---------------------
47 |
48 | [Luigi Auriemma](http://aluigi.org) for reverse engineering the GameSpy protocol and encryption.
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.sln.docstates
8 |
9 | # Build results
10 | [Dd]ebug/
11 | [Dd]ebugPublic/
12 | [Rr]elease/
13 | build/
14 | bld/
15 | [Bb]in/
16 | [Oo]bj/
17 |
18 | # MSTest test Results
19 | [Tt]est[Rr]esult*/
20 | [Bb]uild[Ll]og.*
21 |
22 | #NUNIT
23 | *.VisualState.xml
24 | TestResult.xml
25 |
26 | # Build Results of an ATL Project
27 | [Dd]ebugPS/
28 | [Rr]eleasePS/
29 | dlldata.c
30 |
31 | *_i.c
32 | *_p.c
33 | *_i.h
34 | *.ilk
35 | *.meta
36 | *.obj
37 | *.pch
38 | *.pdb
39 | *.pgc
40 | *.pgd
41 | *.rsp
42 | *.sbr
43 | *.tlb
44 | *.tli
45 | *.tlh
46 | *.tmp
47 | *.tmp_proj
48 | *.log
49 | *.vspscc
50 | *.vssscc
51 | .builds
52 | *.pidb
53 | *.svclog
54 | *.scc
55 |
56 | # Chutzpah Test files
57 | _Chutzpah*
58 |
59 | # Visual C++ cache files
60 | ipch/
61 | *.aps
62 | *.ncb
63 | *.opensdf
64 | *.sdf
65 | *.cachefile
66 |
67 | # Visual Studio profiler
68 | *.psess
69 | *.vsp
70 | *.vspx
71 |
72 | # TFS 2012 Local Workspace
73 | $tf/
74 |
75 | # Guidance Automation Toolkit
76 | *.gpState
77 |
78 | # ReSharper is a .NET coding add-in
79 | _ReSharper*/
80 | *.[Rr]e[Ss]harper
81 | *.DotSettings.user
82 |
83 | # JustCode is a .NET coding addin-in
84 | .JustCode
85 |
86 | # TeamCity is a build add-in
87 | _TeamCity*
88 |
89 | # DotCover is a Code Coverage Tool
90 | *.dotCover
91 |
92 | # NCrunch
93 | *.ncrunch*
94 | _NCrunch_*
95 | .*crunch*.local.xml
96 |
97 | # MightyMoose
98 | *.mm.*
99 | AutoTest.Net/
100 |
101 | # Web workbench (sass)
102 | .sass-cache/
103 |
104 | # Installshield output folder
105 | [Ee]xpress/
106 |
107 | # DocProject is a documentation generator add-in
108 | DocProject/buildhelp/
109 | DocProject/Help/*.HxT
110 | DocProject/Help/*.HxC
111 | DocProject/Help/*.hhc
112 | DocProject/Help/*.hhk
113 | DocProject/Help/*.hhp
114 | DocProject/Help/Html2
115 | DocProject/Help/html
116 |
117 | # Click-Once directory
118 | publish/
119 |
120 | # Publish Web Output
121 | *.[Pp]ublish.xml
122 | *.azurePubxml
123 |
124 | # NuGet Packages Directory
125 | packages/
126 | ## TODO: If the tool you use requires repositories.config uncomment the next line
127 | #!packages/repositories.config
128 |
129 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
130 | # This line needs to be after the ignore of the build folder (and the packages folder if the line above has been uncommented)
131 | !packages/build/
132 |
133 | # Windows Azure Build Output
134 | csx/
135 | *.build.csdef
136 |
137 | # Windows Store app package directory
138 | AppPackages/
139 |
140 | # Others
141 | sql/
142 | *.Cache
143 | ClientBin/
144 | [Ss]tyle[Cc]op.*
145 | ~$*
146 | *~
147 | *.dbmdl
148 | *.dbproj.schemaview
149 | *.pfx
150 | *.publishsettings
151 | node_modules/
152 |
153 | # RIA/Silverlight projects
154 | Generated_Code/
155 |
156 | # Backup & report files from converting an old project file to a newer
157 | # Visual Studio version. Backup files are not needed, because we have git ;-)
158 | _UpgradeReport_Files/
159 | Backup*/
160 | UpgradeLog*.XML
161 | UpgradeLog*.htm
162 |
163 | # SQL Server files
164 | *.mdf
165 | *.ldf
166 |
167 | # Business Intelligence projects
168 | *.rdl.data
169 | *.bim.layout
170 | *.bim_*.settings
171 |
172 | # Microsoft Fakes
173 | FakesAssemblies/
174 |
--------------------------------------------------------------------------------
/PRMasterServer/Servers/CDKeyServer.cs:
--------------------------------------------------------------------------------
1 | using PRMasterServer.Data;
2 | using System;
3 | using System.Net;
4 | using System.Net.Sockets;
5 | using System.Text;
6 | using System.Text.RegularExpressions;
7 | using System.Threading;
8 |
9 | namespace PRMasterServer.Servers
10 | {
11 | internal class CDKeyServer
12 | {
13 | private const string Category = "CDKey";
14 |
15 | public Action Log = (x, y) => { };
16 | public Action LogError = (x, y) => { };
17 |
18 | public Thread Thread;
19 |
20 | private const int BufferSize = 8192;
21 | private Socket _socket;
22 | private SocketAsyncEventArgs _socketReadEvent;
23 | private byte[] _socketReceivedBuffer;
24 |
25 | private readonly Regex _dataPattern = new Regex(@"^\\auth\\\\pid\\1059\\ch\\[a-zA-z0-9]{8,10}\\resp\\(?[a-zA-z0-9]{72})\\ip\\\d+\\skey\\(?\d+)(\\reqproof\\[01]\\)?$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture);
26 | private const string _dataResponse = @"\uok\\cd\{0}\skey\{1}";
27 |
28 | public CDKeyServer(IPAddress listen, ushort port, Action log, Action logError)
29 | {
30 | Log = log;
31 | LogError = logError;
32 |
33 | Thread = new Thread(StartServer) {
34 | Name = "CD Key Thread"
35 | };
36 | Thread.Start(new AddressInfo() {
37 | Address = listen,
38 | Port = port
39 | });
40 | }
41 |
42 | public void Dispose()
43 | {
44 | Dispose(true);
45 | GC.SuppressFinalize(this);
46 | }
47 |
48 | protected virtual void Dispose(bool disposing)
49 | {
50 | try {
51 | if (disposing) {
52 | if (_socket != null) {
53 | _socket.Close();
54 | _socket.Dispose();
55 | _socket = null;
56 | }
57 | }
58 | } catch (Exception) {
59 | }
60 | }
61 |
62 | ~CDKeyServer()
63 | {
64 | Dispose(false);
65 | }
66 |
67 | private void StartServer(object parameter)
68 | {
69 | AddressInfo info = (AddressInfo)parameter;
70 |
71 | Log(Category, "Starting CD Key Server");
72 |
73 | try {
74 | _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) {
75 | SendTimeout = 5000,
76 | ReceiveTimeout = 5000,
77 | SendBufferSize = BufferSize,
78 | ReceiveBufferSize = BufferSize
79 | };
80 |
81 | _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true);
82 | _socket.Bind(new IPEndPoint(info.Address, info.Port));
83 |
84 | _socketReadEvent = new SocketAsyncEventArgs() {
85 | RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0)
86 | };
87 | _socketReceivedBuffer = new byte[BufferSize];
88 | _socketReadEvent.SetBuffer(_socketReceivedBuffer, 0, BufferSize);
89 | _socketReadEvent.Completed += OnDataReceived;
90 | } catch (Exception e) {
91 | LogError(Category, String.Format("Unable to bind CD Key Server to {0}:{1}", info.Address, info.Port));
92 | LogError(Category, e.ToString());
93 | return;
94 | }
95 |
96 | WaitForData();
97 | }
98 |
99 | private void WaitForData()
100 | {
101 | Thread.Sleep(10);
102 |
103 | try {
104 | _socket.ReceiveFromAsync(_socketReadEvent);
105 | } catch (SocketException e) {
106 | LogError(Category, "Error receiving data");
107 | LogError(Category, e.ToString());
108 | return;
109 | }
110 | }
111 |
112 | private void OnDataReceived(object sender, SocketAsyncEventArgs e)
113 | {
114 | try {
115 | IPEndPoint remote = (IPEndPoint)e.RemoteEndPoint;
116 |
117 | string receivedData = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
118 | string decrypted = Xor(receivedData);
119 |
120 | // known messages
121 | // \ka\ = keep alive from the game server every 20s, we don't care about this
122 | // \auth\ ... = authenticate cd key, this is what we care about
123 | // \disc\ ... = disconnect cd key, because there's checks if the cd key is in use, which we don't care about really, but we could if we wanted to
124 |
125 | // \ka\ is a keep alive from the game server, it's useless :p
126 | if (decrypted != @"\ka\") {
127 | Match m = _dataPattern.Match(decrypted);
128 |
129 | if (m.Success) {
130 | Log(Category, String.Format("Received request from: {0}:{1}", ((IPEndPoint)e.RemoteEndPoint).Address, ((IPEndPoint)e.RemoteEndPoint).Port));
131 |
132 | string reply = String.Format(_dataResponse, m.Groups["Challenge"].Value.Substring(0, 32), m.Groups["Key"].Value);
133 |
134 | byte[] response = Encoding.UTF8.GetBytes(Xor(reply));
135 | _socket.SendTo(response, remote);
136 | }
137 | }
138 | } catch (Exception) {
139 | }
140 |
141 | WaitForData();
142 | }
143 |
144 | private static string Xor(string s)
145 | {
146 | const string gamespy = "gamespy";
147 | int length = s.Length;
148 | char[] data = s.ToCharArray();
149 | int index = 0;
150 |
151 | for (int i = 0; length > 0; length--) {
152 | if (i >= gamespy.Length)
153 | i = 0;
154 |
155 | data[index++] ^= gamespy[i++];
156 | }
157 |
158 | return new String(data);
159 | }
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/PRMasterServer/PRMasterServer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {64BC01A8-FCD2-4AB7-8811-3200F83AE124}
8 | Exe
9 | Properties
10 | PRMasterServer
11 | PRMasterServer
12 | v4.0
13 | 512
14 |
15 |
16 | true
17 | $(SolutionDir)\bin\Debug\
18 | DEBUG;TRACE
19 | full
20 | AnyCPU
21 | prompt
22 | MinimumRecommendedRules.ruleset
23 |
24 |
25 | $(SolutionDir)\bin\Release\
26 | TRACE
27 | true
28 | pdbonly
29 | AnyCPU
30 | prompt
31 | MinimumRecommendedRules.ruleset
32 |
33 |
34 | Images\search.ico
35 |
36 |
37 | app.manifest
38 |
39 |
40 |
41 | ..\packages\EntityFramework.6.0.0\lib\net40\EntityFramework.dll
42 |
43 |
44 | ..\packages\EntityFramework.6.0.0\lib\net40\EntityFramework.SqlServer.dll
45 |
46 |
47 | ..\packages\MaxMind.Db.0.2.3.0\lib\net40\MaxMind.Db.dll
48 |
49 |
50 | ..\packages\MaxMind.GeoIP2.0.3.2.0\lib\net40\MaxMind.GeoIP2.dll
51 |
52 |
53 | False
54 | ..\packages\Newtonsoft.Json.6.0.2\lib\net40\Newtonsoft.Json.dll
55 |
56 |
57 | ..\packages\RestSharp.104.4.0\lib\net4\RestSharp.dll
58 |
59 |
60 |
61 |
62 |
63 | ..\packages\System.Data.SQLite.Core.1.0.92.0\lib\net40\System.Data.SQLite.dll
64 |
65 |
66 | ..\packages\System.Data.SQLite.EF6.1.0.92.0\lib\net40\System.Data.SQLite.EF6.dll
67 |
68 |
69 | ..\packages\System.Data.SQLite.Linq.1.0.92.0\lib\net40\System.Data.SQLite.Linq.dll
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 | GlobalAssemblyInfo.cs
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 | False
98 | External\Reality.Net.dll
99 |
100 |
101 |
102 |
103 |
104 |
105 | Always
106 |
107 |
108 | Always
109 |
110 |
111 |
112 |
113 |
114 | Designer
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
--------------------------------------------------------------------------------
/PRMasterServer/Utils/SQLMethods.cs:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Author: Todd Hubers (http://www.alivate.com.au)
4 |
5 | This is free and unencumbered software released into the public domain.
6 |
7 | Anyone is free to copy, modify, publish, use, compile, sell, or
8 | distribute this software, either in source code form or as a compiled
9 | binary, for any purpose, commercial or non-commercial, and by any
10 | means.
11 |
12 | In jurisdictions that recognize copyright laws, the author or authors
13 | of this software dedicate any and all copyright interest in the
14 | software to the public domain. We make this dedication for the benefit
15 | of the public at large and to the detriment of our heirs and
16 | successors. We intend this dedication to be an overt act of
17 | relinquishment in perpetuity of all present and future rights to this
18 | software under copyright law.
19 |
20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
23 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
24 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
25 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
26 | OTHER DEALINGS IN THE SOFTWARE.
27 |
28 | For more information, please refer to
29 | */
30 |
31 | /**
32 | * PRMasterServer changes:
33 | * Added a NotLike method, which is the same as Like, but not'd :p
34 | */
35 |
36 | using System;
37 |
38 | namespace Alivate
39 | {
40 | public static class SQLMethods
41 | {
42 | ///
43 | /// EvaluateIsLike
44 | ///
45 | /// The value to evaluate
46 | /// The pattern to use
47 | /// Whether the pattern matches the value to evaluate
48 | public static bool EvaluateIsLike(string MatchValue, string Pattern)
49 | {
50 | return EvaluateIsLike(MatchValue, Pattern, '%', '_', '!');
51 | }
52 |
53 | ///
54 | /// EvaluateIsNotLike
55 | ///
56 | /// The value to evaluate
57 | /// The pattern to use
58 | /// Whether the pattern matches the value to evaluate
59 | public static bool EvaluateIsNotLike(string MatchValue, string Pattern)
60 | {
61 | return EvaluateIsNotLike(MatchValue, Pattern, '%', '_', '!');
62 | }
63 |
64 | ///
65 | /// EvaluateIsLike
66 | ///
67 | /// The value to evaluate
68 | /// The pattern to use
69 | /// Whether the pattern matches the value to evaluate
70 | public static bool EvaluateIsLike(string MatchValue, string Pattern, char Wildcard = '%', char Placeholder = '_', char Escape = '!')
71 | {
72 | LikeParams l = new LikeParams() {
73 | MatchValue = MatchValue.ToLowerInvariant(),
74 | Pattern = Pattern.ToLowerInvariant(),
75 | Wildcard = Wildcard,
76 | PlaceHolder = Placeholder,
77 | Escape = Escape
78 | };
79 |
80 | return EvaluateIsLike(l, 0, 0);
81 | }
82 |
83 | ///
84 | /// EvaluateIsNotLike
85 | ///
86 | /// The value to evaluate
87 | /// The pattern to use
88 | /// Whether the pattern matches the value to evaluate
89 | public static bool EvaluateIsNotLike(string MatchValue, string Pattern, char Wildcard = '%', char Placeholder = '_', char Escape = '!')
90 | {
91 | LikeParams l = new LikeParams() {
92 | MatchValue = MatchValue.ToLowerInvariant(),
93 | Pattern = Pattern.ToLowerInvariant(),
94 | Wildcard = Wildcard,
95 | PlaceHolder = Placeholder,
96 | Escape = Escape
97 | };
98 |
99 | return !EvaluateIsLike(l, 0, 0);
100 | }
101 |
102 | private static bool EvaluateIsLike(LikeParams l, int ValuePosition, int PatternPosition)
103 | {
104 | bool IsOnEscape = false;
105 |
106 | while (true) {
107 | IsOnEscape = false;
108 | if (l.Pattern[PatternPosition] == l.Escape) {
109 | IsOnEscape = true;
110 | PatternPosition++;
111 | if (PatternPosition == l.Pattern.Length) {
112 | IsOnEscape = false;
113 | PatternPosition--;
114 | //throw new Exception("Escape character found at end of string - can't use that"); //Run out of characters
115 | }
116 | }
117 |
118 | if (!IsOnEscape && l.Pattern[PatternPosition] == l.Wildcard) {
119 | PatternPosition++; //Look at the next character from now on
120 |
121 | if (PatternPosition == l.Pattern.Length) //Wildcard at the end of the pattern, requires no further processing
122 | return true;
123 |
124 | //Find the first case of a character we can match (escaped or otherwise, fast forwarding past placeholders and other wildcards along the way)
125 | while (true) {
126 | IsOnEscape = false;
127 |
128 | if (l.Pattern[PatternPosition] == l.Escape) {
129 | IsOnEscape = true;
130 | PatternPosition++;
131 | if (PatternPosition == l.Pattern.Length)
132 | throw new Exception("Escape character found at end of string - can't use that"); //Run out of characters
133 | }
134 |
135 | if (!IsOnEscape && l.Pattern[PatternPosition] == l.PlaceHolder) {
136 | ValuePosition++; //Requires at least 1 character before search text
137 | if (ValuePosition == l.MatchValue.Length)
138 | return false; //Run out of characters
139 | } else if (!IsOnEscape && l.Pattern[PatternPosition] == l.Wildcard) {
140 | PatternPosition++;
141 | if (PatternPosition == l.Pattern.Length)
142 | return true; //Run out of characters
143 | } else {
144 | char SearchCharacter = l.Pattern[PatternPosition];
145 | if (IsOnEscape && SearchCharacter != l.Wildcard && SearchCharacter != l.PlaceHolder && SearchCharacter != l.Escape)
146 | throw new Exception("Invalid escape sequence (wildcard scan) - " + PatternPosition);
147 |
148 | int start = ValuePosition;
149 | while (true) {
150 | //Now we can find a starting position for continued Evaluation
151 | start = l.MatchValue.IndexOf(SearchCharacter, start);
152 | if (start == -1)
153 | return false; //Match could not be found
154 |
155 | if (!IsOnEscape) {
156 | if (EvaluateIsLike(l, start, PatternPosition))
157 | return true; //Pop the true up the stack
158 | } else {
159 | if (EvaluateIsLike(l, start, PatternPosition - 1)) //Substract 1 so the recursed function can re-evaluate
160 | return true; //Pop the true up the stack
161 | }
162 |
163 | start++; //Try to find another match
164 | }
165 | }
166 | }
167 |
168 | } else if (!IsOnEscape && l.Pattern[PatternPosition] == l.PlaceHolder) {
169 | if (ValuePosition == l.MatchValue.Length) //MatchValue is too short - we've reached the end
170 | return false;
171 | } else {
172 | if (ValuePosition == l.MatchValue.Length)
173 | return false; //Characters left over in value, without wildcard in pattern on last character
174 |
175 | char ValueCharacter = l.MatchValue[ValuePosition];
176 | char PatternCharacter = l.Pattern[PatternPosition];
177 | if (IsOnEscape && PatternCharacter != l.Wildcard && PatternCharacter != l.PlaceHolder && PatternCharacter != l.Escape)
178 | throw new Exception(String.Format("Invalid escape sequence - {0} - {1}", PatternPosition, ValueCharacter));
179 |
180 | if (ValueCharacter != PatternCharacter) //Characters don't match - fail
181 | return false;
182 | }
183 |
184 | ValuePosition++;
185 | PatternPosition++;
186 |
187 | if (PatternPosition == l.Pattern.Length) {
188 | if (ValuePosition == l.MatchValue.Length)
189 | return true; //Run out of characters
190 | else
191 | return false; //Left over characters in Value without % in pattern
192 | }
193 | }
194 | }
195 |
196 | //Shared data across recursion
197 | class LikeParams
198 | {
199 | public string MatchValue;
200 | public string Pattern;
201 | public char Wildcard;
202 | public char PlaceHolder;
203 | public char Escape;
204 | }
205 | }
206 | }
207 |
--------------------------------------------------------------------------------
/PRMasterServer/Data/LoginDatabase.cs:
--------------------------------------------------------------------------------
1 | using Reality.Net.Extensions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Data;
5 | using System.Data.SQLite;
6 | using System.IO;
7 | using System.Net;
8 | using System.Runtime.InteropServices;
9 |
10 | namespace PRMasterServer.Data
11 | {
12 | public class LoginDatabase : IDisposable
13 | {
14 | private const string Category = "LoginDatabase";
15 |
16 | private static Action Log = (x, y) => { };
17 | private static Action LogError = (x, y) => { };
18 |
19 | private static LoginDatabase _instance;
20 |
21 | private SQLiteConnection _db;
22 |
23 | private delegate bool EventHandler(CtrlType sig);
24 | private static EventHandler _closeHandler;
25 |
26 | private SQLiteCommand _getUsersByName;
27 | private SQLiteCommand _getUsersByEmail;
28 | private SQLiteCommand _updateUser;
29 | private SQLiteCommand _createUser;
30 | private SQLiteCommand _countUsers;
31 | private SQLiteCommand _logUser;
32 | private SQLiteCommand _logUserUpdateCountry;
33 |
34 | // we're not going to have 100 million users using this login database
35 | private const int UserIdOffset = 200000000;
36 | private const int ProfileIdOffset = 100000000;
37 |
38 | private readonly object _dbLock = new object();
39 |
40 | public static void Initialize(string databasePath, Action log, Action logError)
41 | {
42 | // we need to safely dispose of the database when the application closes
43 | // this is a console app, so we need to hook into the console ctrl signal
44 | _closeHandler += CloseHandler;
45 | SetConsoleCtrlHandler(_closeHandler, true);
46 |
47 | Log = log;
48 | LogError = logError;
49 |
50 | _instance = new LoginDatabase();
51 |
52 | databasePath = Path.GetFullPath(databasePath);
53 |
54 | if (!File.Exists(databasePath)) {
55 | SQLiteConnection.CreateFile(databasePath);
56 | }
57 |
58 | if (File.Exists(databasePath)) {
59 | SQLiteConnectionStringBuilder connBuilder = new SQLiteConnectionStringBuilder() {
60 | DataSource = databasePath,
61 | Version = 3,
62 | PageSize = 4096,
63 | CacheSize = 10000,
64 | JournalMode = SQLiteJournalModeEnum.Wal,
65 | LegacyFormat = false,
66 | DefaultTimeout = 500
67 | };
68 |
69 | _instance._db = new SQLiteConnection(connBuilder.ToString());
70 | _instance._db.Open();
71 |
72 | if (_instance._db.State == ConnectionState.Open) {
73 | bool read = false;
74 | using (SQLiteCommand queryTables = new SQLiteCommand("SELECT * FROM sqlite_master WHERE type='table' AND name='users'", _instance._db)) {
75 | using (SQLiteDataReader reader = queryTables.ExecuteReader()) {
76 | while (reader.Read()) {
77 | read = true;
78 | break;
79 | }
80 | }
81 | }
82 |
83 | if (!read) {
84 | Log(Category, "No database found, creating now");
85 | using (SQLiteCommand createTables = new SQLiteCommand("CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, country TEXT NOT NULL, lastip TEXT NOT NULL, lasttime INTEGER NULL DEFAULT '0', session INTEGER NULL DEFAULT '0' )", _instance._db)) {
86 | createTables.ExecuteNonQuery();
87 | }
88 | Log(Category, "Using " + databasePath);
89 | _instance.PrepareStatements();
90 | return;
91 | } else {
92 | Log(Category, "Using " + databasePath);
93 | _instance.PrepareStatements();
94 | return;
95 | }
96 | }
97 | }
98 |
99 | LogError(Category, "Error creating database");
100 | _instance.Dispose();
101 | _instance = null;
102 | }
103 |
104 | private void PrepareStatements()
105 | {
106 | _getUsersByName = new SQLiteCommand("SELECT id, password, email, country, session FROM users WHERE name=@name COLLATE NOCASE", _db);
107 | _getUsersByName.Parameters.Add("@name", DbType.String);
108 |
109 | _getUsersByEmail = new SQLiteCommand("SELECT id, name, country, session FROM users WHERE email=@email AND password=@password", _db);
110 | _getUsersByEmail.Parameters.Add("@email", DbType.String);
111 | _getUsersByEmail.Parameters.Add("@password", DbType.String);
112 |
113 | _updateUser = new SQLiteCommand("UPDATE users SET password=@pass, email=@email, country=@country, session=@session WHERE name=@name COLLATE NOCASE", _db);
114 | _updateUser.Parameters.Add("@pass", DbType.String);
115 | _updateUser.Parameters.Add("@email", DbType.String);
116 | _updateUser.Parameters.Add("@country", DbType.String);
117 | _updateUser.Parameters.Add("@session", DbType.Int64);
118 | _updateUser.Parameters.Add("@name", DbType.String);
119 |
120 | _createUser = new SQLiteCommand("INSERT INTO users (name, password, email, country, lastip) VALUES ( @name, @pass, @email, @country, @ip )", _db);
121 | _createUser.Parameters.Add("@name", DbType.String);
122 | _createUser.Parameters.Add("@pass", DbType.String);
123 | _createUser.Parameters.Add("@email", DbType.String);
124 | _createUser.Parameters.Add("@country", DbType.String);
125 | _createUser.Parameters.Add("@ip", DbType.String);
126 |
127 | _countUsers = new SQLiteCommand("SELECT COUNT(*) FROM users WHERE name=@name COLLATE NOCASE", _db);
128 | _countUsers.Parameters.Add("@name", DbType.String);
129 |
130 | _logUser = new SQLiteCommand("UPDATE users SET lastip=@ip, lasttime=@time WHERE name=@name COLLATE NOCASE", _db);
131 | _logUser.Parameters.Add("@ip", DbType.String);
132 | _logUser.Parameters.Add("@time", DbType.Int64);
133 | _logUser.Parameters.Add("@name", DbType.String);
134 |
135 | _logUserUpdateCountry = new SQLiteCommand("UPDATE users SET country=@country, lastip=@ip, lasttime=@time WHERE name=@name COLLATE NOCASE", _db);
136 | _logUserUpdateCountry.Parameters.Add("@country", DbType.String);
137 | _logUserUpdateCountry.Parameters.Add("@ip", DbType.String);
138 | _logUserUpdateCountry.Parameters.Add("@time", DbType.Int64);
139 | _logUserUpdateCountry.Parameters.Add("@name", DbType.String);
140 | }
141 |
142 | private static bool CloseHandler(CtrlType sig)
143 | {
144 | if (_instance != null)
145 | _instance.Dispose();
146 |
147 | switch (sig) {
148 | case CtrlType.CTRL_C_EVENT:
149 | case CtrlType.CTRL_LOGOFF_EVENT:
150 | case CtrlType.CTRL_SHUTDOWN_EVENT:
151 | case CtrlType.CTRL_CLOSE_EVENT:
152 | default:
153 | return false;
154 | }
155 | }
156 |
157 | public void Dispose()
158 | {
159 | Dispose(true);
160 | GC.SuppressFinalize(this);
161 | }
162 |
163 | protected virtual void Dispose(bool disposing)
164 | {
165 | try {
166 | if (disposing) {
167 | if (_getUsersByName != null) {
168 | _getUsersByName.Dispose();
169 | _getUsersByName = null;
170 | }
171 | if (_getUsersByEmail != null) {
172 | _getUsersByEmail.Dispose();
173 | _getUsersByEmail = null;
174 | }
175 | if (_updateUser != null) {
176 | _updateUser.Dispose();
177 | _updateUser = null;
178 | }
179 | if (_createUser != null) {
180 | _createUser.Dispose();
181 | _createUser = null;
182 | }
183 | if (_countUsers != null) {
184 | _countUsers.Dispose();
185 | _countUsers = null;
186 | }
187 | if (_logUser != null) {
188 | _logUser.Dispose();
189 | _logUser = null;
190 | }
191 | if (_logUserUpdateCountry != null) {
192 | _logUserUpdateCountry.Dispose();
193 | _logUserUpdateCountry = null;
194 | }
195 | if (_db != null) {
196 | _db.Close();
197 | _db.Dispose();
198 | _db = null;
199 | }
200 | _instance = null;
201 |
202 | if (_instance != null) {
203 | _instance.Dispose();
204 | _instance = null;
205 | }
206 | }
207 | } catch (Exception) {
208 | }
209 | }
210 |
211 | ~LoginDatabase()
212 | {
213 | Dispose(false);
214 | }
215 |
216 | public static bool IsInitialized()
217 | {
218 | return _instance != null && _instance._db != null;
219 | }
220 |
221 | public static LoginDatabase Instance
222 | {
223 | get
224 | {
225 | if (_instance == null) {
226 | throw new ArgumentNullException("Instance", "Initialize() must be called first");
227 | }
228 |
229 | return _instance;
230 | }
231 | }
232 |
233 | public Dictionary GetData(string username)
234 | {
235 | if (_db == null)
236 | return null;
237 |
238 | if (!UserExists(username))
239 | return null;
240 |
241 | lock (_dbLock) {
242 | _getUsersByName.Parameters["@name"].Value = username;
243 |
244 | using (SQLiteDataReader reader = _getUsersByName.ExecuteReader()) {
245 | if (reader.Read()) {
246 | // only go once
247 |
248 | Dictionary data = new Dictionary();
249 | data.Add("id", reader["id"]);
250 | data.Add("name", username);
251 | data.Add("passwordenc", reader["password"]);
252 | data.Add("email", reader["email"]);
253 | data.Add("country", reader["country"]);
254 | data.Add("userid", (Int64)reader["id"] + UserIdOffset);
255 | data.Add("profileid", (Int64)reader["id"] + ProfileIdOffset);
256 | data.Add("session", reader["session"]);
257 |
258 | return data;
259 | }
260 | }
261 | }
262 |
263 | return null;
264 | }
265 |
266 | public List> GetData(string email, string passwordEncrypted)
267 | {
268 | if (_db == null)
269 | return null;
270 |
271 | List> values = new List>();
272 |
273 | lock (_dbLock) {
274 | _getUsersByEmail.Parameters["@email"].Value = email.ToLowerInvariant();
275 | _getUsersByEmail.Parameters["@password"].Value = passwordEncrypted;
276 |
277 | using (SQLiteDataReader reader = _getUsersByEmail.ExecuteReader()) {
278 | while (reader.Read()) {
279 | // loop through all nicks associated with that email/pass combo
280 |
281 | Dictionary data = new Dictionary();
282 | data.Add("id", reader["id"]);
283 | data.Add("name", reader["name"]);
284 | data.Add("passwordenc", passwordEncrypted);
285 | data.Add("email", email);
286 | data.Add("country", reader["country"]);
287 | data.Add("userid", (Int64)reader["id"] + UserIdOffset);
288 | data.Add("profileid", (Int64)reader["id"] + ProfileIdOffset);
289 | data.Add("session", reader["session"]);
290 |
291 | values.Add(data);
292 | }
293 | }
294 | }
295 |
296 | return values;
297 | }
298 |
299 | public void SetData(string name, Dictionary data)
300 | {
301 | var oldValues = GetData(name);
302 |
303 | if (oldValues == null)
304 | return;
305 |
306 | lock (_dbLock) {
307 | _updateUser.Parameters["@pass"].Value = data.ContainsKey("passwordenc") ? data["passwordenc"] : oldValues["passwordenc"];
308 | _updateUser.Parameters["@email"].Value = data.ContainsKey("email") ? ((string)data["email"]).ToLowerInvariant() : oldValues["email"];
309 | _updateUser.Parameters["@country"].Value = data.ContainsKey("country") ? data["country"].ToString().ToUpperInvariant() : oldValues["country"];
310 | _updateUser.Parameters["@session"].Value = data.ContainsKey("session") ? data["session"] : oldValues["session"];
311 | _updateUser.Parameters["@name"].Value = name;
312 |
313 | _updateUser.ExecuteNonQuery();
314 | }
315 | }
316 |
317 | public void LogLogin(string name, IPAddress address)
318 | {
319 | if (_db == null)
320 | return;
321 |
322 | var data = GetData(name);
323 | if (data == null)
324 | return;
325 |
326 | // for some reason, when creating an account, sometimes the country doesn't get set
327 | // it gets set to ?? which is the default. probably the message didn't make it through or something
328 | // but anyway, if it doesn't match what's in the db, then we want to update the country field to the user's
329 | // country as defined by IP address
330 | // to save on db writes, we do this as part of logging the ip/time
331 |
332 | string country = "??";
333 | if (GeoIP.Instance != null && GeoIP.Instance.Reader != null) {
334 | try {
335 | country = GeoIP.Instance.Reader.Omni(address.ToString()).Country.IsoCode.ToUpperInvariant();
336 | } catch (Exception) {
337 | }
338 | }
339 |
340 | if (country != "??" && !data["country"].ToString().Equals(country, StringComparison.InvariantCultureIgnoreCase)) {
341 | lock (_dbLock) {
342 |
343 | _logUserUpdateCountry.Parameters["@country"].Value = country;
344 | _logUserUpdateCountry.Parameters["@ip"].Value = address.ToString();
345 | _logUserUpdateCountry.Parameters["@time"].Value = DateTime.UtcNow.ToEpochInt();
346 | _logUserUpdateCountry.Parameters["@name"].Value = name;
347 |
348 | _logUserUpdateCountry.ExecuteNonQuery();
349 | }
350 | } else {
351 | lock (_dbLock) {
352 | _logUser.Parameters["@ip"].Value = address.ToString();
353 | _logUser.Parameters["@time"].Value = DateTime.UtcNow.ToEpochInt();
354 | _logUser.Parameters["@name"].Value = name;
355 |
356 | _logUser.ExecuteNonQuery();
357 | }
358 | }
359 | }
360 |
361 | public void CreateUser(string username, string passwordEncrypted, string email, string country, IPAddress address)
362 | {
363 | if (_db == null)
364 | return;
365 |
366 | if (UserExists(username))
367 | return;
368 |
369 | lock (_dbLock) {
370 | _createUser.Parameters["@name"].Value = username;
371 | _createUser.Parameters["@pass"].Value = passwordEncrypted;
372 | _createUser.Parameters["@email"].Value = email.ToLowerInvariant();
373 | _createUser.Parameters["@country"].Value = country.ToUpperInvariant();
374 | _createUser.Parameters["@ip"].Value = address.ToString();
375 |
376 | _createUser.ExecuteNonQuery();
377 | }
378 | }
379 |
380 | public bool UserExists(string username)
381 | {
382 | bool existing = false;
383 |
384 | if (_db == null)
385 | return false;
386 |
387 | lock (_dbLock) {
388 | _countUsers.Parameters["@name"].Value = username;
389 |
390 | using (SQLiteDataReader reader = _countUsers.ExecuteReader()) {
391 | if (reader.Read()) {
392 | // only go once
393 |
394 | if (reader.FieldCount == 1 && (Int64)reader[0] == 1) {
395 | existing = true;
396 | }
397 | }
398 | }
399 | }
400 |
401 | return existing;
402 | }
403 |
404 | [DllImport("Kernel32")]
405 | private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
406 |
407 | private enum CtrlType
408 | {
409 | CTRL_C_EVENT = 0,
410 | CTRL_BREAK_EVENT = 1,
411 | CTRL_CLOSE_EVENT = 2,
412 | CTRL_LOGOFF_EVENT = 5,
413 | CTRL_SHUTDOWN_EVENT = 6
414 | }
415 | }
416 | }
417 |
--------------------------------------------------------------------------------
/PRMasterServer/Servers/ServerListReport.cs:
--------------------------------------------------------------------------------
1 | using Alivate;
2 | using MaxMind.GeoIP2;
3 | using PRMasterServer.Data;
4 | using System;
5 | using System.Collections.Concurrent;
6 | using System.Collections.Generic;
7 | using System.Globalization;
8 | using System.IO;
9 | using System.Linq;
10 | using System.Net;
11 | using System.Net.Sockets;
12 | using System.Reflection;
13 | using System.Text;
14 | using System.Text.RegularExpressions;
15 | using System.Threading;
16 |
17 | namespace PRMasterServer.Servers
18 | {
19 | internal class ServerListReport
20 | {
21 | private const string Category = "ServerReport";
22 |
23 | public Action Log = (x, y) => { };
24 | public Action LogError = (x, y) => { };
25 |
26 | public readonly ConcurrentDictionary Servers;
27 |
28 | private string[] ModWhitelist;
29 | private IPAddress[] PlasmaServers;
30 |
31 | public Thread Thread;
32 |
33 | private const int BufferSize = 65535;
34 | private Socket _socket;
35 | private SocketAsyncEventArgs _socketReadEvent;
36 | private byte[] _socketReceivedBuffer;
37 |
38 | // 09 then 4 00's then battlefield2
39 | private readonly byte[] _initialMessage = new byte[] { 0x09, 0x00, 0x00, 0x00, 0x00, 0x62, 0x61, 0x74, 0x74, 0x6c, 0x65, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x32, 0x00 };
40 |
41 | public ServerListReport(IPAddress listen, ushort port, Action log, Action logError)
42 | {
43 | Log = log;
44 | LogError = logError;
45 |
46 | GeoIP.Initialize(log, Category);
47 |
48 | Servers = new ConcurrentDictionary();
49 |
50 | Thread = new Thread(StartServer) {
51 | Name = "Server Reporting Socket Thread"
52 | };
53 | Thread.Start(new AddressInfo() {
54 | Address = listen,
55 | Port = port
56 | });
57 |
58 | new Thread(StartCleanup) {
59 | Name = "Server Reporting Cleanup Thread"
60 | }.Start();
61 |
62 | new Thread(StartDynamicInfoReload) {
63 | Name = "Dynamic Info Reload Thread"
64 | }.Start();
65 | }
66 |
67 | public void Dispose()
68 | {
69 | Dispose(true);
70 | GC.SuppressFinalize(this);
71 | }
72 |
73 | protected virtual void Dispose(bool disposing)
74 | {
75 | try {
76 | if (disposing) {
77 | if (_socket != null) {
78 | _socket.Close();
79 | _socket.Dispose();
80 | _socket = null;
81 | }
82 | }
83 | } catch (Exception) {
84 | }
85 | }
86 |
87 | ~ServerListReport()
88 | {
89 | Dispose(false);
90 | }
91 |
92 | private void StartServer(object parameter)
93 | {
94 | AddressInfo info = (AddressInfo)parameter;
95 |
96 | Log(Category, "Starting Server List Reporting");
97 |
98 | try {
99 | _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) {
100 | SendTimeout = 5000,
101 | ReceiveTimeout = 5000,
102 | SendBufferSize = BufferSize,
103 | ReceiveBufferSize = BufferSize
104 | };
105 |
106 | _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true);
107 | _socket.Bind(new IPEndPoint(info.Address, info.Port));
108 |
109 | _socketReadEvent = new SocketAsyncEventArgs() {
110 | RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0)
111 | };
112 | _socketReceivedBuffer = new byte[BufferSize];
113 | _socketReadEvent.SetBuffer(_socketReceivedBuffer, 0, BufferSize);
114 | _socketReadEvent.Completed += OnDataReceived;
115 | } catch (Exception e) {
116 | LogError(Category, String.Format("Unable to bind Server List Reporting to {0}:{1}", info.Address, info.Port));
117 | LogError(Category, e.ToString());
118 | return;
119 | }
120 |
121 | WaitForData();
122 | }
123 |
124 | private void StartCleanup(object parameter)
125 | {
126 | while (true) {
127 | foreach (var key in Servers.Keys) {
128 | GameServer value;
129 |
130 | if (Servers.TryGetValue(key, out value)) {
131 | if (value.LastPing < DateTime.UtcNow - TimeSpan.FromSeconds(30)) {
132 | Log(Category, String.Format("Removing old server at: {0}", key));
133 |
134 | GameServer temp;
135 | Servers.TryRemove(key, out temp);
136 | }
137 | }
138 | }
139 |
140 | Thread.Sleep(10000);
141 | }
142 | }
143 |
144 | private void StartDynamicInfoReload(object obj)
145 | {
146 | while (true) {
147 | // the modwhitelist.txt file is for only allowing servers running certain mods to register with the master server
148 | // by default, this is pr or pr_* (it's really pr!_%, since % is wildcard, _ is placeholder, ! is escape)
149 | // # is for comments
150 | // you either want to utilize modwhitelist.txt or hardcode the default if you're using another mod...
151 | // put each mod name on a new line
152 | // to allow all mods, just put a single %
153 | if (File.Exists("modwhitelist.txt")) {
154 | Log(Category, "Loading mod whitelist");
155 | ModWhitelist = File.ReadAllLines("modwhitelist.txt").Where(x => !String.IsNullOrWhiteSpace(x) && !x.Trim().StartsWith("#")).ToArray();
156 | } else {
157 | ModWhitelist = new string[] { "pr", "pr!_%" };
158 | }
159 |
160 | // plasma servers (bf2_plasma = 1) makes servers show up in green in the server list in bf2's main menu (or blue in pr's menu)
161 | // this could be useful to promote servers and make them stand out, sponsored servers, special events, stuff like that
162 | // put in the ip address of each server on a new line in plasmaservers.txt, and make them stand out
163 | if (File.Exists("plasmaservers.txt")) {
164 | Log(Category, "Loading plasma servers");
165 | PlasmaServers = File.ReadAllLines("plasmaservers.txt").Select(x => {
166 | IPAddress address;
167 | if (IPAddress.TryParse(x, out address))
168 | return address;
169 | else
170 | return null;
171 | }).Where(x => x != null).ToArray();
172 | } else {
173 | PlasmaServers = new IPAddress[0];
174 | }
175 |
176 | GC.Collect();
177 |
178 | Thread.Sleep(5 * 60 * 1000);
179 | }
180 | }
181 |
182 | private void WaitForData()
183 | {
184 | Thread.Sleep(10);
185 | GC.Collect();
186 |
187 | try {
188 | _socket.ReceiveFromAsync(_socketReadEvent);
189 | } catch (SocketException e) {
190 | LogError(Category, "Error receiving data");
191 | LogError(Category, e.ToString());
192 | return;
193 | }
194 | }
195 |
196 | private void OnDataReceived(object sender, SocketAsyncEventArgs e)
197 | {
198 | try {
199 | IPEndPoint remote = (IPEndPoint)e.RemoteEndPoint;
200 |
201 | byte[] receivedBytes = new byte[e.BytesTransferred];
202 | Array.Copy(e.Buffer, e.Offset, receivedBytes, 0, e.BytesTransferred);
203 |
204 | // there by a bunch of different message formats...
205 |
206 | if (receivedBytes.SequenceEqual(_initialMessage)) {
207 | // the initial message is basically the gamename, 0x09 0x00 0x00 0x00 0x00 battlefield2
208 | // reply back a good response
209 | byte[] response = new byte[] { 0xfe, 0xfd, 0x09, 0x00, 0x00, 0x00, 0x00 };
210 | _socket.SendTo(response, remote);
211 | } else if (receivedBytes.Length > 5 && receivedBytes[0] == 0x03) {
212 | // this is where server details come in, it starts with 0x03, it happens every 60 seconds or so
213 |
214 | byte[] uniqueId = new byte[4];
215 | Array.Copy(receivedBytes, 1, uniqueId, 0, 4);
216 |
217 | if (!ParseServerDetails(remote, receivedBytes.Skip(5).ToArray())) {
218 | // this should be some sort of proper encrypted challenge, but for now i'm just going to hard code it because I don't know how the encryption works...
219 | byte[] response = new byte[] { 0xfe, 0xfd, 0x01, uniqueId[0], uniqueId[1], uniqueId[2], uniqueId[3], 0x44, 0x3d, 0x73, 0x7e, 0x6a, 0x59, 0x30, 0x30, 0x37, 0x43, 0x39, 0x35, 0x41, 0x42, 0x42, 0x35, 0x37, 0x34, 0x43, 0x43, 0x00 };
220 | _socket.SendTo(response, remote);
221 | }
222 | } else if (receivedBytes.Length > 5 && receivedBytes[0] == 0x01) {
223 | // this is a challenge response, it starts with 0x01
224 |
225 | byte[] uniqueId = new byte[4];
226 | Array.Copy(receivedBytes, 1, uniqueId, 0, 4);
227 |
228 | // confirm against the hardcoded challenge
229 | byte[] validate = new byte[] { 0x72, 0x62, 0x75, 0x67, 0x4a, 0x34, 0x34, 0x64, 0x34, 0x7a, 0x2b, 0x66, 0x61, 0x78, 0x30, 0x2f, 0x74, 0x74, 0x56, 0x56, 0x46, 0x64, 0x47, 0x62, 0x4d, 0x7a, 0x38, 0x41, 0x00 };
230 | byte[] clientResponse = new byte[validate.Length];
231 | Array.Copy(receivedBytes, 5, clientResponse, 0, clientResponse.Length);
232 |
233 | // if we validate, reply back a good response
234 | if (clientResponse.SequenceEqual(validate)) {
235 | byte[] response = new byte[] { 0xfe, 0xfd, 0x0a, uniqueId[0], uniqueId[1], uniqueId[2], uniqueId[3] };
236 | _socket.SendTo(response, remote);
237 |
238 | AddValidServer(remote);
239 | }
240 | } else if (receivedBytes.Length == 5 && receivedBytes[0] == 0x08) {
241 | // this is a server ping, it starts with 0x08, it happens every 20 seconds or so
242 |
243 | byte[] uniqueId = new byte[4];
244 | Array.Copy(receivedBytes, 1, uniqueId, 0, 4);
245 |
246 | RefreshServerPing(remote);
247 | }
248 | } catch (Exception ex) {
249 | LogError(Category, ex.ToString());
250 | }
251 |
252 | WaitForData();
253 | }
254 |
255 | private void RefreshServerPing(IPEndPoint remote)
256 | {
257 | string key = String.Format("{0}:{1}", remote.Address, remote.Port);
258 | if (Servers.ContainsKey(key)) {
259 | GameServer value;
260 | if (Servers.TryGetValue(key, out value)) {
261 | value.LastPing = DateTime.UtcNow;
262 | Servers[key] = value;
263 | }
264 | }
265 | }
266 |
267 | private bool ParseServerDetails(IPEndPoint remote, byte[] data)
268 | {
269 | string key = String.Format("{0}:{1}", remote.Address, remote.Port);
270 | string receivedData = Encoding.UTF8.GetString(data);
271 |
272 | //Console.WriteLine(receivedData.Replace("\x00", "\\x00").Replace("\x02", "\\x02"));
273 |
274 | // split by 000 (info/player separator) and 002 (players/teams separator)
275 | // the players/teams separator is really 00, but because 00 may also be used elsewhere (an empty value for example), we hardcode it to 002
276 | // the 2 is the size of the teams, for BF2 this is always 2.
277 | string[] sections = receivedData.Split(new string[] { "\x00\x00\x00", "\x00\x00\x02" }, StringSplitOptions.None);
278 |
279 | //Console.WriteLine(sections.Length);
280 |
281 | if (sections.Length != 3 && !receivedData.EndsWith("\x00\x00"))
282 | return true; // true means we don't send back a response
283 |
284 | string serverVars = sections[0];
285 | //string playerVars = sections[1];
286 | //string teamVars = sections[2];
287 |
288 | string[] serverVarsSplit = serverVars.Split(new string[] { "\x00" }, StringSplitOptions.None);
289 |
290 | GameServer server = new GameServer() {
291 | Valid = false,
292 | IPAddress = remote.Address.ToString(),
293 | QueryPort = remote.Port,
294 | LastRefreshed = DateTime.UtcNow,
295 | LastPing = DateTime.UtcNow
296 | };
297 |
298 | // set the country based off ip address
299 | if (GeoIP.Instance == null || GeoIP.Instance.Reader == null) {
300 | server.country = "??";
301 | } else {
302 | try {
303 | server.country = GeoIP.Instance.Reader.Omni(server.IPAddress).Country.IsoCode.ToUpperInvariant();
304 | } catch (Exception e) {
305 | LogError(Category, e.ToString());
306 | server.country = "??";
307 | }
308 | }
309 |
310 | for (int i = 0; i < serverVarsSplit.Length - 1; i += 2) {
311 | PropertyInfo property = server.GetType().GetProperty(serverVarsSplit[i]);
312 |
313 | if (property == null)
314 | continue;
315 |
316 | if (property.Name == "hostname") {
317 | // strip consecutive whitespace from hostname
318 | property.SetValue(server, Regex.Replace(serverVarsSplit[i + 1], @"\s+", " ").Trim(), null);
319 | } else if (property.Name == "bf2_plasma") {
320 | // set plasma to true if the ip is in plasmaservers.txt
321 | if (PlasmaServers.Any(x => x.Equals(remote.Address)))
322 | property.SetValue(server, true, null);
323 | else
324 | property.SetValue(server, false, null);
325 | } else if (property.Name == "bf2_ranked") {
326 | // we're always a ranked server (helps for mods with a default bf2 main menu, and default filters wanting ranked servers)
327 | property.SetValue(server, true, null);
328 | } else if (property.Name == "bf2_pure") {
329 | // we're always a pure server
330 | property.SetValue(server, true, null);
331 | } else if (property.PropertyType == typeof(Boolean)) {
332 | // parse string to bool (values come in as 1 or 0)
333 | int value;
334 | if (Int32.TryParse(serverVarsSplit[i + 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) {
335 | property.SetValue(server, value != 0, null);
336 | }
337 | } else if (property.PropertyType == typeof(Int32)) {
338 | // parse string to int
339 | int value;
340 | if (Int32.TryParse(serverVarsSplit[i + 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) {
341 | property.SetValue(server, value, null);
342 | }
343 | } else if (property.PropertyType == typeof(Double)) {
344 | // parse string to double
345 | double value;
346 | if (Double.TryParse(serverVarsSplit[i + 1], NumberStyles.Float, CultureInfo.InvariantCulture, out value)) {
347 | property.SetValue(server, value, null);
348 | }
349 | } else if (property.PropertyType == typeof(String)) {
350 | // parse string to string
351 | property.SetValue(server, serverVarsSplit[i + 1], null);
352 | }
353 | }
354 |
355 | if (String.IsNullOrWhiteSpace(server.gamename) || !server.gamename.Equals("battlefield2", StringComparison.InvariantCultureIgnoreCase)) {
356 | // only allow servers with a gamename of battlefield2
357 | return true; // true means we don't send back a response
358 | } else if (String.IsNullOrWhiteSpace(server.gamevariant) || !ModWhitelist.ToList().Any(x => SQLMethods.EvaluateIsLike(server.gamevariant, x))) {
359 | // only allow servers with a gamevariant of those listed in modwhitelist.txt, or (pr || pr_*) by default
360 | return true; // true means we don't send back a response
361 | }
362 |
363 | // you've got to have all these properties in order for your server to be valid
364 | if (!String.IsNullOrWhiteSpace(server.hostname) &&
365 | !String.IsNullOrWhiteSpace(server.gamevariant) &&
366 | !String.IsNullOrWhiteSpace(server.gamever) &&
367 | !String.IsNullOrWhiteSpace(server.gametype) &&
368 | !String.IsNullOrWhiteSpace(server.mapname) &&
369 | server.hostport > 1024 && server.hostport <= UInt16.MaxValue &&
370 | server.maxplayers > 0) {
371 | server.Valid = true;
372 | }
373 |
374 | // if the server list doesn't contain this server, we need to return false in order to send a challenge
375 | // if the server replies back with the good challenge, it'll be added in AddValidServer
376 | if (!Servers.ContainsKey(key))
377 | return false;
378 |
379 | Servers.AddOrUpdate(key, server, (k, old) => {
380 | if (!old.Valid && server.Valid) {
381 | Log(Category, String.Format("Added new server at: {0}:{1} ({2}) ({3})", server.IPAddress, server.QueryPort, server.country, server.gamevariant));
382 | }
383 |
384 | return server;
385 | });
386 |
387 | return true;
388 | }
389 |
390 | private void AddValidServer(IPEndPoint remote)
391 | {
392 | string key = String.Format("{0}:{1}", remote.Address, remote.Port);
393 | GameServer server = new GameServer() {
394 | Valid = false,
395 | IPAddress = remote.Address.ToString(),
396 | QueryPort = remote.Port,
397 | LastRefreshed = DateTime.UtcNow,
398 | LastPing = DateTime.UtcNow
399 | };
400 |
401 | Servers.AddOrUpdate(key, server, (k, old) => {
402 | return server;
403 | });
404 | }
405 | }
406 | }
407 |
--------------------------------------------------------------------------------
/PRMasterServer/Servers/LoginServerMessages.cs:
--------------------------------------------------------------------------------
1 | using PRMasterServer.Data;
2 | using Reality.Net.Extensions;
3 | using Reality.Net.GameSpy.Servers;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Globalization;
7 | using System.Net;
8 | using System.Text;
9 |
10 | namespace PRMasterServer.Servers
11 | {
12 | internal class LoginServerMessages
13 | {
14 | private readonly static Random _random = new Random();
15 |
16 | public static byte[] GenerateServerChallenge(ref LoginSocketState state)
17 | {
18 | state.ServerChallenge = _random.GetString(10);
19 | string message = String.Format(@"\lc\1\challenge\{0}\id\1\final\", state.ServerChallenge);
20 | return DataFunctions.StringToBytes(message);
21 | }
22 |
23 | public static byte[] SendProof(ref LoginSocketState state, Dictionary keyValues)
24 | {
25 | string response = String.Empty;
26 |
27 | int requiredValues = 0;
28 |
29 | state.Name = String.Empty;
30 |
31 | if (keyValues.ContainsKey("uniquenick")) {
32 | state.Name = keyValues["uniquenick"];
33 | requiredValues++;
34 | }
35 |
36 | if (keyValues.ContainsKey("challenge")) {
37 | state.ClientChallenge = keyValues["challenge"];
38 | requiredValues++;
39 | }
40 |
41 | if (keyValues.ContainsKey("response")) {
42 | response = keyValues["response"];
43 | requiredValues++;
44 | }
45 |
46 | if (requiredValues != 3)
47 | return DataFunctions.StringToBytes(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\");
48 |
49 | var clientData = LoginDatabase.Instance.GetData(state.Name);
50 |
51 | if (clientData != null) {
52 | state.PasswordEncrypted = (string)clientData["passwordenc"];
53 |
54 | if (response == GenerateResponseValue(ref state)) {
55 | ushort session = GenerateSession(state.Name);
56 |
57 | string proof = String.Format(@"\lc\2\sesskey\{0}\proof\{1}\userid\{2}\profileid\{3}\uniquenick\{4}\lt\{5}\id\1\final\",
58 | session,
59 | GenerateProofValue(state),
60 | clientData["userid"],
61 | clientData["profileid"],
62 | state.Name,
63 | _random.GetString(22, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][") + "__");
64 |
65 | /*state.Session = session.ToString();
66 | Dictionary updateClientData = new Dictionary() {
67 | { "session", session }
68 | };
69 | LoginDatabase.Instance.SetData(state.Name, updateClientData);*/
70 |
71 | LoginDatabase.Instance.LogLogin(state.Name, ((IPEndPoint)state.Socket.RemoteEndPoint).Address);
72 |
73 | state.State++;
74 | return DataFunctions.StringToBytes(proof);
75 | } else {
76 | return DataFunctions.StringToBytes(@"\error\\err\260\fatal\\errmsg\The password provided is incorrect.\id\1\final\");
77 | }
78 | } else {
79 | return DataFunctions.StringToBytes(String.Format(@"\error\\err\265\fatal\\errmsg\Username [{0}] doesn't exist!\id\1\final\", state.Name));
80 | }
81 | }
82 |
83 | public static byte[] SendProfile(ref LoginSocketState state, Dictionary keyValues, bool retrieve)
84 | {
85 | var clientData = LoginDatabase.Instance.GetData(state.Name);
86 |
87 | if (clientData == null) {
88 | return DataFunctions.StringToBytes(String.Format(@"\error\\err\265\fatal\\errmsg\Username [{0}] doesn't exist!\id\1\final\", state.Name));
89 | }
90 |
91 | string message = String.Format(
92 | @"\pi\\profileid\{0}\nick\{1}\userid\{2}\email\{3}\sig\{4}\uniquenick\{5}\pid\{6}" +
93 | @"\firstname\lastname\countrycode\{7}\birthday\{8}\lon\{9}\lat\{10}\loc\id\{11}\final\",
94 | clientData["profileid"],
95 | state.Name,
96 | clientData["userid"],
97 | clientData["email"],
98 | _random.GetString(32, "0123456789abcdef"),
99 | state.Name,
100 | 0,
101 | clientData["country"],
102 | 16844722,
103 | "0.000000",
104 | "0.000000",
105 | retrieve ? 5 : 2
106 | );
107 |
108 | if (!retrieve)
109 | state.State++;
110 |
111 | return DataFunctions.StringToBytes(message);
112 | }
113 |
114 | public static void UpdateProfile(ref LoginSocketState state, Dictionary keyValues)
115 | {
116 | string country = "??";
117 | if (keyValues.ContainsKey("countrycode")) {
118 | country = keyValues["countrycode"].ToUpperInvariant();
119 | }
120 |
121 | Dictionary clientData = new Dictionary() {
122 | { "country", country }
123 | };
124 |
125 | LoginDatabase.Instance.SetData(state.Name, clientData);
126 | state.State++;
127 | }
128 |
129 | public static void Logout(ref LoginSocketState state, Dictionary keyValues)
130 | {
131 | // we're not doing anything about session, so no need to reset it back to 0...
132 | // maybe one day though...
133 | /*Dictionary clientData = new Dictionary() {
134 | { "session", (Int64)0 }
135 | };
136 | LoginDatabase.Instance.SetData(state.Name, clientData);*/
137 | state.Dispose();
138 | }
139 |
140 | public static byte[] NewUser(ref LoginSocketState state, Dictionary keyValues)
141 | {
142 | string message = String.Empty;
143 |
144 | if (keyValues.ContainsKey("nick")) {
145 | state.Name = keyValues["nick"];
146 | } else {
147 | return DataFunctions.StringToBytes(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\");
148 | }
149 |
150 | if (keyValues.ContainsKey("email")) {
151 | state.Email = keyValues["email"];
152 | } else {
153 | return DataFunctions.StringToBytes(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\");
154 | }
155 |
156 | if (keyValues.ContainsKey("passwordenc")) {
157 | state.PasswordEncrypted = keyValues["passwordenc"];
158 | } else {
159 | return DataFunctions.StringToBytes(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\");
160 | }
161 |
162 | if (LoginDatabase.Instance.UserExists(state.Name)) {
163 | return DataFunctions.StringToBytes(@"\error\\err\516\fatal\\errmsg\This account name is already in use!\id\1\final\");
164 | } else {
165 | string password = DecryptPassword(state.PasswordEncrypted);
166 |
167 | LoginDatabase.Instance.CreateUser(state.Name, password.ToMD5(), state.Email, "??", ((IPEndPoint)state.Socket.RemoteEndPoint).Address);
168 |
169 | var clientData = LoginDatabase.Instance.GetData(state.Name);
170 |
171 | if (clientData == null) {
172 | return DataFunctions.StringToBytes(@"\error\\err\0\fatal\\errmsg\Error creating account!\id\1\final\");
173 | }
174 |
175 | message = String.Format(@"\nur\\userid\{0}\profileid\{1}\id\1\final\", clientData["userid"], clientData["profileid"]);
176 | }
177 |
178 | return DataFunctions.StringToBytes(message);
179 | }
180 |
181 | public static byte[] SendKeepAlive()
182 | {
183 | return DataFunctions.StringToBytes(@"\ka\\final\");
184 | }
185 |
186 | public static byte[] SendHeartbeat()
187 | {
188 | return DataFunctions.StringToBytes(String.Format(@"\lt\{0}\final\", _random.GetString(22, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][") + "__"));
189 | }
190 |
191 | internal static byte[] SendNicks(ref LoginSocketState state, Dictionary keyValues)
192 | {
193 | if (!keyValues.ContainsKey("email") || (!keyValues.ContainsKey("passenc") && !keyValues.ContainsKey("pass"))) {
194 | return DataFunctions.StringToBytes(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\");
195 | }
196 |
197 | string password = String.Empty;
198 | if (keyValues.ContainsKey("passenc")) {
199 | password = DecryptPassword(keyValues["passenc"]);
200 | } else if (keyValues.ContainsKey("pass")) {
201 | password = keyValues["pass"];
202 | }
203 |
204 | password = password.ToMD5();
205 |
206 | var clientData = LoginDatabase.Instance.GetData(keyValues["email"], password);
207 |
208 | if (clientData == null) {
209 | return DataFunctions.StringToBytes(@"\error\\err\551\fatal\\errmsg\Unable to get any associated profiles.\id\1\final\");
210 | }
211 |
212 | List nicks = new List();
213 | foreach (var client in clientData) {
214 | nicks.Add((string)client["name"]);
215 | }
216 |
217 | if (nicks.Count == 0) {
218 | return DataFunctions.StringToBytes(@"\nr\0\ndone\\final\");
219 | }
220 |
221 | state.State++;
222 | return DataFunctions.StringToBytes(GenerateNicks(nicks.ToArray()));
223 | }
224 |
225 | private static string GenerateNicks(string[] nicks)
226 | {
227 | string message = @"\nr\" + nicks.Length;
228 | for (int i = 0; i < nicks.Length; i++) {
229 | message += String.Format(@"\nick\{0}\uniquenick\{0}", nicks[i]);
230 | }
231 | message += @"\ndone\final\";
232 | return message;
233 | }
234 |
235 | internal static byte[] SendCheck(ref LoginSocketState state, Dictionary keyValues)
236 | {
237 | string name = String.Empty;
238 |
239 | if (String.IsNullOrWhiteSpace(name)) {
240 | if (keyValues.ContainsKey("uniquenick")) {
241 | name = keyValues["uniquenick"];
242 | }
243 | }
244 | if (String.IsNullOrWhiteSpace(name)) {
245 | if (keyValues.ContainsKey("nick")) {
246 | name = keyValues["nick"];
247 | }
248 | }
249 | if (String.IsNullOrWhiteSpace(name)) {
250 | return DataFunctions.StringToBytes(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\");
251 | }
252 |
253 | var clientData = LoginDatabase.Instance.GetData(name);
254 |
255 | if (clientData == null) {
256 | return DataFunctions.StringToBytes(String.Format(@"\error\\err\265\fatal\\errmsg\Username [{0}] doesn't exist!\id\1\final\", name));
257 | }
258 |
259 | string message = String.Format(@"\cur\0\pid\{0}\final\", clientData["profileid"]);
260 |
261 | return DataFunctions.StringToBytes(message);
262 | }
263 |
264 | private static string GenerateProofValue(LoginSocketState state)
265 | {
266 | string value = state.PasswordEncrypted;
267 | value += new String(' ', 48);
268 | value += state.Name;
269 | value += state.ServerChallenge;
270 | value += state.ClientChallenge;
271 | value += state.PasswordEncrypted;
272 |
273 | return value.ToMD5();
274 | }
275 |
276 | private static string GenerateResponseValue(ref LoginSocketState state)
277 | {
278 | string value = state.PasswordEncrypted;
279 | value += new String(' ', 48);
280 | value += state.Name;
281 | value += state.ClientChallenge;
282 | value += state.ServerChallenge;
283 | value += state.PasswordEncrypted;
284 |
285 | return value.ToMD5();
286 | }
287 |
288 | private static ushort GenerateSession(string name)
289 | {
290 | ushort[] crc_table = new ushort[256] {
291 | 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
292 | 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
293 | 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
294 | 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
295 | 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
296 | 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
297 | 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
298 | 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
299 | 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
300 | 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
301 | 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
302 | 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
303 | 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
304 | 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
305 | 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
306 | 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
307 | 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
308 | 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
309 | 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
310 | 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
311 | 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
312 | 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
313 | 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
314 | 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
315 | 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
316 | 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
317 | 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
318 | 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
319 | 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
320 | 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
321 | 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
322 | 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
323 | };
324 |
325 | int len = name.Length;
326 | int nameIndex = 0;
327 |
328 | ushort session = 0;
329 | while (len-- != 0) {
330 | session = (ushort)(crc_table[((name[nameIndex] ^ session) & 0xff) % 256] ^ (session >> 8));
331 | nameIndex++;
332 | }
333 |
334 | return session;
335 | }
336 |
337 | private static string DecryptPassword(string password)
338 | {
339 | string decrypted = gsBase64Decode(password, password.Length);
340 | gsEncode(ref decrypted);
341 | return decrypted;
342 | }
343 |
344 | public static int gsEncode(ref string password)
345 | {
346 | byte[] pass = DataFunctions.StringToBytes(password);
347 |
348 | int i;
349 | int a;
350 | int c;
351 | int d;
352 | int num = 0x79707367; // "gspy"
353 | int passlen = pass.Length;
354 |
355 | if (num == 0)
356 | num = 1;
357 | else
358 | num &= 0x7fffffff;
359 |
360 | for (i = 0; i < passlen; i++) {
361 | d = 0xff;
362 | c = 0;
363 | d -= c;
364 | if (d != 0) {
365 | num = gsLame(num);
366 | a = num % d;
367 | a += c;
368 | } else
369 | a = c;
370 |
371 | pass[i] ^= (byte)(a % 256);
372 | }
373 |
374 | password = DataFunctions.BytesToString(pass);
375 | return passlen;
376 | }
377 |
378 | private static int gsLame(int num)
379 | {
380 | int a;
381 | int c = (num >> 16) & 0xffff;
382 |
383 | a = num & 0xffff;
384 | c *= 0x41a7;
385 | a *= 0x41a7;
386 | a += ((c & 0x7fff) << 16);
387 |
388 | if (a < 0) {
389 | a &= 0x7fffffff;
390 | a++;
391 | }
392 |
393 | a += (c >> 15);
394 |
395 | if (a < 0) {
396 | a &= 0x7fffffff;
397 | a++;
398 | }
399 |
400 | return a;
401 | }
402 |
403 | private static string gsBase64Decode(string s, int size)
404 | {
405 | byte[] data = DataFunctions.StringToBytes(s);
406 |
407 | int len;
408 | int xlen;
409 | int a = 0;
410 | int b = 0;
411 | int c = 0;
412 | int step;
413 | int limit;
414 | int y = 0;
415 | int z = 0;
416 |
417 | byte[] buff;
418 | byte[] p;
419 |
420 | char[] basechars = new char[128] { // supports also the Gamespy base64
421 | '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00',
422 | '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00',
423 | '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x3e', '\x00', '\x00', '\x00', '\x3f',
424 | '\x34', '\x35', '\x36', '\x37', '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00',
425 | '\x00', '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e',
426 | '\x0f', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x3e', '\x00', '\x3f', '\x00', '\x00',
427 | '\x00', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f', '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27', '\x28',
428 | '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f', '\x30', '\x31', '\x32', '\x33', '\x00', '\x00', '\x00', '\x00', '\x00'
429 | };
430 |
431 | if (size <= 0)
432 | len = data.Length;
433 | else
434 | len = size;
435 |
436 | xlen = ((len >> 2) * 3) + 1;
437 | buff = new byte[xlen % 256];
438 | if (buff.Length == 0) return null;
439 |
440 | p = buff;
441 | limit = data.Length + len;
442 |
443 | for (step = 0; ; step++) {
444 | do {
445 | if (z >= limit) {
446 | c = 0;
447 | break;
448 | }
449 | if (z < data.Length)
450 | c = data[z];
451 | else
452 | c = 0;
453 | z++;
454 | if ((c == '=') || (c == '_')) {
455 | c = 0;
456 | break;
457 | }
458 | } while (c != 0 && ((c <= (byte)' ') || (c > 0x7f)));
459 | if (c == 0) break;
460 |
461 | switch (step & 3) {
462 | case 0:
463 | a = basechars[c];
464 | break;
465 | case 1:
466 | b = basechars[c];
467 | p[y++] = (byte)(((a << 2) | (b >> 4)) % 256);
468 | break;
469 | case 2:
470 | a = basechars[c];
471 | p[y++] = (byte)((((b & 15) << 4) | (a >> 2)) % 256);
472 | break;
473 | case 3:
474 | p[y++] = (byte)((((a & 3) << 6) | basechars[c]) % 256);
475 | break;
476 | default:
477 | break;
478 | }
479 | }
480 | p[y] = 0;
481 |
482 | len = p.Length - buff.Length;
483 |
484 | if (size != 0)
485 | size = len;
486 |
487 | if ((len + 1) != xlen)
488 | if (buff.Length == 0) return null;
489 |
490 | return DataFunctions.BytesToString(buff).Substring(0, y);
491 | }
492 | }
493 | }
494 |
--------------------------------------------------------------------------------
/PRMasterServer/Servers/LoginServer.cs:
--------------------------------------------------------------------------------
1 | using PRMasterServer.Data;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Net;
5 | using System.Net.Sockets;
6 | using System.Text;
7 | using System.Threading;
8 |
9 | namespace PRMasterServer.Servers
10 | {
11 | internal class LoginServer
12 | {
13 | public const string Category = "Login";
14 |
15 | public Action Log = (x, y) => { };
16 | public Action LogError = (x, y) => { };
17 |
18 | public Thread ThreadClientManager;
19 | public Thread ThreadSearchManager;
20 |
21 | private static Socket _clientManagerSocket;
22 | private static Socket _searchManagerSocket;
23 |
24 | private readonly ManualResetEvent _clientManagerReset = new ManualResetEvent(false);
25 | private readonly ManualResetEvent _searchManagerReset = new ManualResetEvent(false);
26 |
27 | public LoginServer(IPAddress listen, ushort clientManagerPort, ushort searchManagerPort, Action log, Action logError)
28 | {
29 | ServicePointManager.SetTcpKeepAlive(true, 60 * 1000 * 10, 1000);
30 |
31 | Log = log;
32 | LogError = logError;
33 |
34 | ThreadClientManager = new Thread(StartServerClientManager) {
35 | Name = "Login Thread Client Manager"
36 | };
37 | ThreadClientManager.Start(new AddressInfo() {
38 | Address = listen,
39 | Port = clientManagerPort
40 | });
41 |
42 | ThreadSearchManager = new Thread(StartServerSearchManager) {
43 | Name = "Login Thread Search Manager"
44 | };
45 | ThreadSearchManager.Start(new AddressInfo() {
46 | Address = listen,
47 | Port = searchManagerPort
48 | });
49 | }
50 |
51 | public void Dispose()
52 | {
53 | Dispose(true);
54 | GC.SuppressFinalize(this);
55 | }
56 |
57 | protected virtual void Dispose(bool disposing)
58 | {
59 | try {
60 | if (disposing) {
61 | if (_clientManagerSocket != null) {
62 | _clientManagerSocket.Close();
63 | _clientManagerSocket.Dispose();
64 | _clientManagerSocket = null;
65 | }
66 | if (_searchManagerSocket != null) {
67 | _searchManagerSocket.Close();
68 | _searchManagerSocket.Dispose();
69 | _searchManagerSocket = null;
70 | }
71 | }
72 | } catch (Exception) {
73 | }
74 | }
75 |
76 | ~LoginServer()
77 | {
78 | Dispose(false);
79 | }
80 |
81 | private void StartServerClientManager(object parameter)
82 | {
83 | AddressInfo info = (AddressInfo)parameter;
84 |
85 | Log(Category, "Starting Login Server ClientManager");
86 |
87 | try {
88 | _clientManagerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) {
89 | SendTimeout = 30000,
90 | ReceiveTimeout = 30000,
91 | SendBufferSize = 8192,
92 | ReceiveBufferSize = 8192,
93 | Blocking = false
94 | };
95 |
96 | _clientManagerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true);
97 | _clientManagerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
98 | _clientManagerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false);
99 | _clientManagerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
100 |
101 | _clientManagerSocket.Bind(new IPEndPoint(info.Address, info.Port));
102 | _clientManagerSocket.Listen(10);
103 | } catch (Exception e) {
104 | LogError(Category, String.Format("Unable to bind Login Server ClientManager to {0}:{1}", info.Address, info.Port));
105 | LogError(Category, e.ToString());
106 | return;
107 | }
108 |
109 | while (true) {
110 | _clientManagerReset.Reset();
111 |
112 | LoginSocketState state = new LoginSocketState() {
113 | Type = LoginSocketState.SocketType.Client,
114 | Socket = _clientManagerSocket
115 | };
116 |
117 | _clientManagerSocket.BeginAccept(AcceptCallback, state);
118 | _clientManagerReset.WaitOne();
119 | }
120 | }
121 |
122 | private void StartServerSearchManager(object parameter)
123 | {
124 | AddressInfo info = (AddressInfo)parameter;
125 |
126 | Log(Category, "Starting Login Server SearchManager");
127 |
128 | try {
129 | _searchManagerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) {
130 | SendTimeout = 5000,
131 | ReceiveTimeout = 5000,
132 | SendBufferSize = 8192,
133 | ReceiveBufferSize = 8192,
134 | Blocking = false
135 | };
136 |
137 | _searchManagerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true);
138 | _searchManagerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
139 | _searchManagerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false);
140 | _searchManagerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
141 |
142 | _searchManagerSocket.Bind(new IPEndPoint(info.Address, info.Port));
143 | _searchManagerSocket.Listen(10);
144 | } catch (Exception e) {
145 | LogError(Category, String.Format("Unable to bind Login Server SearchManager to {0}:{1}", info.Address, info.Port));
146 | LogError(Category, e.ToString());
147 | return;
148 | }
149 |
150 | while (true) {
151 | _searchManagerReset.Reset();
152 |
153 | LoginSocketState state = new LoginSocketState() {
154 | Type = LoginSocketState.SocketType.Search,
155 | Socket = _searchManagerSocket
156 | };
157 |
158 | _searchManagerSocket.BeginAccept(AcceptCallback, state);
159 | _searchManagerReset.WaitOne();
160 | }
161 | }
162 |
163 | private void AcceptCallback(IAsyncResult ar)
164 | {
165 | LoginSocketState state = (LoginSocketState)ar.AsyncState;
166 |
167 | try {
168 | Socket client = state.Socket.EndAccept(ar);
169 |
170 | Thread.Sleep(1);
171 |
172 | if (state.Type == LoginSocketState.SocketType.Client)
173 | _clientManagerReset.Set();
174 | else if (state.Type == LoginSocketState.SocketType.Search)
175 | _searchManagerReset.Set();
176 |
177 | state.Socket = client;
178 |
179 | Log(Category, String.Format("[{0}] New Client: {1}:{2}", state.Type, ((IPEndPoint)state.Socket.RemoteEndPoint).Address, ((IPEndPoint)state.Socket.RemoteEndPoint).Port));
180 |
181 | if (state.Type == LoginSocketState.SocketType.Client) {
182 | // ClientManager server sends data first
183 | byte[] buffer = LoginServerMessages.GenerateServerChallenge(ref state);
184 | SendToClient(ref state, buffer);
185 |
186 | if (state != null) {
187 | state.State++;
188 | }
189 | } else if (state.Type == LoginSocketState.SocketType.Search) {
190 | // SearchManager server waits for data first
191 | }
192 | } catch (NullReferenceException) {
193 | if (state != null)
194 | state.Dispose();
195 | state = null;
196 | } catch (SocketException e) {
197 | LogError(Category, "Error accepting client");
198 | LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e));
199 | if (state != null)
200 | state.Dispose();
201 | state = null;
202 | return;
203 | }
204 |
205 | WaitForData(ref state);
206 | }
207 |
208 | public bool SendToClient(ref LoginSocketState state, byte[] data)
209 | {
210 | if (data == null || state == null || state.Socket == null)
211 | return false;
212 |
213 | try {
214 | if (state.SendCallback == null)
215 | state.SendCallback = OnSent;
216 |
217 | state.Socket.BeginSend(data, 0, data.Length, SocketFlags.None, state.SendCallback, state);
218 | return true;
219 | } catch (NullReferenceException) {
220 | if (state != null)
221 | state.Dispose();
222 | state = null;
223 | return false;
224 | } catch (SocketException e) {
225 | if (e.SocketErrorCode != SocketError.ConnectionAborted &&
226 | e.SocketErrorCode != SocketError.ConnectionReset) {
227 | LogError(Category, "Error sending data");
228 | LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e));
229 | }
230 | if (state != null)
231 | state.Dispose();
232 | state = null;
233 | return false;
234 | }
235 | }
236 |
237 | private void OnSent(IAsyncResult async)
238 | {
239 | LoginSocketState state = (LoginSocketState)async.AsyncState;
240 |
241 | if (state == null || state.Socket == null)
242 | return;
243 |
244 | try {
245 | int sent = state.Socket.EndSend(async);
246 | Log(Category, String.Format("[{0}] Sent {1} byte response to: {2}:{3}", state.Type, sent, ((IPEndPoint)state.Socket.RemoteEndPoint).Address, ((IPEndPoint)state.Socket.RemoteEndPoint).Port));
247 | } catch (NullReferenceException) {
248 | if (state != null)
249 | state.Dispose();
250 | state = null;
251 | } catch (SocketException e) {
252 | switch (e.SocketErrorCode) {
253 | case SocketError.ConnectionReset:
254 | case SocketError.Disconnecting:
255 | if (state != null)
256 | state.Dispose();
257 | state = null;
258 | return;
259 | default:
260 | LogError(Category, "Error sending data");
261 | LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e));
262 | if (state != null)
263 | state.Dispose();
264 | state = null;
265 | return;
266 | }
267 | }
268 | }
269 |
270 | private void WaitForData(ref LoginSocketState state)
271 | {
272 | Thread.Sleep(10);
273 |
274 | try {
275 | if (state.DataReceivedCallback == null)
276 | state.DataReceivedCallback = OnDataReceived;
277 |
278 | state.Socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, state.DataReceivedCallback, state);
279 | } catch (NullReferenceException) {
280 | if (state != null)
281 | state.Dispose();
282 | state = null;
283 | } catch (ObjectDisposedException) {
284 | if (state != null)
285 | state.Dispose();
286 | state = null;
287 | } catch (SocketException e) {
288 | if (e.SocketErrorCode == SocketError.NotConnected) {
289 | if (state != null)
290 | state.Dispose();
291 | state = null;
292 | return;
293 | }
294 |
295 | if (e.SocketErrorCode != SocketError.ConnectionAborted &&
296 | e.SocketErrorCode != SocketError.ConnectionReset) {
297 | LogError(Category, "Error receiving data");
298 | LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e));
299 | }
300 | if (state != null)
301 | state.Dispose();
302 | state = null;
303 | return;
304 | }
305 | }
306 |
307 | private void OnDataReceived(IAsyncResult async)
308 | {
309 | LoginSocketState state = (LoginSocketState)async.AsyncState;
310 |
311 | if (state == null || state.Socket == null)
312 | return;
313 |
314 | try {
315 | // receive data from the socket
316 | int received = state.Socket.EndReceive(async);
317 | if (received == 0) {
318 | // when EndReceive returns 0, it means the socket on the other end has been shut down.
319 | return;
320 | }
321 |
322 | // take what we received, and append it to the received data buffer
323 | state.ReceivedData.Append(Encoding.UTF8.GetString(state.Buffer, 0, received));
324 | string receivedData = state.ReceivedData.ToString();
325 |
326 | // does what we received contain the \final\ delimiter?
327 | if (receivedData.LastIndexOf(@"\final\") > -1) {
328 | state.ReceivedData.Clear();
329 |
330 | // lets split up the message based on the delimiter
331 | string[] messages = receivedData.Split(new string[] { @"\final\" }, StringSplitOptions.RemoveEmptyEntries);
332 |
333 | for (int i = 0; i < messages.Length; i++) {
334 | ParseMessage(ref state, messages[i]);
335 | }
336 | }
337 | } catch (ObjectDisposedException) {
338 | if (state != null)
339 | state.Dispose();
340 | state = null;
341 | return;
342 | } catch (SocketException e) {
343 | switch (e.SocketErrorCode) {
344 | case SocketError.ConnectionReset:
345 | case SocketError.Disconnecting:
346 | case SocketError.NotConnected:
347 | case SocketError.TimedOut:
348 | if (state != null)
349 | state.Dispose();
350 | state = null;
351 | return;
352 | default:
353 | LogError(Category, "Error receiving data");
354 | LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e));
355 | if (state != null)
356 | state.Dispose();
357 | state = null;
358 | return;
359 | }
360 | } catch (Exception e) {
361 | LogError(Category, "Error receiving data");
362 | LogError(Category, e.ToString());
363 | }
364 |
365 | // and we wait for more data...
366 | WaitForData(ref state);
367 | }
368 |
369 | private void ParseMessage(ref LoginSocketState state, string message)
370 | {
371 | string query;
372 | var keyValues = GetKeyValue(message, out query);
373 |
374 | if (keyValues == null || String.IsNullOrWhiteSpace(query)) {
375 | return;
376 | }
377 |
378 | Log(Category, String.Format("[{0}] Received {1} query from: {2}:{3}", state.Type, query, ((IPEndPoint)state.Socket.RemoteEndPoint).Address, ((IPEndPoint)state.Socket.RemoteEndPoint).Port));
379 |
380 | if (keyValues.ContainsKey("gamename") && !keyValues["gamename"].Equals("battlefield2", StringComparison.InvariantCultureIgnoreCase)) {
381 | // say no to those not using bf2... Begone evil demon, bf2 for life!
382 | return;
383 | }
384 |
385 | switch (state.Type) {
386 | case LoginSocketState.SocketType.Client:
387 | HandleClientManager(ref state, query, keyValues);
388 | break;
389 | case LoginSocketState.SocketType.Search:
390 | HandleSearchManager(ref state, query, keyValues);
391 | break;
392 | }
393 | }
394 |
395 | private void HandleClientManager(ref LoginSocketState state, string query, Dictionary keyValues)
396 | {
397 | if (state == null || String.IsNullOrWhiteSpace(query) || keyValues == null) {
398 | return;
399 | }
400 |
401 | if (state.State == 1) {
402 | if (query.Equals("login", StringComparison.InvariantCultureIgnoreCase)) {
403 | SendToClient(ref state, LoginServerMessages.SendProof(ref state, keyValues));
404 | state.StartKeepAlive(this);
405 | } else if (query.Equals("newuser", StringComparison.InvariantCultureIgnoreCase)) {
406 | SendToClient(ref state, LoginServerMessages.NewUser(ref state, keyValues));
407 | }
408 | } else if (state.State == 2) {
409 | if (query.Equals("getprofile", StringComparison.InvariantCultureIgnoreCase)) {
410 | SendToClient(ref state, LoginServerMessages.SendProfile(ref state, keyValues, false));
411 | } else if (query.Equals("updatepro", StringComparison.InvariantCultureIgnoreCase)) {
412 | LoginServerMessages.UpdateProfile(ref state, keyValues);
413 | }
414 | } else if (state.State == 3) {
415 | if (query.Equals("logout", StringComparison.InvariantCultureIgnoreCase)) {
416 | LoginServerMessages.Logout(ref state, keyValues);
417 | } else if (query.Equals("getprofile", StringComparison.InvariantCultureIgnoreCase)) {
418 | SendToClient(ref state, LoginServerMessages.SendProfile(ref state, keyValues, true));
419 | }
420 | } else if (state.State >= 4) {
421 | state.Dispose();
422 | }
423 | }
424 |
425 | private void HandleSearchManager(ref LoginSocketState state, string query, Dictionary keyValues)
426 | {
427 | if (state.State == 0) {
428 | if (query.Equals("nicks", StringComparison.InvariantCultureIgnoreCase)) {
429 | SendToClient(ref state, LoginServerMessages.SendNicks(ref state, keyValues));
430 | } else if (query.Equals("check", StringComparison.InvariantCultureIgnoreCase)) {
431 | SendToClient(ref state, LoginServerMessages.SendCheck(ref state, keyValues));
432 | }
433 | } else if (state.State == 1) {
434 | state.State++;
435 | } else if (state.State >= 2) {
436 | state.Dispose();
437 | }
438 | }
439 |
440 | private static Dictionary GetKeyValue(string message, out string query)
441 | {
442 | Dictionary parsedData = new Dictionary();
443 |
444 | string[] responseData = message.Split(new string[] { @"\" }, StringSplitOptions.None);
445 |
446 | if (responseData.Length > 1) {
447 | query = responseData[1];
448 | } else {
449 | query = String.Empty;
450 | return null;
451 | }
452 |
453 | for (int i = 1; i < responseData.Length - 1; i += 2) {
454 | if (parsedData.ContainsKey(responseData[i])) {
455 | parsedData[responseData[i].ToLowerInvariant()] = responseData[i + 1];
456 | } else {
457 | parsedData.Add(responseData[i].ToLowerInvariant(), responseData[i + 1]);
458 | }
459 | }
460 |
461 | return parsedData;
462 | }
463 | }
464 |
465 | internal class LoginSocketState : IDisposable
466 | {
467 | public enum SocketType
468 | {
469 | Client,
470 | Search
471 | }
472 |
473 | public AsyncCallback SendCallback;
474 | public AsyncCallback DataReceivedCallback;
475 |
476 | public SocketType Type;
477 |
478 | public Socket Socket = null;
479 | public byte[] Buffer = new byte[8192];
480 | public StringBuilder ReceivedData = new StringBuilder(8192);
481 |
482 | public int State = 0;
483 | public int HeartbeatState = 0;
484 | public string Session = "";
485 |
486 | public string ServerChallenge;
487 | public string ClientChallenge;
488 | public string Name;
489 | public string Email;
490 | public string PasswordEncrypted;
491 |
492 | private Timer _keepAliveTimer;
493 |
494 | public void StartKeepAlive(LoginServer server)
495 | {
496 | if (_keepAliveTimer != null) {
497 | // if the timer already exists, destroy it so we can start a new one...
498 | _keepAliveTimer.Dispose();
499 | }
500 |
501 | // send a keep alive request every 2 minutes
502 | _keepAliveTimer = new Timer(KeepAliveCallback, server, TimeSpan.FromMinutes(2), TimeSpan.FromMinutes(2));
503 | }
504 |
505 | private void KeepAliveCallback(object s)
506 | {
507 | LoginServer server = (LoginServer)s;
508 |
509 | try {
510 | if (_keepAliveTimer == null) {
511 | Dispose();
512 | return;
513 | }
514 |
515 | LoginSocketState state = this;
516 | HeartbeatState++;
517 |
518 | Console.WriteLine("sending keep alive");
519 | if (!server.SendToClient(ref state, LoginServerMessages.SendKeepAlive())) {
520 | Dispose();
521 | return;
522 | }
523 |
524 | // every 2nd keep alive request, we send an additional heartbeat
525 | if (HeartbeatState % 2 == 0) {
526 | Console.WriteLine("sending heartbeat");
527 | if (!server.SendToClient(ref state, LoginServerMessages.SendHeartbeat())) {
528 | Dispose();
529 | return;
530 | }
531 | }
532 | } catch (Exception e) {
533 | server.LogError(LoginServer.Category, "Error running keep alive: " + e);
534 | Dispose();
535 | }
536 | }
537 |
538 | public void Dispose()
539 | {
540 | Dispose(true);
541 | GC.SuppressFinalize(this);
542 | }
543 |
544 | protected virtual void Dispose(bool disposing)
545 | {
546 | try {
547 | if (disposing) {
548 | SendCallback = null;
549 | DataReceivedCallback = null;
550 |
551 | if (Socket != null) {
552 | Socket.Shutdown(SocketShutdown.Both);
553 | Socket.Close();
554 | Socket.Dispose();
555 | Socket = null;
556 | }
557 |
558 | if (_keepAliveTimer != null) {
559 | _keepAliveTimer.Dispose();
560 | _keepAliveTimer = null;
561 | }
562 | }
563 |
564 | // yeah yeah, this is terrible, but it stops a memory leak :|
565 | GC.Collect();
566 | } catch (Exception) {
567 | }
568 | }
569 |
570 | ~LoginSocketState()
571 | {
572 | Dispose(false);
573 | }
574 | }
575 | }
576 |
--------------------------------------------------------------------------------
/PRMasterServer/Servers/ServerListRetrieve.cs:
--------------------------------------------------------------------------------
1 | using PRMasterServer.Data;
2 | using Reality.Net.Extensions;
3 | using Reality.Net.GameSpy.Servers;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Linq.Dynamic;
8 | using System.Net;
9 | using System.Net.Sockets;
10 | using System.Reflection;
11 | using System.Text;
12 | using System.Text.RegularExpressions;
13 | using System.Threading;
14 |
15 | namespace PRMasterServer.Servers
16 | {
17 | internal class ServerListRetrieve
18 | {
19 | private const string Category = "ServerRetrieve";
20 |
21 | public Action Log = (x, y) => { };
22 | public Action LogError = (x, y) => { };
23 |
24 | public Thread Thread;
25 |
26 | private static Socket _socket;
27 | private readonly ServerListReport _report;
28 |
29 | private readonly ManualResetEvent _reset = new ManualResetEvent(false);
30 | private AsyncCallback _socketSendCallback;
31 | private AsyncCallback _socketDataReceivedCallback;
32 |
33 | public ServerListRetrieve(IPAddress listen, ushort port, ServerListReport report, Action log, Action logError)
34 | {
35 | Log = log;
36 | LogError = logError;
37 |
38 | _report = report;
39 | /*
40 | _report.Servers.TryAdd("test", new List() {
41 | new GameServer() {
42 | Valid = true,
43 | IPAddress = "192.168.1.2",
44 | QueryPort = 29900,
45 | country = "AU",
46 | hostname = "[PR v1.2.0.0] 42",
47 | gamename = "battlefield2",
48 | gamever = "1.5.3153-802.0",
49 | mapname = "Awesome Map",
50 | gametype = "gpm_cq",
51 | gamevariant = "pr",
52 | numplayers = 100,
53 | maxplayers = 100,
54 | gamemode = "openplaying",
55 | password = false,
56 | timelimit = 14400,
57 | roundtime = 1,
58 | hostport = 16567,
59 | bf2_dedicated = true,
60 | bf2_ranked = true,
61 | bf2_anticheat = false,
62 | bf2_os = "win32",
63 | bf2_autorec = true,
64 | bf2_d_idx = "http://",
65 | bf2_d_dl = "http://",
66 | bf2_voip = true,
67 | bf2_autobalanced = false,
68 | bf2_friendlyfire = true,
69 | bf2_tkmode = "No Punish",
70 | bf2_startdelay = 240.0,
71 | bf2_spawntime = 300.0,
72 | bf2_sponsortext = "Welcome to an awesome server!",
73 | bf2_sponsorlogo_url = "http://",
74 | bf2_communitylogo_url = "http://",
75 | bf2_scorelimit = 100,
76 | bf2_ticketratio = 100.0,
77 | bf2_teamratio = 100.0,
78 | bf2_team1 = "US",
79 | bf2_team2 = "MEC",
80 | bf2_bots = false,
81 | bf2_pure = false,
82 | bf2_mapsize = 64,
83 | bf2_globalunlocks = true,
84 | bf2_fps = 35.0,
85 | bf2_plasma = true,
86 | bf2_reservedslots = 16,
87 | bf2_coopbotratio = 0,
88 | bf2_coopbotcount = 0,
89 | bf2_coopbotdiff = 0,
90 | bf2_novehicles = false
91 | }
92 | });
93 |
94 | IQueryable servers = _report.Servers.Select(x => x.Value).AsQueryable();
95 | Console.WriteLine(servers.Where("gamever = '1.5.3153-802.0' and gamevariant = 'pr' and hostname like '%[[]PR v1.2.0.0% %' and hostname like '%2%'").Count());
96 | */
97 |
98 | Thread = new Thread(StartServer) {
99 | Name = "Server Retrieving Socket Thread"
100 | };
101 | Thread.Start(new AddressInfo() {
102 | Address = listen,
103 | Port = port
104 | });
105 | }
106 |
107 | public void Dispose()
108 | {
109 | Dispose(true);
110 | GC.SuppressFinalize(this);
111 | }
112 |
113 | protected virtual void Dispose(bool disposing)
114 | {
115 | try {
116 | if (disposing) {
117 | if (_socket != null) {
118 | _socket.Close();
119 | _socket.Dispose();
120 | _socket = null;
121 | }
122 | }
123 | } catch (Exception) {
124 | }
125 | }
126 |
127 | ~ServerListRetrieve()
128 | {
129 | Dispose(false);
130 | }
131 |
132 | private void StartServer(object parameter)
133 | {
134 | AddressInfo info = (AddressInfo)parameter;
135 |
136 | Log(Category, "Starting Server List Retrieval");
137 |
138 | try {
139 | _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) {
140 | SendTimeout = 5000,
141 | ReceiveTimeout = 5000,
142 | SendBufferSize = 65535,
143 | ReceiveBufferSize = 65535
144 | };
145 | _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true);
146 | _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
147 |
148 | _socket.Bind(new IPEndPoint(info.Address, info.Port));
149 | _socket.Listen(10);
150 | } catch (Exception e) {
151 | LogError(Category, String.Format("Unable to bind Server List Retrieval to {0}:{1}", info.Address, info.Port));
152 | LogError(Category, e.ToString());
153 | return;
154 | }
155 |
156 | while (true) {
157 | _reset.Reset();
158 | _socket.BeginAccept(AcceptCallback, _socket);
159 | _reset.WaitOne();
160 | }
161 | }
162 |
163 | private void AcceptCallback(IAsyncResult ar)
164 | {
165 | _reset.Set();
166 |
167 | Socket listener = (Socket)ar.AsyncState;
168 | Socket handler = listener.EndAccept(ar);
169 |
170 | SocketState state = new SocketState() {
171 | Socket = handler
172 | };
173 |
174 | WaitForData(state);
175 | }
176 |
177 | private void WaitForData(SocketState state)
178 | {
179 | Thread.Sleep(10);
180 | if (state == null || state.Socket == null || !state.Socket.Connected)
181 | return;
182 |
183 | try {
184 | if (_socketDataReceivedCallback == null)
185 | _socketDataReceivedCallback = OnDataReceived;
186 |
187 | state.Socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, _socketDataReceivedCallback, state);
188 | } catch (ObjectDisposedException) {
189 | state.Socket = null;
190 | } catch (SocketException e) {
191 | if (e.SocketErrorCode == SocketError.NotConnected)
192 | return;
193 |
194 | LogError(Category, "Error receiving data");
195 | LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e));
196 | return;
197 | }
198 | }
199 |
200 | private void OnDataReceived(IAsyncResult async)
201 | {
202 | SocketState state = (SocketState)async.AsyncState;
203 |
204 | if (state == null || state.Socket == null || !state.Socket.Connected)
205 | return;
206 |
207 | try {
208 | // receive data from the socket
209 | int received = state.Socket.EndReceive(async);
210 | if (received == 0) {
211 | // when EndReceive returns 0, it means the socket on the other end has been shut down.
212 | return;
213 | }
214 |
215 | // take what we received, and append it to the received data buffer
216 | state.ReceivedData.Append(Encoding.UTF8.GetString(state.Buffer, 0, received));
217 | string receivedData = state.ReceivedData.ToString();
218 |
219 | // does what we received end with \x00\x00\x00\x00\x??
220 | if (receivedData.Substring(receivedData.Length - 5, 4) == "\x00\x00\x00\x00") {
221 | state.ReceivedData.Clear();
222 |
223 | // lets split up the message based on the delimiter
224 | string[] messages = receivedData.Split(new string[] { "\x00\x00\x00\x00" }, StringSplitOptions.RemoveEmptyEntries);
225 |
226 | for (int i = 0; i < messages.Length; i++) {
227 | if (messages[i].StartsWith("battlefield2")) {
228 | if (ParseRequest(state, messages[i]))
229 | return;
230 | }
231 | }
232 | }
233 | } catch (ObjectDisposedException) {
234 | if (state != null)
235 | state.Dispose();
236 | state = null;
237 | return;
238 | } catch (SocketException e) {
239 | switch (e.SocketErrorCode) {
240 | case SocketError.ConnectionReset:
241 | if (state != null)
242 | state.Dispose();
243 | state = null;
244 | return;
245 | case SocketError.Disconnecting:
246 | if (state != null)
247 | state.Dispose();
248 | state = null;
249 | return;
250 | default:
251 | LogError(Category, "Error receiving data");
252 | LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e));
253 | if (state != null)
254 | state.Dispose();
255 | state = null;
256 | return;
257 | }
258 | } catch (Exception e) {
259 | LogError(Category, "Error receiving data");
260 | LogError(Category, e.ToString());
261 | }
262 |
263 | // and we wait for more data...
264 | WaitForData(state);
265 | }
266 |
267 | private void SendToClient(SocketState state, byte[] data)
268 | {
269 | if (state == null)
270 | return;
271 |
272 | if (state.Socket == null || !state.Socket.Connected) {
273 | state.Dispose();
274 | state = null;
275 | return;
276 | }
277 |
278 | if (_socketSendCallback == null)
279 | _socketSendCallback = OnSent;
280 |
281 | try {
282 | state.Socket.BeginSend(data, 0, data.Length, SocketFlags.None, _socketSendCallback, state);
283 | } catch (SocketException e) {
284 | LogError(Category, "Error sending data");
285 | LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e));
286 | }
287 | }
288 |
289 | private void OnSent(IAsyncResult async)
290 | {
291 | SocketState state = (SocketState)async.AsyncState;
292 |
293 | if (state == null || state.Socket == null)
294 | return;
295 |
296 | try {
297 | int sent = state.Socket.EndSend(async);
298 | Log(Category, String.Format("Sent {0} byte response to: {1}:{2}", sent, ((IPEndPoint)state.Socket.RemoteEndPoint).Address, ((IPEndPoint)state.Socket.RemoteEndPoint).Port));
299 | } catch (SocketException e) {
300 | switch (e.SocketErrorCode) {
301 | case SocketError.ConnectionReset:
302 | case SocketError.Disconnecting:
303 | return;
304 | default:
305 | LogError(Category, "Error sending data");
306 | LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e));
307 | return;
308 | }
309 | } finally {
310 | state.Dispose();
311 | state = null;
312 | }
313 | }
314 |
315 | private bool ParseRequest(SocketState state, string message)
316 | {
317 | string[] data = message.Split(new char[] { '\x00' }, StringSplitOptions.RemoveEmptyEntries);
318 | if (data.Length != 4 ||
319 | !data[0].Equals("battlefield2", StringComparison.InvariantCultureIgnoreCase) ||
320 | (
321 | !data[1].Equals("battlefield2", StringComparison.InvariantCultureIgnoreCase) &&
322 | !data[1].Equals("gslive", StringComparison.InvariantCultureIgnoreCase)
323 | )
324 | ) {
325 | return false;
326 | }
327 |
328 | string gamename = data[1].ToLowerInvariant();
329 | string validate = data[2].Substring(0, 8);
330 | string filter = FixFilter(data[2].Substring(8));
331 | string[] fields = data[3].Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
332 |
333 | Log(Category, String.Format("Received client request: {0}:{1}", ((IPEndPoint)state.Socket.RemoteEndPoint).Address, ((IPEndPoint)state.Socket.RemoteEndPoint).Port));
334 |
335 | IQueryable servers = _report.Servers.ToList().Select(x => x.Value).Where(x => x.Valid).AsQueryable();
336 | if (!String.IsNullOrWhiteSpace(filter)) {
337 | try {
338 | //Console.WriteLine(filter);
339 | servers = servers.Where(filter);
340 | //Console.WriteLine(servers.Count());
341 | } catch (Exception e) {
342 | LogError(Category, "Error parsing filter");
343 | LogError(Category, filter);
344 | LogError(Category, e.ToString());
345 | }
346 | }
347 |
348 | // http://aluigi.altervista.org/papers/gslist.cfg
349 | byte[] key;
350 | if (gamename == "battlefield2")
351 | key = DataFunctions.StringToBytes("hW6m9a");
352 | else if (gamename == "arma2oapc")
353 | key = DataFunctions.StringToBytes("sGKWik");
354 | else
355 | key = DataFunctions.StringToBytes("Xn221z");
356 |
357 | byte[] unencryptedServerList = PackServerList(state, servers, fields);
358 | byte[] encryptedServerList = GSEncoding.Encode(key, DataFunctions.StringToBytes(validate), unencryptedServerList, unencryptedServerList.LongLength);
359 | SendToClient(state, encryptedServerList);
360 | return true;
361 | }
362 |
363 | private static byte[] PackServerList(SocketState state, IEnumerable servers, string[] fields)
364 | {
365 | IPEndPoint remoteEndPoint = ((IPEndPoint)state.Socket.RemoteEndPoint);
366 |
367 | byte[] ipBytes = remoteEndPoint.Address.GetAddressBytes();
368 | byte[] value2 = BitConverter.GetBytes((ushort)6500);
369 | byte fieldsCount = (byte)fields.Length;
370 |
371 | List data = new List();
372 | data.AddRange(ipBytes);
373 | data.AddRange(BitConverter.IsLittleEndian ? value2.Reverse() : value2);
374 | data.Add(fieldsCount);
375 | data.Add(0);
376 |
377 | foreach (var field in fields) {
378 | data.AddRange(DataFunctions.StringToBytes(field));
379 | data.AddRange(new byte[] { 0, 0 });
380 | }
381 |
382 | foreach (var server in servers) {
383 | // commented this stuff out since it caused some issues on testing, might come back to it later and see what's happening...
384 | // NAT traversal stuff...
385 | // 126 (\x7E) = public ip / public port / private ip / private port / icmp ip
386 | // 115 (\x73) = public ip / public port / private ip / private port
387 | // 85 (\x55) = public ip / public port
388 | // 81 (\x51) = public ip / public port
389 | /*Console.WriteLine(server.IPAddress);
390 | Console.WriteLine(server.QueryPort);
391 | Console.WriteLine(server.localip0);
392 | Console.WriteLine(server.localip1);
393 | Console.WriteLine(server.localport);
394 | Console.WriteLine(server.natneg);
395 | if (!String.IsNullOrWhiteSpace(server.localip0) && !String.IsNullOrWhiteSpace(server.localip1) && server.localport > 0) {
396 | data.Add(126);
397 | data.AddRange(IPAddress.Parse(server.IPAddress).GetAddressBytes());
398 | data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)server.QueryPort).Reverse() : BitConverter.GetBytes((ushort)server.QueryPort));
399 | data.AddRange(IPAddress.Parse(server.localip0).GetAddressBytes());
400 | data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)server.localport).Reverse() : BitConverter.GetBytes((ushort)server.localport));
401 | data.AddRange(IPAddress.Parse(server.localip1).GetAddressBytes());
402 | } else if (!String.IsNullOrWhiteSpace(server.localip0) && server.localport > 0) {
403 | data.Add(115);
404 | data.AddRange(IPAddress.Parse(server.IPAddress).GetAddressBytes());
405 | data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)server.QueryPort).Reverse() : BitConverter.GetBytes((ushort)server.QueryPort));
406 | data.AddRange(IPAddress.Parse(server.localip0).GetAddressBytes());
407 | data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)server.localport).Reverse() : BitConverter.GetBytes((ushort)server.localport));
408 | } else {*/
409 | data.Add(81); // it could be 85 as well, unsure of the difference, but 81 seems more common...
410 | data.AddRange(IPAddress.Parse(server.IPAddress).GetAddressBytes());
411 | data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)server.QueryPort).Reverse() : BitConverter.GetBytes((ushort)server.QueryPort));
412 | //}
413 |
414 | data.Add(255);
415 |
416 | for (int i = 0; i < fields.Length; i++) {
417 | data.AddRange(DataFunctions.StringToBytes(GetField(server, fields[i])));
418 |
419 | if (i < fields.Length - 1)
420 | data.AddRange(new byte[] { 0, 255 });
421 | }
422 |
423 | data.Add(0);
424 | }
425 |
426 | data.AddRange(new byte[] { 0, 255, 255, 255, 255 });
427 |
428 | return data.ToArray();
429 | }
430 |
431 | private static string GetField(GameServer server, string fieldName)
432 | {
433 | object value = server.GetType().GetProperty(fieldName).GetValue(server, null);
434 | if (value == null)
435 | return String.Empty;
436 | else if (value is Boolean)
437 | return (bool)value ? "1" : "0";
438 | else
439 | return value.ToString();
440 | }
441 |
442 | private string FixFilter(string filter)
443 | {
444 | // escape [
445 | filter = filter.Replace("[", "[[]");
446 |
447 | // fix an issue in the BF2 main menu where filter expressions aren't joined properly
448 | // i.e. "numplayers > 0gametype like '%gpm_cq%'"
449 | // becomes "numplayers > 0 && gametype like '%gpm_cq%'"
450 | try {
451 | filter = FixFilterOperators(filter);
452 | } catch (Exception e) {
453 | LogError(Category, e.ToString());
454 | }
455 |
456 | // fix quotes inside quotes
457 | // i.e. hostname like 'flyin' high'
458 | // becomes hostname like 'flyin_ high'
459 | try {
460 | filter = FixFilterQuotes(filter);
461 | } catch (Exception e) {
462 | LogError(Category, e.ToString());
463 | }
464 |
465 | // fix consecutive whitespace
466 | filter = Regex.Replace(filter, @"\s+", " ").Trim();
467 |
468 | return filter;
469 | }
470 |
471 | private static string FixFilterOperators(string filter)
472 | {
473 | PropertyInfo[] properties = typeof(GameServer).GetProperties();
474 | List filterableProperties = new List();
475 |
476 | // get all the properties that aren't "[NonFilter]"
477 | foreach (var property in properties) {
478 | if (property.GetCustomAttributes(false).Any(x => x.GetType().Name == "NonFilterAttribute"))
479 | continue;
480 |
481 | filterableProperties.Add(property.Name);
482 | }
483 |
484 | // go through each property, see if they exist in the filter,
485 | // and check to see if what's before the property is a logical operator
486 | // if it is not, then we slap a && before it
487 | foreach (var property in filterableProperties) {
488 | IEnumerable indexes = filter.IndexesOf(property);
489 | foreach (var index in indexes) {
490 | if (index > 0) {
491 | int length = 0;
492 | bool hasLogical = IsLogical(filter, index, out length, true) || IsOperator(filter, index, out length, true) || IsGroup(filter, index, out length, true);
493 | if (!hasLogical) {
494 | filter = filter.Insert(index, " && ");
495 | }
496 | }
497 | }
498 | }
499 | return filter;
500 | }
501 |
502 | private static string FixFilterQuotes(string filter)
503 | {
504 | StringBuilder newFilter = new StringBuilder(filter);
505 |
506 | for (int i = 0; i < filter.Length; i++) {
507 | int length = 0;
508 | bool isOperator = IsOperator(filter, i, out length);
509 |
510 | if (isOperator) {
511 | i += length;
512 | bool isInsideString = false;
513 | for (; i < filter.Length; i++) {
514 | if (filter[i] == '\'' || filter[i] == '"') {
515 | if (isInsideString) {
516 | // check what's after the quote to see if we terminate the string
517 | if (i >= filter.Length - 1) {
518 | // end of string
519 | isInsideString = false;
520 | break;
521 | }
522 | for (int j = i + 1; j < filter.Length; j++) {
523 | // continue along whitespace
524 | if (filter[j] == ' ') {
525 | continue;
526 | } else {
527 | // if it's a logical operator, then we terminate
528 | bool op = IsLogical(filter, j, out length);
529 | if (op) {
530 | isInsideString = false;
531 | j += length;
532 | i = j;
533 | }
534 | break;
535 | }
536 | }
537 | if (isInsideString) {
538 | // and if we're still inside the string, replace the quote with a wildcard character
539 | newFilter[i] = '_';
540 | }
541 | continue;
542 | } else {
543 | isInsideString = true;
544 | }
545 | }
546 | }
547 | }
548 | }
549 |
550 | return newFilter.ToString();
551 | }
552 |
553 | private static bool IsOperator(string filter, int i, out int length, bool previous = false)
554 | {
555 | bool isOperator = false;
556 | length = 0;
557 |
558 | if (i < filter.Length - 1) {
559 | string op = filter.Substring(i - (i >= 2 ? (previous ? 2 : 0) : 0), 1);
560 | if (op == "=" || op == "<" || op == ">") {
561 | isOperator = true;
562 | length = 1;
563 | }
564 | }
565 |
566 | if (!isOperator) {
567 | if (i < filter.Length - 2) {
568 | string op = filter.Substring(i - (i >= 3 ? (previous ? 3 : 0) : 0), 2);
569 | if (op == "==" || op == "!=" || op == "<>" || op == "<=" || op == ">=") {
570 | isOperator = true;
571 | length = 2;
572 | }
573 | }
574 | }
575 |
576 | if (!isOperator) {
577 | if (i < filter.Length - 4) {
578 | string op = filter.Substring(i - (i >= 5 ? (previous ? 5 : 0) : 0), 4);
579 | if (op.Equals("like", StringComparison.InvariantCultureIgnoreCase)) {
580 | isOperator = true;
581 | length = 4;
582 | }
583 | }
584 | }
585 |
586 | if (!isOperator) {
587 | if (i < filter.Length - 8) {
588 | string op = filter.Substring(i - (i >= 9 ? (previous ? 9 : 0) : 0), 8);
589 | if (op.Equals("not like", StringComparison.InvariantCultureIgnoreCase)) {
590 | isOperator = true;
591 | length = 8;
592 | }
593 | }
594 | }
595 |
596 | return isOperator;
597 | }
598 |
599 | private static bool IsLogical(string filter, int i, out int length, bool previous = false)
600 | {
601 | bool isLogical = false;
602 | length = 0;
603 |
604 | if (i < filter.Length - 2) {
605 | string op = filter.Substring(i - (i >= 3 ? (previous ? 3 : 0) : 0), 2);
606 | if (op == "&&" || op == "||" || op.Equals("or", StringComparison.InvariantCultureIgnoreCase)) {
607 | isLogical = true;
608 | length = 2;
609 | }
610 | }
611 |
612 | if (!isLogical) {
613 | if (i < filter.Length - 3) {
614 | string op = filter.Substring(i - (i >= 4 ? (previous ? 4 : 0) : 0), 3);
615 | if (op.Equals("and", StringComparison.InvariantCultureIgnoreCase)) {
616 | isLogical = true;
617 | length = 3;
618 | }
619 | }
620 | }
621 |
622 | return isLogical;
623 | }
624 |
625 | private static bool IsGroup(string filter, int i, out int length, bool previous = false)
626 | {
627 | bool isGroup = false;
628 | length = 0;
629 |
630 | if (i < filter.Length - 1) {
631 | string op = filter.Substring(i - (i >= 2 ? (previous ? 2 : 0) : 0), 1);
632 | if (op == "(" || op == ")") {
633 | isGroup = true;
634 | length = 1;
635 | }
636 | if (!isGroup && previous) {
637 | op = filter.Substring(i - (i >= 1 ? (previous ? 1 : 0) : 0), 1);
638 | if (op == "(" || op == ")") {
639 | isGroup = true;
640 | length = 1;
641 | }
642 | }
643 | }
644 |
645 | return isGroup;
646 | }
647 |
648 | private class SocketState : IDisposable
649 | {
650 | public Socket Socket = null;
651 | public byte[] Buffer = new byte[8192];
652 | public StringBuilder ReceivedData = new StringBuilder(8192);
653 |
654 | public void Dispose()
655 | {
656 | Dispose(true);
657 | GC.SuppressFinalize(this);
658 | }
659 |
660 | protected virtual void Dispose(bool disposing)
661 | {
662 | try {
663 | if (disposing) {
664 | if (Socket != null) {
665 | try {
666 | Socket.Shutdown(SocketShutdown.Both);
667 | } catch (Exception) {
668 | }
669 | Socket.Close();
670 | Socket.Dispose();
671 | Socket = null;
672 | }
673 | }
674 |
675 | GC.Collect();
676 | } catch (Exception) {
677 | }
678 | }
679 |
680 | ~SocketState()
681 | {
682 | Dispose(false);
683 | }
684 | }
685 | }
686 | }
687 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------