Class: Winhttp::Session
- Inherits:
-
Object
- Object
- Winhttp::Session
- Defined in:
- lib/winhttp.rb,
ext/winhttp/winhttp.c
Overview
One async WinHTTP session handle plus its configuration. Thread-safe and fiber-safe: any number of threads/fibers may issue requests concurrently.
Instance Attribute Summary collapse
-
#revocation ⇒ Object
readonly
The effective revocation policy, settled at construction.
Class Method Summary collapse
-
._open(*args) ⇒ Object
Winhttp::Session._open(ua, access_type, proxy, bypass, connect_ms, send_ms, receive_ms, (-1 == unset) http2, decompress, redirect_policy, max_redirects, revocation) revocation: 0 none / 1 best_effort / 2 strict Returns [session, effective_revocation_int].
-
.new(user_agent: "winhttp-ruby/#{Winhttp::VERSION}", proxy: :system, proxy_bypass: nil, http2: true, decompress: true, revocation: :best_effort, redirects: 10, connect_timeout: nil, send_timeout: nil, receive_timeout: nil) ⇒ Object
Open a Session.
-
.open(**opts) ⇒ Object
Open a session and ensure-close it around the block (block form).
Instance Method Summary collapse
- #_live ⇒ Object
-
#_mark_closed ⇒ Object
Mark the session closed FIRST (GVL-held, strictly before any handle is closed): new requests / _start's re-check raise Winhttp::Closed.
-
#_start(req_obj, vverb, vhost, vport, vsecure, vpath, vblob, vbody, vrev) ⇒ Object
Session#_start(req_obj, verb, host, port, secure, path, header_blob, body, effective_revocation) -> id (Integer).
-
#_try_close_handle ⇒ Object
Close the session handle iff live == 0.
-
#close ⇒ Object
Close the session: mark closed FIRST (new requests raise Closed), abort every in-flight request (those raise Canceled), wait — bounded, <= 5 s — for the OS to finish teardown, then close the session handle.
- #closed? ⇒ Boolean
- #delete(url, headers: nil, timeout: nil, &chunk) ⇒ Object
- #get(url, headers: nil, timeout: nil, &chunk) ⇒ Object
- #head(url, headers: nil, timeout: nil) ⇒ Object
- #patch(url, body:, headers: nil, timeout: nil, &chunk) ⇒ Object
- #post(url, body: "", headers: nil, timeout: nil, &chunk) ⇒ Object
- #put(url, body:, headers: nil, timeout: nil, &chunk) ⇒ Object
- #request(method, url, body: nil, headers: nil, timeout: nil, &chunk) ⇒ Object
Instance Attribute Details
#revocation ⇒ Object (readonly)
The effective revocation policy, settled at construction.
277 278 279 |
# File 'lib/winhttp.rb', line 277 def revocation @revocation end |
Class Method Details
._open(*args) ⇒ Object
Winhttp::Session._open(ua, access_type, proxy, bypass, connect_ms, send_ms, receive_ms, (-1 == unset) http2, decompress, redirect_policy, max_redirects, revocation) revocation: 0 none / 1 best_effort / 2 strict Returns [session, effective_revocation_int].
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 |
# File 'ext/winhttp/winhttp.c', line 370
static VALUE
ses_open(int argc, VALUE *argv, VALUE klass)
{
VALUE vua, vaccess, vproxy, vbypass, vct, vst, vrt, vh2, vdec, vrp, vmaxr, vrev;
VALUE obj;
whses **slot;
whses *s;
HINTERNET hs;
WCHAR *ua = NULL, *proxy = NULL, *bypass = NULL;
DWORD access, gle;
long long ct, st, rt;
int want_h2, want_dec, redirect_policy, rev;
long long maxr;
DWORD secure_protocols;
int effective_rev;
/* We pass exactly 12 positional args from Ruby; read them directly. */
if (argc != 12) rb_raise(rb_eArgError, "winhttp: _open arity");
vua = argv[0]; vaccess = argv[1]; vproxy = argv[2]; vbypass = argv[3];
vct = argv[4]; vst = argv[5]; vrt = argv[6];
vh2 = argv[7]; vdec = argv[8]; vrp = argv[9]; vmaxr = argv[10]; vrev = argv[11];
access = (DWORD)NUM2ULONG(vaccess);
ct = NUM2LL(vct); st = NUM2LL(vst); rt = NUM2LL(vrt);
want_h2 = RTEST(vh2); want_dec = RTEST(vdec);
redirect_policy = NUM2INT(vrp);
maxr = NUM2LL(vmaxr);
rev = NUM2INT(vrev);
/* Convert all strings up front (TypeError here is clean: no handle yet). */
ua = to_wide(vua);
if (!NIL_P(vproxy)) proxy = to_wide(vproxy);
if (!NIL_P(vbypass)) bypass = to_wide(vbypass);
obj = ses_alloc(klass);
TypedData_Get_Struct(obj, whses *, &ses_type, slot);
hs = WinHttpOpen(ua, access,
proxy ? proxy : WINHTTP_NO_PROXY_NAME,
bypass ? bypass : WINHTTP_NO_PROXY_BYPASS,
WINHTTP_FLAG_ASYNC);
gle = GetLastError();
xfree(ua);
if (proxy) xfree(proxy);
if (bypass) xfree(bypass);
if (!hs) raise_code(eOSError, "WinHttpOpen", gle);
/* Register the status callback ONCE on the session before any child handle
* (inherited by derived handles). */
if (WinHttpSetStatusCallback(hs, status_callback,
WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0)
== WINHTTP_INVALID_STATUS_CALLBACK) {
gle = GetLastError();
WinHttpCloseHandle(hs);
raise_code(eOSError, "WinHttpSetStatusCallback", gle);
}
/* Timeouts (resolve fixed at 0 == default-infinite resolve; others only
* when the caller supplied them; -1 means "leave the WinHTTP default"). */
if (ct >= 0 || st >= 0 || rt >= 0) {
int cms = (int)(ct >= 0 ? ct : 0);
int sms = (int)(st >= 0 ? st : 30000);
int rms = (int)(rt >= 0 ? rt : 30000);
if (!WinHttpSetTimeouts(hs, 0, cms, sms, rms)) {
gle = GetLastError();
WinHttpCloseHandle(hs);
raise_code(eOSError, "WinHttpSetTimeouts", gle);
}
}
/* TLS floor: always TLS1.2|TLS1.3, fall back to TLS1.2 alone, else raise. */
secure_protocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 |
WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3;
if (!set_dword_opt(hs, WINHTTP_OPTION_SECURE_PROTOCOLS, secure_protocols)) {
secure_protocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
if (!set_dword_opt(hs, WINHTTP_OPTION_SECURE_PROTOCOLS, secure_protocols)) {
gle = GetLastError();
WinHttpCloseHandle(hs);
raise_code(eOSError, "WinHttpSetOption(SECURE_PROTOCOLS)", gle);
}
}
/* HTTP/2 + decompression: best-effort, a rejecting OS degrades silently. */
if (want_h2)
set_dword_opt(hs, WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL,
WINHTTP_PROTOCOL_FLAG_HTTP2);
if (want_dec)
set_dword_opt(hs, WINHTTP_OPTION_DECOMPRESSION,
WINHTTP_DECOMPRESSION_FLAG_ALL);
/* Redirect policy + max count. */
set_dword_opt(hs, WINHTTP_OPTION_REDIRECT_POLICY, (DWORD)redirect_policy);
if (maxr >= 0)
set_dword_opt(hs, WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS, (DWORD)maxr);
/* Revocation policy is settled here by probing throwaway handles (neither
* call touches the network; both probe handles are context-less, so their
* HANDLE_CLOSING arrives as id 0 and the pump drops it). */
effective_rev = 0; /* :none default */
if (rev != 0) {
HINTERNET hc = WinHttpConnect(hs, L"localhost", 80, 0);
if (hc) {
HINTERNET hrq = WinHttpOpenRequest(hc, L"GET", L"/", NULL,
WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (hrq) {
BOOL ok_rev = set_dword_opt(hrq, WINHTTP_OPTION_ENABLE_FEATURE,
WINHTTP_ENABLE_SSL_REVOCATION);
if (rev == 2) {
/* :strict — revocation must be available, else raise. */
if (ok_rev) {
effective_rev = 2;
} else {
gle = GetLastError();
WinHttpCloseHandle(hrq);
WinHttpCloseHandle(hc);
WinHttpCloseHandle(hs);
raise_code(eOSError,
"WinHttpSetOption(ENABLE_SSL_REVOCATION)", gle);
}
} else {
/* :best_effort — both options must succeed, else degrade. */
BOOL ok_off = ok_rev &&
set_dword_opt(hrq, WINHTTP_OPTION_IGNORE_CERT_REVOCATION_OFFLINE,
TRUE);
effective_rev = (ok_rev && ok_off) ? 1 : 0;
}
WinHttpCloseHandle(hrq);
} else if (rev == 2) {
gle = GetLastError();
WinHttpCloseHandle(hc);
WinHttpCloseHandle(hs);
raise_code(eOSError, "WinHttpOpenRequest(probe)", gle);
}
WinHttpCloseHandle(hc);
} else if (rev == 2) {
gle = GetLastError();
WinHttpCloseHandle(hs);
raise_code(eOSError, "WinHttpConnect(probe)", gle);
}
}
s = (whses *)calloc(1, sizeof(whses));
if (!s) { WinHttpCloseHandle(hs); rb_raise(rb_eNoMemError, "winhttp: out of memory"); }
s->hsession = hs;
s->live = 0;
s->closed = 0;
s->wrapper_gone = 0;
*slot = s;
return rb_ary_new3(2, obj, INT2NUM(effective_rev));
}
|
.new(user_agent: "winhttp-ruby/#{Winhttp::VERSION}", proxy: :system, proxy_bypass: nil, http2: true, decompress: true, revocation: :best_effort, redirects: 10, connect_timeout: nil, send_timeout: nil, receive_timeout: nil) ⇒ Object
Open a Session. See the gem README for the full option contract.
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 |
# File 'lib/winhttp.rb', line 280 def self.new(user_agent: "winhttp-ruby/#{Winhttp::VERSION}", proxy: :system, proxy_bypass: nil, http2: true, decompress: true, revocation: :best_effort, redirects: 10, connect_timeout: nil, send_timeout: nil, receive_timeout: nil) access, proxy_str = resolve_proxy(proxy, proxy_bypass) rev_int = REVOCATION_INT[revocation] raise ArgumentError, "winhttp: revocation must be :best_effort/:strict/:none" unless rev_int unless redirects.is_a?(Integer) && (0..65_535).cover?(redirects) raise ArgumentError, "winhttp: redirects must be an Integer in 0..65535" end redirect_policy = redirects.zero? ? REDIRECT_NEVER : REDIRECT_DISALLOW_HTTPS_TO_HTTP ct = ms_or_unset(connect_timeout, "connect_timeout") st = ms_or_unset(send_timeout, "send_timeout") rt = ms_or_unset(receive_timeout, "receive_timeout") session, eff = _open(user_agent.to_s, access, proxy_str, proxy_bypass, ct, st, rt, http2 ? true : false, decompress ? true : false, redirect_policy, redirects, rev_int) session.send(:finish_init, REVOCATION_SYM[eff], rev_int) session end |
.open(**opts) ⇒ Object
Open a session and ensure-close it around the block (block form).
348 349 350 351 352 353 354 355 356 357 |
# File 'lib/winhttp.rb', line 348 def self.open(**opts) s = new(**opts) return s unless block_given? begin yield s ensure s.close end end |
Instance Method Details
#_live ⇒ Object
549 550 551 552 |
# File 'ext/winhttp/winhttp.c', line 549
static VALUE ses_live_count(VALUE self) {
whses *s = ses_ptr(self);
return s ? LONG2NUM(s->live) : INT2NUM(0);
}
|
#_mark_closed ⇒ Object
Mark the session closed FIRST (GVL-held, strictly before any handle is closed): new requests / _start's re-check raise Winhttp::Closed. Returns the raw HINTERNET so Ruby can sequence the abort sweep before _close_handle.
531 532 533 534 535 536 |
# File 'ext/winhttp/winhttp.c', line 531
static VALUE ses_mark_closed(VALUE self) {
whses *s = ses_ptr(self);
if (!s) return Qnil;
s->closed = 1;
return Qnil;
}
|
#_start(req_obj, vverb, vhost, vport, vsecure, vpath, vblob, vbody, vrev) ⇒ Object
Session#_start(req_obj, verb, host, port, secure, path, header_blob, body, effective_revocation) -> id (Integer)
One raise-hygienic C frame. The Request wrapper (req_obj) is allocated in Ruby and passed in so its free hook owns the handles from the instant they exist. Holds the GVL throughout (§3.5), so the ses->closed re-check is race-free against Session#close.
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 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 |
# File 'ext/winhttp/winhttp.c', line 656
static VALUE
req_start(VALUE self, VALUE req_obj, VALUE vverb, VALUE vhost, VALUE vport,
VALUE vsecure, VALUE vpath, VALUE vblob, VALUE vbody, VALUE vrev)
{
whses *ses = ses_ptr(self);
whreq **slot;
whreq *r;
WCHAR *verb = NULL, *host = NULL, *path = NULL, *blob = NULL;
INTERNET_PORT port = (INTERNET_PORT)NUM2UINT(vport);
int secure = RTEST(vsecure);
int rev = NUM2INT(vrev);
DWORD open_flags = secure ? WINHTTP_FLAG_SECURE : 0;
DWORD gle;
uint64_t id;
if (!ses || ses->closed)
rb_raise(eClosed, "winhttp: session is closed");
TypedData_Get_Struct(req_obj, whreq *, &req_type, slot);
/* Coerce/convert all strings up front (raise-clean: no control block yet). */
verb = to_wide(vverb);
host = to_wide(vhost);
path = to_wide(vpath);
if (!NIL_P(vblob)) blob = to_wide(vblob);
/* Allocate the control block + buffers (plain malloc; free on failure and
* raise manually so an OOM longjmp can't leak the wide strings). */
r = (whreq *)calloc(1, sizeof(whreq));
if (r) r->rbuf = (unsigned char *)malloc(RBUF_CAP);
if (!r || !r->rbuf) {
if (r) free(r);
xfree(verb); xfree(host); xfree(path); if (blob) xfree(blob);
rb_raise(rb_eNoMemError, "winhttp: out of memory");
}
r->ses = ses;
*slot = r; /* the wrapper free hook owns r from here on */
/* Copy the body into a private buffer (WinHTTP does not copy buffers). */
if (!NIL_P(vbody)) {
long blen;
StringValue(vbody);
blen = RSTRING_LEN(vbody);
if (blen > 0) {
r->body = (unsigned char *)malloc((size_t)blen);
if (!r->body) {
xfree(verb); xfree(host); xfree(path); if (blob) xfree(blob);
rb_raise(rb_eNoMemError, "winhttp: out of memory");
}
memcpy(r->body, RSTRING_PTR(vbody), (size_t)blen);
r->body_len = (size_t)blen;
}
}
/* Re-check ses->closed (TOCTOU close — §3.4/§5.25): GVL-held, race-free. */
if (ses->closed) {
xfree(verb); xfree(host); xfree(path); if (blob) xfree(blob);
rb_raise(eClosed, "winhttp: session is closed");
}
r->hconn = WinHttpConnect(ses->hsession, host, port, 0);
if (!r->hconn) {
gle = GetLastError();
xfree(verb); xfree(host); xfree(path); if (blob) xfree(blob);
/* pre-arm cleanup: no context, immediate free is safe (free hook). */
raise_code(class_for_code(gle), "WinHttpConnect", gle);
}
r->hreq = WinHttpOpenRequest(r->hconn, verb, path, NULL,
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
open_flags);
if (!r->hreq) {
gle = GetLastError();
xfree(verb); xfree(host); xfree(path); if (blob) xfree(blob);
raise_code(class_for_code(gle), "WinHttpOpenRequest", gle);
}
xfree(verb); xfree(host); xfree(path); /* done with these */
/* Registration strictly before arming, so an armed context always has a
* table entry. */
id = g_next_id++;
r->id = id;
st_insert(g_reqs, (st_data_t)id, (st_data_t)r);
ses->live++;
/* Arm the context value before anything can complete (§5.10): this is what
* makes HANDLE_CLOSING with our id guaranteed. */
{
DWORD_PTR ctxv = (DWORD_PTR)id;
if (!WinHttpSetOption(r->hreq, WINHTTP_OPTION_CONTEXT_VALUE,
&ctxv, sizeof(ctxv))) {
gle = GetLastError();
/* roll back registration; still pre-arm (ctx not set) => free now. */
st_delete(g_reqs, (st_data_t *)&id, NULL);
ses->live--;
if (blob) xfree(blob);
raise_code(class_for_code(gle), "WinHttpSetOption(CONTEXT_VALUE)", gle);
}
r->ctx_armed = 1;
}
/* --- post-arm regime: any failure leaves the block registered + live
* counted; EV_CLOSING settles it (§3.4). Never free inline here. --- */
/* Per-request revocation options matching the construction-settled policy. */
if (rev != 0) {
if (!set_dword_opt(r->hreq, WINHTTP_OPTION_ENABLE_FEATURE,
WINHTTP_ENABLE_SSL_REVOCATION)) {
gle = GetLastError();
if (blob) xfree(blob);
WinHttpCloseHandle(r->hreq);
r->handles_closed = 1;
raise_code(class_for_code(gle),
"WinHttpSetOption(ENABLE_SSL_REVOCATION)", gle);
}
if (rev == 1) {
if (!set_dword_opt(r->hreq, WINHTTP_OPTION_IGNORE_CERT_REVOCATION_OFFLINE,
TRUE)) {
gle = GetLastError();
if (blob) xfree(blob);
WinHttpCloseHandle(r->hreq);
r->handles_closed = 1;
raise_code(class_for_code(gle),
"WinHttpSetOption(IGNORE_CERT_REVOCATION_OFFLINE)", gle);
}
}
}
if (blob) {
if (!WinHttpAddRequestHeaders(r->hreq, blob, (DWORD)-1,
WINHTTP_ADDREQ_FLAG_ADD)) {
gle = GetLastError();
xfree(blob);
WinHttpCloseHandle(r->hreq);
r->handles_closed = 1;
raise_code(class_for_code(gle), "WinHttpAddRequestHeaders", gle);
}
xfree(blob);
}
return ULL2NUM(id);
}
|
#_try_close_handle ⇒ Object
Close the session handle iff live == 0. Returns true when closed (or already gone / no live requests), false when deferred because requests are still tearing down.
541 542 543 544 545 546 547 |
# File 'ext/winhttp/winhttp.c', line 541
static VALUE ses_try_close_handle(VALUE self) {
whses *s = ses_ptr(self);
if (!s) return Qtrue;
if (s->live > 0) return Qfalse;
if (s->hsession) { WinHttpCloseHandle(s->hsession); s->hsession = NULL; }
return Qtrue;
}
|
#close ⇒ Object
Close the session: mark closed FIRST (new requests raise Closed), abort every in-flight request (those raise Canceled), wait — bounded, <= 5 s — for the OS to finish teardown, then close the session handle. Idempotent.
390 391 392 393 394 395 396 397 398 399 400 401 |
# File 'lib/winhttp.rb', line 390 def close @lock.synchronize do return nil if @closed_flag @closed_flag = true _mark_closed inflight = @inflight.values end abort_inflight bounded_close_handle nil end |
#closed? ⇒ Boolean
523 524 525 526 |
# File 'ext/winhttp/winhttp.c', line 523
static VALUE ses_closed_p(VALUE self) {
whses *s = ses_ptr(self);
return (!s || s->closed) ? Qtrue : Qfalse;
}
|
#delete(url, headers: nil, timeout: nil, &chunk) ⇒ Object
379 380 381 |
# File 'lib/winhttp.rb', line 379 def delete(url, headers: nil, timeout: nil, &chunk) perform("DELETE", url, nil, headers, timeout, &chunk) end |
#get(url, headers: nil, timeout: nil, &chunk) ⇒ Object
359 360 361 |
# File 'lib/winhttp.rb', line 359 def get(url, headers: nil, timeout: nil, &chunk) perform("GET", url, nil, headers, timeout, &chunk) end |
#head(url, headers: nil, timeout: nil) ⇒ Object
363 364 365 |
# File 'lib/winhttp.rb', line 363 def head(url, headers: nil, timeout: nil) perform("HEAD", url, nil, headers, timeout) end |
#patch(url, body:, headers: nil, timeout: nil, &chunk) ⇒ Object
375 376 377 |
# File 'lib/winhttp.rb', line 375 def patch(url, body:, headers: nil, timeout: nil, &chunk) perform("PATCH", url, body, headers, timeout, &chunk) end |
#post(url, body: "", headers: nil, timeout: nil, &chunk) ⇒ Object
367 368 369 |
# File 'lib/winhttp.rb', line 367 def post(url, body: "", headers: nil, timeout: nil, &chunk) perform("POST", url, body, headers, timeout, &chunk) end |
#put(url, body:, headers: nil, timeout: nil, &chunk) ⇒ Object
371 372 373 |
# File 'lib/winhttp.rb', line 371 def put(url, body:, headers: nil, timeout: nil, &chunk) perform("PUT", url, body, headers, timeout, &chunk) end |
#request(method, url, body: nil, headers: nil, timeout: nil, &chunk) ⇒ Object
383 384 385 |
# File 'lib/winhttp.rb', line 383 def request(method, url, body: nil, headers: nil, timeout: nil, &chunk) perform(Winhttp.send(:normalize_method, method), url, body, headers, timeout, &chunk) end |