-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpRequest.cs
More file actions
435 lines (380 loc) · 16.4 KB
/
HttpRequest.cs
File metadata and controls
435 lines (380 loc) · 16.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
using System;
using System.Collections;
using System.Data.SqlTypes;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Diagnostics;
using Microsoft.SqlServer.Server;
using System.Linq;
namespace HttpRequestLibrary
{
public class HttpRequest
{
private static readonly string[] ValidHttpMethods =
{
"GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS", "TRACE"
};
// Limites para rodar dentro do SQL Server (CLR)
private const int MaxPayloadSize = 20 * 1024 * 1024; // 20MB
private const int MaxResponseSize = 20 * 1024 * 1024; // 20MB
private const int MaxErrorResponseSize = 512 * 1024; // 512KB
private const int DefaultTimeoutMilliseconds = 120_000; // 120s
private class HttpResponse
{
public int StatusCode { get; set; }
public string Response { get; set; }
public long Timing { get; set; }
}
[SqlFunction(
DataAccess = DataAccessKind.None,
FillRowMethodName = "FillRow",
TableDefinition = "statusCode INT, response NVARCHAR(MAX), timing BIGINT")]
public static IEnumerable DllHttpRequest(
SqlString method,
SqlString url,
SqlString headers,
SqlInt32 timeout,
SqlString payload,
SqlBoolean skipCertificateValidation)
{
try { EnableUnsafeHeaderParsing(); } catch { /* Ignora se falhar por permissão */ }
var result = new HttpResponse();
var stopwatch = Stopwatch.StartNew();
bool hasError = false;
// guarda o callback original para restaurar depois
var originalCertValidation = ServicePointManager.ServerCertificateValidationCallback;
try
{
Uri uri = null;
// SqlBoolean: True => entra, False/Null => não entra (opção segura)
if (skipCertificateValidation)
{
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) =>
{
// aceita todos os certificados
return true;
};
}
// 1. Configuração de Segurança / Conexões (nível AppDomain)
try
{
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
}
catch { }
// 2. Tenta injetar o TLS 1.3
try
{
const int Tls13Value = 12288;
ServicePointManager.SecurityProtocol |= (SecurityProtocolType)Tls13Value;
}
catch
{
// O ambiente (Windows/CLR) é antigo e não suporta TLS 1.3.
// Vida que segue com o TLS mais seguro disponível.
}
ServicePointManager.Expect100Continue = false;
if (ServicePointManager.DefaultConnectionLimit < 512)
ServicePointManager.DefaultConnectionLimit = 512;
// 2. Validações de Entrada
if (method.IsNull || string.IsNullOrWhiteSpace(method.Value))
{
SetError(result, 400, "Error: METHOD_REQUIRED");
hasError = true;
}
else if (url.IsNull ||
string.IsNullOrWhiteSpace(url.Value) ||
!Uri.TryCreate(url.Value, UriKind.Absolute, out uri))
{
SetError(result, 400, "Error: INVALID_URL");
hasError = true;
}
else if (!Array.Exists(
ValidHttpMethods,
m => m.Equals(method.Value, StringComparison.OrdinalIgnoreCase)))
{
SetError(result, 400, "Error: INVALID_HTTP_METHOD");
hasError = true;
}
// Timeout: NULL => default, negativo => erro
int timeoutValue = DefaultTimeoutMilliseconds;
if (!timeout.IsNull)
{
if (timeout.Value < 0)
{
SetError(result, 400, "Error: INVALID_TIMEOUT");
hasError = true;
}
else
{
timeoutValue = timeout.Value;
}
}
// 3. Execução da Requisição
if (!hasError)
{
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = method.Value.ToUpperInvariant();
request.Timeout = timeoutValue;
request.ReadWriteTimeout = timeoutValue;
request.UserAgent = "HttpRequestLibrary/1.0";
request.KeepAlive = false;
// 3.1 Headers
if (!headers.IsNull && !string.IsNullOrWhiteSpace(headers.Value))
{
try
{
ApplyHeadersFromJson(headers.Value, request);
}
catch (JsonException ex)
{
SetError(result, 400, $"Error: HEADERS_JSON_INVALID - {ex.Message}");
hasError = true;
}
catch (ArgumentException ex)
{
SetError(result, 400, $"Error: HEADERS_INVALID - {ex.Message}");
hasError = true;
}
catch (Exception ex)
{
SetError(result, 500, $"Error: HEADERS_UNEXPECTED - {ex.Message}");
hasError = true;
}
}
// 3.2 Payload
if (!hasError &&
!payload.IsNull &&
request.Method != "GET" &&
request.Method != "HEAD")
{
string payloadValue = payload.Value ?? string.Empty;
byte[] payloadBytes = Encoding.UTF8.GetBytes(payloadValue);
if (payloadBytes.Length > MaxPayloadSize)
{
SetError(
result,
413,
$"Error: PAYLOAD_TOO_LARGE (max {MaxPayloadSize} bytes)");
hasError = true;
}
else
{
if (string.IsNullOrEmpty(request.ContentType))
request.ContentType = "application/json";
request.ContentLength = payloadBytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(payloadBytes, 0, payloadBytes.Length);
}
}
}
// 3.3 Envio
if (!hasError)
{
// mede apenas a latência da chamada HTTP
stopwatch.Restart();
using (var response = (HttpWebResponse)request.GetResponse())
{
result.StatusCode = (int)response.StatusCode;
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
Encoding encoding = GetEncoding(response.ContentType);
result.Response = ReadStreamWithLimit(
responseStream,
MaxResponseSize,
encoding);
}
else
{
result.Response = string.Empty;
}
}
}
result.Timing = stopwatch.ElapsedMilliseconds;
}
}
}
catch (WebException ex)
{
if (stopwatch.IsRunning)
stopwatch.Stop();
result.Timing = stopwatch.ElapsedMilliseconds;
if (ex.Status == WebExceptionStatus.Timeout)
{
result.StatusCode = 408;
result.Response = "Error: REQUEST_TIMEOUT";
}
else if (ex.Response is HttpWebResponse errorResponse)
{
result.StatusCode = (int)errorResponse.StatusCode;
try
{
using (errorResponse)
using (var responseStream = errorResponse.GetResponseStream())
{
if (responseStream != null)
{
Encoding encoding = GetEncoding(errorResponse.ContentType);
result.Response = ReadStreamWithLimit(
responseStream,
MaxErrorResponseSize,
encoding);
}
else
{
result.Response = $"Error: HTTP_{result.StatusCode}_NO_BODY";
}
}
}
catch (Exception innerEx)
{
result.Response =
$"Error: WEB_EXCEPTION_BODY_READ_FAILED - {ex.Message} -> {innerEx.Message}";
}
}
else
{
result.StatusCode = 0;
result.Response = $"Error: CONNECTION_FAILURE ({ex.Status}) - {ex.Message}";
}
}
catch (Exception ex)
{
if (stopwatch.IsRunning)
stopwatch.Stop();
result.Timing = stopwatch.ElapsedMilliseconds;
result.StatusCode = 0;
result.Response = $"Error: UNEXPECTED_EXCEPTION - {ex.GetType().Name}: {ex.Message}";
}
finally
{
// restaura sempre o callback original (evita ficar inseguro para sempre)
ServicePointManager.ServerCertificateValidationCallback = originalCertValidation;
if (stopwatch.IsRunning)
stopwatch.Stop();
if (result.Timing <= 0)
result.Timing = stopwatch.ElapsedMilliseconds;
}
yield return result;
}
public static void FillRow(
object obj,
out SqlInt32 statusCode,
out SqlString response,
out SqlInt64 timing)
{
var result = (HttpResponse)obj;
statusCode = result.StatusCode;
response = result.Response ?? SqlString.Null;
timing = result.Timing;
}
// --------- Helpers Privados ---------
private static void SetError(HttpResponse result, int statusCode, string message)
{
result.StatusCode = statusCode;
result.Response = message;
}
private static void ApplyHeadersFromJson(string json, HttpWebRequest request)
{
var headerList = JsonSerializer.Deserialize<JsonElement[]>(json);
if (headerList == null)
throw new ArgumentException("Headers cannot be null.");
foreach (var header in headerList)
{
if (header.ValueKind != JsonValueKind.Object)
throw new ArgumentException("Each header must be a JSON object.");
var properties = header.EnumerateObject().ToList();
if (properties.Count != 1)
throw new ArgumentException("Each header object must have exactly one key-value pair.");
var property = properties[0];
string key = property.Name;
string value = property.Value.GetString();
if (string.IsNullOrEmpty(key) || value == null)
continue;
if (key.IndexOfAny(new[] { '\r', '\n' }) >= 0 ||
value.IndexOfAny(new[] { '\r', '\n' }) >= 0)
{
throw new ArgumentException("Invalid characters in header.");
}
if (key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase))
{
request.ContentType = value;
}
else if (key.Equals("User-Agent", StringComparison.OrdinalIgnoreCase))
{
request.UserAgent = value;
}
else
{
request.Headers.Add(key, value);
}
}
}
private static string ReadStreamWithLimit(Stream stream, int maxSize, Encoding encoding)
{
if (stream == null)
return string.Empty;
if (encoding == null)
encoding = Encoding.UTF8;
byte[] buffer = new byte[8192];
using (var ms = new MemoryStream())
{
int bytesRead;
int totalBytes = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytes += bytesRead;
if (totalBytes > maxSize)
throw new InvalidOperationException(
$"Response limit exceeded ({maxSize / 1024 / 1024} MB)");
ms.Write(buffer, 0, bytesRead);
}
return encoding.GetString(ms.ToArray());
}
}
private static Encoding GetEncoding(string contentType)
{
if (!string.IsNullOrEmpty(contentType))
{
try
{
string[] parts = contentType.Split(';');
foreach (var part in parts)
{
string trimmed = part.Trim();
if (trimmed.StartsWith("charset=", StringComparison.OrdinalIgnoreCase))
{
string charset = trimmed.Substring("charset=".Length)
.Trim('"', '\'');
if (!string.IsNullOrEmpty(charset))
{
return Encoding.GetEncoding(charset);
}
}
}
}
catch
{
// Charset inválido: cai para UTF-8
}
}
return Encoding.UTF8;
}
private static void EnableUnsafeHeaderParsing()
{
var assembly = typeof(System.Net.Configuration.SettingsSection).Assembly;
var settingsType = assembly.GetType("System.Net.Configuration.SettingsSectionInternal");
var args = new object[0];
var instance = settingsType.GetProperty("Section", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).GetValue(null, args);
var useUnsafeHeaderParsingField = settingsType.GetField("useUnsafeHeaderParsing", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (useUnsafeHeaderParsingField != null)
{
useUnsafeHeaderParsingField.SetValue(instance, true);
}
}
}
}