-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathProgram.cs
More file actions
329 lines (268 loc) · 9.85 KB
/
Program.cs
File metadata and controls
329 lines (268 loc) · 9.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Waher.Content;
using Waher.Runtime.Console;
using Waher.Runtime.Inventory;
using Waher.Runtime.IO;
using Waher.Security;
using Waher.Security.SHA3;
namespace Waher.Utility.Upload
{
class Program
{
/// <summary>
/// Uploads a package (optionally signed) to a broker.
///
/// Command line switches:
///
/// -p PACKAGE_FILENAME Package file name.
/// -s SIGNATURE_FILENAME Optional package signature file name.
/// -h HOST Host name of broker to upload to.
/// -n PORT Port number of broker to upload to,
/// if not using the default port number.
/// -a Account name to use for authentication.
/// -l Account password to use for authentication.
/// -d If package should be downloadable via
/// the web interface.
/// -? Help.
/// </summary>
static async Task<int> Main(string[] args)
{
string PackageFileName = null;
string SignatureFileName = null;
string HostName = null;
string UserName = null;
string Password = null;
string s;
int Port = 0;
int i = 0;
int c = args.Length;
bool Help = false;
bool Downloadable = false;
try
{
Types.Initialize(
typeof(InternetContent).Assembly,
typeof(Program).Assembly);
while (i < c)
{
s = args[i++].ToLower();
switch (s)
{
case "-p":
if (i >= c)
throw new Exception("Missing package file name.");
if (string.IsNullOrEmpty(PackageFileName))
PackageFileName = args[i++];
else
throw new Exception("Only one package file name allowed.");
break;
case "-s":
if (i >= c)
throw new Exception("Missing signature file name.");
if (string.IsNullOrEmpty(SignatureFileName))
SignatureFileName = args[i++];
else
throw new Exception("Only one signature file name allowed.");
break;
case "-h":
if (i >= c)
throw new Exception("Missing host name.");
if (string.IsNullOrEmpty(HostName))
HostName = args[i++];
else
throw new Exception("Only one host name allowed.");
break;
case "-n":
if (i >= c)
throw new Exception("Missing port number.");
if (!int.TryParse(args[i++], out int j) || j <= 0 || j > 65535)
throw new Exception("Invalid port number.");
if (Port == 0)
Port = j;
else
throw new Exception("Only one port number allowed.");
break;
case "-a":
if (i >= c)
throw new Exception("Missing account name.");
if (string.IsNullOrEmpty(UserName))
UserName = args[i++];
else
throw new Exception("Only one user name allowed.");
break;
case "-l":
if (i >= c)
throw new Exception("Missing password.");
if (string.IsNullOrEmpty(Password))
Password = args[i++];
else
throw new Exception("Only one password allowed.");
break;
case "-d":
Downloadable = true;
break;
case "-?":
Help = true;
break;
default:
throw new Exception("Unrecognized switch: " + s);
}
}
if (Help || c == 0)
{
ConsoleOut.WriteLine("Uploads a package (optionally signed) to a broker.");
ConsoleOut.WriteLine();
ConsoleOut.WriteLine("Command line switches:");
ConsoleOut.WriteLine();
ConsoleOut.WriteLine("-p PACKAGE_FILENAME Package file name.");
ConsoleOut.WriteLine("-s SIGNATURE_FILENAME Optional package signature file name.");
ConsoleOut.WriteLine("-h HOST Host name of broker to upload to.");
ConsoleOut.WriteLine("-n PORT Port number of broker to upload to, ");
ConsoleOut.WriteLine(" if not using the default port number.");
ConsoleOut.WriteLine("-a Account name to use for authentication.");
ConsoleOut.WriteLine("-l Account password to use for authentication.");
ConsoleOut.WriteLine("-d If package should be downloadable via");
ConsoleOut.WriteLine(" the web interface.");
ConsoleOut.WriteLine("-? Help.");
return 0;
}
if (string.IsNullOrEmpty(HostName))
throw new Exception("Host name not specified.");
if (string.IsNullOrEmpty(PackageFileName))
throw new Exception("Package file name not specified.");
if (string.IsNullOrEmpty(UserName))
throw new Exception("Account name not specified.");
if (string.IsNullOrEmpty(Password))
throw new Exception("Account password not specified.");
PackageFileName = Path.GetFullPath(PackageFileName);
StringBuilder sb = new();
sb.Append("https://");
sb.Append(HostName);
if (Port > 0)
{
sb.Append(':');
sb.Append(Port);
}
sb.Append('/');
Uri Login = new(sb.ToString() + "Login");
Uri Logout = new(sb.ToString() + "Logout");
Uri UploadPackage = new(sb.ToString() + "UploadPackage");
Uri UploadSignature = new(sb.ToString() + "UploadSignature");
string TabID = Guid.NewGuid().ToString();
string HttpSessionID = Guid.NewGuid().ToString();
ConsoleOut.WriteLine("Logging in to domain " + Login.Host + ".");
sb.Clear();
sb.Append(UserName);
sb.Append(':');
sb.Append(Login.Host);
sb.Append(':');
sb.Append(Password);
byte[] Nonce = new byte[32];
System.Security.Cryptography.RandomNumberGenerator Rnd = System.Security.Cryptography.RandomNumberGenerator.Create();
Rnd.GetBytes(Nonce);
string NonceStr = Convert.ToBase64String(Nonce);
byte[] H1 = new SHA3_256().ComputeVariable(Encoding.UTF8.GetBytes(sb.ToString()));
byte[] H2 = Hashes.ComputeHMACSHA256Hash(Encoding.UTF8.GetBytes(NonceStr), H1);
ContentResponse LoginResponse = await InternetContent.PostAsync(Login,
new Dictionary<string, object>()
{
{ "UserName", UserName },
{ "PasswordHash", Convert.ToBase64String(H2) },
{ "Nonce", NonceStr }
},
new KeyValuePair<string, string>("Cookie", "HttpSessionID=" + HttpSessionID));
LoginResponse.AssertOk();
if (LoginResponse.Decoded is not Dictionary<string, object> Response ||
!Response.TryGetValue("ok", out object Obj) ||
Obj is not bool Ok)
{
throw new Exception("Invalid response from login request.");
}
if (Ok)
Console.Out.WriteLine("Log in successful.");
else
{
if (!Response.TryGetValue("message", out Obj) ||
Obj is not string Message ||
string.IsNullOrEmpty(Message))
{
Message = "Login failed.";
}
throw new Exception(Message);
}
using FileStream PackageStream = new(PackageFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
int BufSize = 4 * 1024 * 1024;
long Length = PackageStream.Length;
long Position = 0;
int BlockNr = 0;
byte[] Buffer = null;
ConsoleOut.WriteLine("Uploading package file.");
do
{
ConsoleOut.Write('.');
c = (int)Math.Min(BufSize, Length - Position);
if (Buffer is null || Buffer.Length != c)
Buffer = new byte[c];
await PackageStream.ReadAllAsync(Buffer, 0, c);
Position += c;
ContentBinaryResponse UploadResponse = await InternetContent.PostAsync(
UploadPackage, Buffer, "application/octet-stream",
new KeyValuePair<string, string>("Cookie", "HttpSessionID=" + HttpSessionID),
new KeyValuePair<string, string>("X-FileName", Path.GetFileName(PackageFileName)),
new KeyValuePair<string, string>("X-TabID", TabID),
new KeyValuePair<string, string>("X-BlockNr", BlockNr++.ToString()),
new KeyValuePair<string, string>("X-More", Position < Length ? "1" : "0"),
new KeyValuePair<string, string>("X-Downloadable", Downloadable ? "1" : "0"),
new KeyValuePair<string, string>("X-GenSign", string.IsNullOrEmpty(SignatureFileName) ? "1" : "0"));
UploadResponse.AssertOk();
}
while (Position < Length);
ConsoleOut.WriteLine();
if (!string.IsNullOrEmpty(SignatureFileName))
{
using FileStream SignatureStream = new(SignatureFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
Length = SignatureStream.Length;
if (Length > int.MaxValue)
throw new Exception("Signature file too large.");
if (Buffer is null || Buffer.Length != Length)
Buffer = new byte[Length];
ConsoleOut.WriteLine("Uploading signature file.");
await SignatureStream.ReadAllAsync(Buffer, 0, (int)Length);
ContentBinaryResponse UploadResponse = await InternetContent.PostAsync(
UploadSignature, Buffer, "application/octet-stream",
new KeyValuePair<string, string>("Cookie", "HttpSessionID=" + HttpSessionID),
new KeyValuePair<string, string>("X-FileName", Path.GetFileName(SignatureFileName)),
new KeyValuePair<string, string>("X-TabID", TabID),
new KeyValuePair<string, string>("X-BlockNr", "0"),
new KeyValuePair<string, string>("X-More", "0"),
new KeyValuePair<string, string>("X-Downloadable", Downloadable ? "1" : "0"));
UploadResponse.AssertOk();
}
ConsoleOut.WriteLine("Package uploaded successfully.");
ConsoleOut.WriteLine("Logging out.");
ContentResponse LogoutResponse = await InternetContent.PostAsync(Logout,
string.Empty,
new KeyValuePair<string, string>("Cookie", "HttpSessionID=" + HttpSessionID));
LoginResponse.AssertOk();
return 0;
}
catch (Exception ex)
{
ConsoleOut.WriteLine();
ConsoleColor Bak = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
ConsoleOut.WriteLine(ex.Message);
Console.ForegroundColor = Bak;
return -1;
}
finally
{
ConsoleOut.Flush(true);
}
}
}
}