-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
775 lines (698 loc) · 25.4 KB
/
Program.cs
File metadata and controls
775 lines (698 loc) · 25.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Xml.Linq;
using Utf8Json;
namespace Https
{
static class RequestContentFormatter
{
public static HttpContent As(ContentType requestContentType, IEnumerable<Content> contents, string xmlRootName)
{
switch (requestContentType)
{
case ContentType.FormUrlEncoded:
return AsFormUrlEncoded(contents);
case ContentType.Xml:
return AsXml(xmlRootName, contents);
case ContentType.Json:
return AsJson(contents);
default:
throw new ArgumentOutOfRangeException(nameof(requestContentType), requestContentType, "Invalid request content type");
}
}
public static HttpContent AsFormUrlEncoded(IEnumerable<Content> contents)
{
var pairs = contents.Select(content => new KeyValuePair<string, string>(content.Property, content.Value));
return new FormUrlEncodedContent(pairs);
}
public static HttpContent AsXml(string root, IEnumerable<Content> contents)
{
var xdocument = new XDocument(
new XElement(
root,
contents.Select(content => new XElement(content.Property, content.Value))
)
);
var stream = new MemoryStream();
xdocument.Save(stream);
stream.Position = 0;
var streamContent = new StreamContent(stream);
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
return streamContent;
}
public static HttpContent AsJson(IEnumerable<Content> contents)
{
var bytes = ArrayPool<byte>.Shared.Rent(100);
var writer = new JsonWriter(bytes);
writer.WriteBeginObject();
var counter = 0;
foreach (var content in contents)
{
if (counter++ > 0)
{
writer.WriteValueSeparator();
}
writer.WritePropertyName(content.Property);
writer.WriteString(content.Value);
}
writer.WriteEndObject();
var stream = new MemoryStream(writer.ToUtf8ByteArray());
var streamContent = new StreamContent(stream);
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/json")
{
CharSet = "utf-8"
};
return streamContent;
}
}
static class ResponseContentFormatter
{
public static async Task As(HttpResponseMessage response, StreamWriter target)
{
using (var stream = await response.Content.ReadAsStreamAsync())
{
switch (response.Content.Headers.ContentType?.MediaType)
{
case "application/json":
await AsJson(stream, target);
break;
default:
await AsOrigin(stream, target);
break;
case "application/xml":
await AsXml(stream, target);
break;
}
}
}
static async Task AsOrigin(Stream source, StreamWriter target)
{
await source.CopyToAsync(target.BaseStream);
}
static Task AsXml(Stream source, StreamWriter target) =>
AsOrigin(source, target);
static Task AsJson(Stream source, StreamWriter target) =>
AsOrigin(source, target);
}
public class Program
{
static IEnumerable<Content> ParseContents(IEnumerable<string> args)
{
foreach (var arg in args)
{
if (Content.TryParse(arg, out var content))
{
yield return content;
}
}
}
void Version()
{
var stream = _stdout();
var writer = new StreamWriter(stream) { AutoFlush = true };
writer.Write("dotnet-https ");
writer.WriteLine(typeof(Program).Assembly.GetName().Version);
writer.Flush();
}
void Help()
{
var stream = _stdout();
var writer = new StreamWriter(stream) { AutoFlush = true };
writer.WriteLine("Usage: https <METHOD> <URI> [options] [content]");
writer.WriteLine("");
writer.WriteLine("Submits HTTP requests. For example https put httpbin.org/put hello=world");
writer.WriteLine("");
writer.WriteLine("Arguments:");
writer.WriteLine(" <METHOD> HTTP method, i.e., get, head, post");
writer.WriteLine(" <URI> URI to send the request to. Leaving the protocol off the URI defaults to https://");
writer.WriteLine("");
writer.WriteLine("Options:");
foreach (var option in Options.GetOptionHelp())
{
writer.Write(" ");
writer.WriteLine(option);
}
writer.WriteLine("");
writer.WriteLine("Content:");
writer.WriteLine("Repeat as many content arguments to create content sent with the HTTP request. Alternatively pipe raw content send as the HTTP request content.");
writer.WriteLine(" <KEY>=<VALUE>");
writer.WriteLine("");
writer.WriteLine("Headers:");
writer.WriteLine("Repeat as many header arguments to assign headers for the HTTP request.");
writer.WriteLine(" <KEY>:<VALUE>");
writer.WriteLine("");
writer.Flush();
}
static void AddHeaders(HttpRequestMessage request, IEnumerable<Content> contents)
{
foreach (var content in contents)
{
if (!request.Headers.TryAddWithoutValidation(content.Property, content.Value))
{
if (!request.Content.Headers.TryAddWithoutValidation(content.Property, content.Value))
{
Console.Error.Write("Unexpected header: ");
Console.Error.WriteLine(content.Property);
}
}
}
}
readonly Func<Stream> _stderr;
readonly Func<Stream> _stdin;
readonly Func<Stream> _stdout;
readonly bool _useStdin;
public Program()
: this(Console.OpenStandardError, Console.OpenStandardInput, Console.OpenStandardOutput, Console.IsInputRedirected)
{
}
public Program(Func<Stream> stderr, Func<Stream> stdin, Func<Stream> stdout, bool useStdin)
{
_stderr = stderr;
_stdin = stdin;
_stdout = stdout;
_useStdin = useStdin;
}
public static Task<int> Main(string[] args) =>
new Program().RunAsync(args);
int HandleOptionsOnly(string[] args)
{
var options = Options.Parse(args);
if (options.Help)
{
Help();
return 0;
}
else if(options.Version)
{
Version();
return 0;
}
Help();
return 1;
}
public async Task<int> RunAsync(string[] args)
{
if (!args.Any())
{
Help();
return 1;
}
var command = default(Command);
if (args.Length > 1)
{
if (!Command.TryParse(args[0], args[1], out command))
{
if (!Command.TryParse(args[0], out command))
{
return HandleOptionsOnly(args);
}
}
}
else if (!Command.TryParse(args[0], out command))
{
return HandleOptionsOnly(args);
}
var optionArgs = args.Skip(2).TakeWhile(x => x.Length > 0 && x[0] == '-');
var options = Options.Parse(optionArgs);
if (options.Help)
{
Help();
return 0;
}
else if (options.Version)
{
Version();
return 0;
}
var contentArgs = args.Skip(2).SkipWhile(x => x.Length > 0 && x[0] == '-');
var stderr = _stderr();
var stderrWriter = new StreamWriter(stderr) { AutoFlush = true };
var stdout = _stdout();
var stdoutWriter = new StreamWriter(stdout) { AutoFlush = true };
{
var renderer = new Renderer(stdoutWriter, stderrWriter);
var http = CreateHttpClient(options);
var request = new HttpRequestMessage(
command.Method ?? HttpMethod.Get,
command.Uri
);
if (_useStdin)
{
var stream = _stdin();
request.Content = new StreamContent(stream);
}
var groups = ParseContents(contentArgs)
.GroupBy(content => content.ContentLocation)
.OrderBy(group => group.Key);
foreach (var group in groups)
{
switch (group.Key)
{
case ContentLocation.Body:
request.Content = RequestContentFormatter.As(options.RequestContentType, group, options.XmlRootName);
break;
case ContentLocation.Header:
AddHeaders(request, group);
break;
}
}
if (!request.Headers.UserAgent.Any())
{
request.Headers.UserAgent.Add(
new ProductInfoHeaderValue(
"dotnet-https",
typeof(Program).Assembly.GetName().Version.ToString()
)
);
}
try
{
var response = await http.SendAsync(request);
await renderer.WriteResponse(response);
}
catch (TaskCanceledException ex)
{
renderer.WriteException(ex);
return 1;
}
catch (OperationCanceledException ex)
{
renderer.WriteException(ex);
return 1;
}
catch (HttpRequestException ex)
{
renderer.WriteException(ex);
return 1;
}
}
stderrWriter.Flush();
stdoutWriter.Flush();
return 0;
}
static HttpClient CreateHttpClient(Options options)
{
var http = default(HttpClient);
if (options.RequiresHandler)
{
var handler = new HttpClientHandler();
if (options.IgnoreCertificate)
{
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
}
if (options.StopAutoRedirects)
{
handler.AllowAutoRedirect = false;
}
http = new HttpClient(handler);
}
else
{
http = new HttpClient();
}
if (options.Timeout.HasValue)
{
http.Timeout = options.Timeout.Value;
}
return http;
}
}
enum ContentType
{
Json = 1,
FormUrlEncoded = 2,
Xml = 3
}
class Options
{
public ContentType RequestContentType { get; }
public string XmlRootName { get; }
public bool IgnoreCertificate { get; }
public TimeSpan? Timeout { get; }
public bool Version { get; }
public bool Help { get; }
public bool StopAutoRedirects { get; }
public bool RequiresHandler => IgnoreCertificate || StopAutoRedirects;
public Options(ContentType requestContentType, string xmlRootName, bool ignoreCertificate, TimeSpan? timeout, bool version, bool help, bool stopAutoRedirects)
{
RequestContentType = requestContentType;
XmlRootName = xmlRootName;
IgnoreCertificate = ignoreCertificate;
Timeout = timeout;
Version = version;
Help = help;
StopAutoRedirects = stopAutoRedirects;
}
public static IEnumerable<string> GetOptionHelp()
{
yield return "--form Renders the content arguments as application/x-www-form-urlencoded";
yield return "--help Show command line help.";
yield return "--ignore-certificate Prevents server certificate validation.";
yield return "--json Renders the content arguments as application/json.";
yield return "--timeout=<VALUE> Sets the timeout of the request using System.TimeSpan.TryParse (https://docs.microsoft.com/en-us/dotnet/api/system.timespan.parse)";
yield return "--version Displays the application verison.";
yield return "--xml=<ROOT_NAME> Renders the content arguments as application/xml using the optional xml root name.";
yield return "--stop-auto-redirects Prevents redirects from automatically being processed.";
}
static int GetArgValueIndex(string arg)
{
var equalsIndex = arg.IndexOf('=');
var spaceIndex = arg.IndexOf(' ');
var index = equalsIndex > -1 && spaceIndex > -1
? Math.Min(equalsIndex, spaceIndex)
: Math.Max(equalsIndex, spaceIndex);
return index == -1 ? index : index + 1;
}
public static Options Parse(IEnumerable<string> args)
{
var requestContentType = ContentType.Json;
var xmlRootName = default(string);
var ignoreCertificate = false;
var timeout = default(TimeSpan?);
var help = false;
var version = false;
var stopAutoRedirects = false;
foreach (var arg in args)
{
if (arg.StartsWith("--json"))
{
requestContentType = ContentType.Json;
}
else if (arg.StartsWith("--xml"))
{
var index = GetArgValueIndex(arg);
if (index == -1)
{
xmlRootName = "xml";
}
else
{
xmlRootName = arg.Substring(index).Trim();
if (string.IsNullOrEmpty(xmlRootName))
{
xmlRootName = "xml";
}
}
requestContentType = ContentType.Xml;
}
else if (arg.StartsWith("--form"))
{
requestContentType = ContentType.FormUrlEncoded;
}
else if (arg.StartsWith("--ignore-certificate"))
{
ignoreCertificate = true;
}
else if (arg.StartsWith("--timeout"))
{
var index = GetArgValueIndex(arg);
if (index > -1)
{
var s = arg.Substring(index).Trim();
if (TimeSpan.TryParse(s, out var to) && to > TimeSpan.Zero)
{
timeout = to;
}
}
}
else if (arg.StartsWith("--version"))
{
version = true;
}
else if (arg.StartsWith("--help") || arg.StartsWith("-?") || arg.StartsWith("help"))
{
help = true;
}
else if (arg.StartsWith("--stop-auto-redirects"))
{
stopAutoRedirects = true;
}
}
return new Options(requestContentType, xmlRootName, ignoreCertificate, timeout, version, help, stopAutoRedirects);
}
}
enum ContentLocation
{
Body = 1,
Header = 2
}
class Content
{
public ContentLocation ContentLocation { get; }
public string Property { get; }
public string Value { get; }
Content(ContentLocation contentLocation, string property, string value)
{
ContentLocation = contentLocation;
Property = property;
Value = value;
}
public static bool TryParse(string s, out Content content)
{
var equalsIndex = s.IndexOf('=');
var colonIndex = s.IndexOf(':');
if (equalsIndex == -1 && colonIndex == -1)
{
content = default;
return false;
}
var contentType = default(ContentLocation);
var index = default(int);
if (equalsIndex > -1 && colonIndex > -1)
{
if (equalsIndex < colonIndex)
{
contentType = ContentLocation.Body;
index = equalsIndex;
}
else
{
contentType = ContentLocation.Header;
index = colonIndex;
}
}
else if (equalsIndex > -1)
{
contentType = ContentLocation.Body;
index = equalsIndex;
}
else
{
contentType = ContentLocation.Header;
index = colonIndex;
}
var property = s.Substring(0, index);
if (property.Length == 0)
{
content = default;
return false;
}
var value = s.Substring(index + 1);
content = new Content(contentType, property, value);
return true;
}
}
class Renderer
{
readonly StreamWriter _output;
readonly StreamWriter _info;
public Renderer(StreamWriter output, StreamWriter info)
{
_output = output;
_info = info;
}
public async Task WriteResponse(HttpResponseMessage response)
{
_info.Write("HTTP/");
_info.Write(response.Version);
_info.Write(" ");
_info.Write((int)response.StatusCode);
_info.Write(" ");
_info.WriteLine(response.ReasonPhrase);
WriteHeaders(response.Headers, response.Content.Headers);
await ResponseContentFormatter.As(response, _output);
}
public void WriteHeaders(HttpResponseHeaders responseHeaders, HttpContentHeaders contentHeaders)
{
var headers = responseHeaders.Concat(contentHeaders);
foreach (var header in headers)
{
foreach (var value in header.Value)
{
_info.Write(header.Key);
_info.Write(":");
_info.Write(" ");
_info.WriteLine(value);
}
}
}
public void WriteException(Exception ex)
{
var help = WriteException(ex, 0);
switch (help)
{
case ExceptionHelp.Timeout:
_info.WriteLine("Request failed to complete within timeout. Try increasing the timeout with the --timeout flag");
break;
case ExceptionHelp.IgnoreCertificate:
_info.WriteLine("Ensure you trust the server certificate or try using the --ignore-certificate flag");
break;
}
}
ExceptionHelp WriteException(Exception ex, int depth)
{
if (depth > 0)
{
_info.Write(new string('\t', depth));
}
_info.WriteLine(ex.Message);
var exceptionHelp = ExceptionHelp.None;
if (ex is TaskCanceledException || ex is OperationCanceledException)
{
return ExceptionHelp.Timeout;
}
else
{
switch (ex.Message)
{
case "The SSL connection could not be established, see inner exception.":
exceptionHelp = ExceptionHelp.IgnoreCertificate;
break;
}
}
if (ex.InnerException != null)
{
var otherHelp = WriteException(ex.InnerException, depth + 1);
if (otherHelp != ExceptionHelp.None)
{
return otherHelp;
}
}
return exceptionHelp;
}
enum ExceptionHelp
{
None = 0,
IgnoreCertificate = 1,
Timeout = 2
}
}
struct Command
{
public HttpMethod Method { get; }
public Uri Uri { get; }
Command(Uri uri)
{
Method = default;
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
Command(HttpMethod method, Uri uri)
{
Method = method ?? throw new ArgumentNullException(nameof(method));
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
static bool StartsWithHttp(string s) =>
s.Length > 6 && s[0] == 'h' && s[1] == 't' && s[2] == 't' && s[3] == 'p' && (s[4] == ':' || (s[4] == 's' && s[5] == ':'));
static bool TryParseUri(string s, out Uri uri)
{
if (!StartsWithHttp(s))
{
s = "https://" + s;
}
return Uri.TryCreate(s, UriKind.Absolute, out uri);
}
static bool TryParseMethod(string s, out HttpMethod method)
{
if (s.Equals(nameof(HttpMethod.Delete), StringComparison.OrdinalIgnoreCase))
{
method = HttpMethod.Delete;
return true;
}
else if (s.Equals(nameof(HttpMethod.Get), StringComparison.OrdinalIgnoreCase))
{
method = HttpMethod.Get;
return true;
}
else if (s.Equals(nameof(HttpMethod.Head), StringComparison.OrdinalIgnoreCase))
{
method = HttpMethod.Head;
return true;
}
else if (s.Equals(nameof(HttpMethod.Options), StringComparison.OrdinalIgnoreCase))
{
method = HttpMethod.Options;
return true;
}
else if (s.Equals(nameof(HttpMethod.Patch), StringComparison.OrdinalIgnoreCase))
{
method = HttpMethod.Patch;
return true;
}
else if (s.Equals(nameof(HttpMethod.Post), StringComparison.OrdinalIgnoreCase))
{
method = HttpMethod.Post;
return true;
}
else if (s.Equals(nameof(HttpMethod.Put), StringComparison.OrdinalIgnoreCase))
{
method = HttpMethod.Put;
return true;
}
else if (s.Equals(nameof(HttpMethod.Trace), StringComparison.OrdinalIgnoreCase))
{
method = HttpMethod.Trace;
return true;
}
method = default;
return false;
}
public static bool TryParse(string methodText, string uriText, out Command command)
{
if (TryParseMethod(methodText, out var method) && TryParseUri(uriText, out var uri))
{
command = new Command(method, uri);
return true;
}
else
{
command = default;
return false;
}
}
public static bool TryParse(string s, out Command command)
{
s = s.Trim();
if (s.StartsWith('-') || s == "help")
{
command = default;
return false;
}
var index = s.IndexOf(' ');
if (index == -1)
{
if (TryParseUri(s, out var uri))
{
command = new Command(uri);
return true;
}
else
{
command = default;
return false;
}
}
else
{
var methodText = s.Substring(0, index);
var uriText = s.Substring(index + 1);
return TryParse(methodText, uriText, out command);
}
}
}
}