casualexpiesource

cu-trainer/Ultra Paradise Application/src/Loader.cs

201 lines · 8.9 KB · plain text · download

1using System;
2using System.Diagnostics;
3using System.IO;
4using System.IO.Compression;
5using System.Net;
6using System.Security.Cryptography;
7
8namespace UltraParadise
9{
10 internal static class UltraPara
11 {
12 public const string DllName = "UltraPara.dll";
13 public const string StubName = "version.dll";
14 private const string Base = "https://updates.smellypawz.com";
15 private const long MaxBytes = 30L * 1024 * 1024;
16
17 public static string Status = "";
18 public static volatile string GameVersion = "";
19
20 private static string Cache { get { return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UltraParadise"), "ultrapara"); } }
21
22 public static string Sha(byte[] b)
23 {
24 using (SHA256 s = SHA256.Create()) return BitConverter.ToString(s.ComputeHash(b)).Replace("-", "").ToLowerInvariant();
25 }
26
27 private static string ShaFile(string p)
28 {
29 using (SHA256 s = SHA256.Create())
30 using (FileStream f = File.OpenRead(p)) return BitConverter.ToString(s.ComputeHash(f)).Replace("-", "").ToLowerInvariant();
31 }
32
33 private static bool Ours(string stub)
34 {
35 try { return FileVersionInfo.GetVersionInfo(stub).ProductName == "UltraPara"; } catch (Exception) { return false; }
36 }
37
38 public static string State(string game)
39 {
40 if (string.IsNullOrEmpty(game) || !Directory.Exists(game)) return "nogame";
41 string dll = Path.Combine(game, DllName), stub = Path.Combine(game, StubName);
42 if (File.Exists(stub) && !Ours(stub)) return "foreign";
43 if (!File.Exists(dll) || !File.Exists(stub)) return "missing";
44 try { return ShaFile(dll) == UltraParaInfo.DllSha && ShaFile(stub) == UltraParaInfo.StubSha ? "ok" : "old"; }
45 catch (Exception) { return "old"; }
46 }
47
48 public static string InstalledVersion(string game)
49 {
50 try
51 {
52 string dll = Path.Combine(game, DllName);
53 return File.Exists(dll) ? FileVersionInfo.GetVersionInfo(dll).ProductVersion : null;
54 }
55 catch (Exception) { return null; }
56 }
57
58 public static bool LoadedIn(Process p)
59 {
60 if (p == null) return false;
61 try
62 {
63 p.Refresh();
64 foreach (ProcessModule m in p.Modules)
65 if (string.Equals(m.ModuleName, DllName, StringComparison.OrdinalIgnoreCase)) return true;
66 }
67 catch (Exception) { }
68 return false;
69 }
70
71 public static string LastLog(string game)
72 {
73 try
74 {
75 string f = Path.Combine(Path.Combine(game, "UltraParadise"), "UltraPara.log");
76 if (!File.Exists(f)) return null;
77 string[] lines;
78 using (FileStream fs = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
79 using (StreamReader r = new StreamReader(fs)) lines = r.ReadToEnd().Replace("\r", "").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
80 return lines.Length > 0 ? lines[lines.Length - 1] : null;
81 }
82 catch (Exception) { return null; }
83 }
84
85 private static byte[] Download(Action<int> progress)
86 {
87 Directory.CreateDirectory(Cache);
88 string cached = Path.Combine(Cache, UltraParaInfo.ZipName);
89 if (File.Exists(cached))
90 {
91 byte[] c = File.ReadAllBytes(cached);
92 if (Sha(c) == UltraParaInfo.ZipSha) return c;
93 try { File.Delete(cached); } catch (Exception) { }
94 }
95 byte[] b = null;
96 for (int attempt = 1; ; attempt++)
97 {
98 try { b = Fetch(progress); break; }
99 catch (WebException) { if (attempt >= 3) throw; }
100 catch (IOException) { if (attempt >= 3) throw; }
101 System.Threading.Thread.Sleep(2000 * attempt);
102 }
103 if (Sha(b) != UltraParaInfo.ZipSha) throw new InvalidDataException("the download didn't match the fingerprint built into the trainer, so nothing was installed");
104 try { File.WriteAllBytes(cached, b); } catch (Exception) { }
105 return b;
106 }
107
108 private static byte[] Fetch(Action<int> progress)
109 {
110 ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
111 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Base + "/v1/download?app=ultrapara&version=" + UltraParaInfo.Version);
112 req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version;
113 req.Timeout = 15000;
114 req.ReadWriteTimeout = 30000;
115 req.AllowAutoRedirect = false;
116 MemoryStream ms = new MemoryStream();
117 using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
118 {
119 long total = res.ContentLength;
120 if (total > MaxBytes) throw new InvalidDataException("the download is too big");
121 using (Stream s = res.GetResponseStream())
122 {
123 byte[] buf = new byte[65536];
124 int n, last = -1;
125 while ((n = s.Read(buf, 0, buf.Length)) > 0)
126 {
127 ms.Write(buf, 0, n);
128 if (ms.Length > MaxBytes) throw new InvalidDataException("the download is too big");
129 if (total > 0 && progress != null)
130 {
131 int pc = (int)(ms.Length * 100 / total);
132 if (pc != last) { last = pc; progress(pc); }
133 }
134 }
135 }
136 }
137 return ms.ToArray();
138 }
139
140 private static byte[] Entry(ZipArchive z, string name, string sha)
141 {
142 ZipArchiveEntry e = z.GetEntry(name);
143 if (e == null) throw new InvalidDataException(name + " is missing from the download");
144 MemoryStream ms = new MemoryStream();
145 using (Stream s = e.Open()) s.CopyTo(ms);
146 byte[] b = ms.ToArray();
147 if (Sha(b) != sha) throw new InvalidDataException(name + " didn't match its fingerprint");
148 return b;
149 }
150
151 private static void Put(string path, byte[] b)
152 {
153 string tmp = path + ".new";
154 File.WriteAllBytes(tmp, b);
155 if (File.Exists(path)) File.Delete(path);
156 File.Move(tmp, path);
157 }
158
159 public static string Install(string game, Action<int> progress)
160 {
161 if (string.IsNullOrEmpty(game) || !Directory.Exists(game)) return "the game folder wasn't found";
162 if (Installer.GameRunning()) return "close the game first";
163 string st = State(game);
164 if (st == "foreign") return "your game folder already has a version.dll from another program or mod (like ReShade). Move it out of the game folder, then try again";
165 if (st == "ok") return null;
166 const string Manual = ". You can also get it from updates.smellypawz.com and put UltraPara.dll and version.dll in the game folder yourself";
167 byte[] zip;
168 try { zip = Download(progress); }
169 catch (WebException e) { return "couldn't download UltraPara.dll from the update server (" + e.Message + ")" + Manual; }
170 catch (IOException e) { return "the UltraPara.dll download stalled (" + e.Message + ")" + Manual; }
171 catch (Exception e) { return e.Message + Manual; }
172 try
173 {
174 byte[] dll, stub;
175 using (ZipArchive z = new ZipArchive(new MemoryStream(zip), ZipArchiveMode.Read))
176 {
177 dll = Entry(z, DllName, UltraParaInfo.DllSha);
178 stub = Entry(z, StubName, UltraParaInfo.StubSha);
179 }
180 Put(Path.Combine(game, DllName), dll);
181 Put(Path.Combine(game, StubName), stub);
182 }
183 catch (UnauthorizedAccessException) { return "Windows wouldn't let the trainer write to the game folder. Run the trainer as administrator once"; }
184 catch (Exception e) { return e.Message; }
185 return State(game) == "ok" ? null : "UltraPara.dll was written but doesn't check out. Try again";
186 }
187
188 public static string Remove(string game)
189 {
190 if (Installer.GameRunning()) return "close the game first";
191 try
192 {
193 string dll = Path.Combine(game, DllName), stub = Path.Combine(game, StubName);
194 if (File.Exists(stub) && Ours(stub)) File.Delete(stub);
195 if (File.Exists(dll)) File.Delete(dll);
196 return null;
197 }
198 catch (Exception e) { return e.Message; }
199 }
200 }
201}