@ng-native/desktop 0.26.1 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -3
- package/bin/app-config.mjs +1 -0
- package/bin/archive.mjs +166 -0
- package/bin/autolink.mjs +61 -30
- package/bin/cli.mjs +127 -27
- package/bin/host.mjs +255 -58
- package/bin/package-linux.mjs +1394 -0
- package/bin/package.mjs +171 -35
- package/bin/plist.mjs +6 -2
- package/bin/png-icon.mjs +315 -0
- package/bin/prebuilt.mjs +147 -26
- package/bin/toolchain.mjs +258 -19
- package/native/CMakeLists.txt +64 -6
- package/native/appkit/CMakeLists.txt +2 -1
- package/native/appkit/appkit-backend.h +1 -0
- package/native/appkit/appkit-backend.mm +13 -0
- package/native/appkit/header-toolbar.mm +28 -25
- package/native/appkit/host-view.h +10 -0
- package/native/appkit/host-view.mm +146 -40
- package/native/appkit/input-replay.h +6 -0
- package/native/appkit/input-replay.mm +21 -12
- package/native/appkit/main.mm +11 -7
- package/native/appkit/native-controls.mm +13 -1
- package/native/appkit/split-view.mm +7 -13
- package/native/appkit/text-input-field.h +4 -0
- package/native/appkit/text-input-field.mm +20 -1
- package/native/cmake/curl.cmake +79 -0
- package/native/cmake/libraries/react-native-reanimated.cmake +5 -0
- package/native/cmake/libraries/react-native-worklets.cmake +5 -0
- package/native/cmake/linked-modules.cmake +20 -4
- package/native/cmake/react-native.cmake +18 -1
- package/native/core/include/ngn/accent-colors.h +38 -0
- package/native/core/include/ngn/accessibility-relations.h +65 -0
- package/native/core/include/ngn/accessibility.h +26 -0
- package/native/core/include/ngn/animated-frame-loop.h +56 -0
- package/native/core/include/ngn/app-info.h +24 -8
- package/native/core/include/ngn/app-menus.h +14 -1
- package/native/core/include/ngn/app-windows.h +15 -2
- package/native/core/include/ngn/aria-role.h +96 -0
- package/native/core/include/ngn/audio.h +2 -0
- package/native/core/include/ngn/camera.h +9 -0
- package/native/core/include/ngn/control-sizes.h +7 -2
- package/native/core/include/ngn/crash-report.h +31 -0
- package/native/core/include/ngn/curl-network.h +93 -0
- package/native/core/include/ngn/dbus-menu.h +39 -0
- package/native/core/include/ngn/default-menu.h +36 -0
- package/native/core/include/ngn/desktop-expo.h +7 -1
- package/native/core/include/ngn/desktop-modules.h +22 -0
- package/native/core/include/ngn/desktop-props.h +21 -1
- package/native/core/include/ngn/desktop-view-props.h +6 -0
- package/native/core/include/ngn/focus-order.h +10 -0
- package/native/core/include/ngn/header-bar.h +22 -0
- package/native/core/include/ngn/host-os.h +6 -0
- package/native/core/include/ngn/host-reload.h +21 -0
- package/native/core/include/ngn/host-state.h +23 -0
- package/native/core/include/ngn/image-source.h +26 -1
- package/native/core/include/ngn/input-script.h +3 -3
- package/native/core/include/ngn/input.h +4 -1
- package/native/core/include/ngn/launch-frame.h +21 -0
- package/native/core/include/ngn/launch-settings.h +23 -5
- package/native/core/include/ngn/mounting-backend.h +5 -0
- package/native/core/include/ngn/mounting-manager.h +1 -0
- package/native/core/include/ngn/native-controls.h +26 -5
- package/native/core/include/ngn/notification-schedule.h +74 -0
- package/native/core/include/ngn/notifications.h +2 -1
- package/native/core/include/ngn/openssl-update-crypto.h +15 -0
- package/native/core/include/ngn/photo-library.h +60 -20
- package/native/core/include/ngn/posix-locale.h +43 -0
- package/native/core/include/ngn/runtime.h +5 -0
- package/native/core/include/ngn/safe-areas.h +14 -2
- package/native/core/include/ngn/split-view.h +78 -0
- package/native/core/include/ngn/surface-metrics.h +7 -0
- package/native/core/include/ngn/system.h +14 -0
- package/native/core/include/ngn/text-input.h +13 -0
- package/native/core/include/ngn/text-units.h +38 -0
- package/native/core/include/ngn/updates.h +14 -2
- package/native/core/include/ngn/view-box.h +40 -0
- package/native/core/include/ngn/view-transform.h +15 -0
- package/native/core/include/ngn/web-browser.h +46 -0
- package/native/core/src/accent-colors.cpp +88 -0
- package/native/core/src/accessibility-relations.cpp +138 -0
- package/native/core/src/accessibility.cpp +50 -0
- package/native/core/src/animated-frame-loop.cpp +166 -0
- package/native/core/src/app-menus.cpp +26 -9
- package/native/core/src/app-windows.cpp +27 -6
- package/native/core/src/aria-role.cpp +127 -0
- package/native/core/src/control-sizes.cpp +9 -5
- package/native/core/src/crash-report.cpp +196 -0
- package/native/core/src/curl-network.cpp +1562 -0
- package/native/core/src/dbus-menu.cpp +71 -0
- package/native/core/src/default-menu.cpp +134 -0
- package/native/core/src/desktop-view-props.cpp +14 -0
- package/native/core/src/focus-order.cpp +19 -0
- package/native/core/src/header-bar.cpp +20 -0
- package/native/core/src/host-os.cpp +19 -0
- package/native/core/src/host-reload.cpp +45 -0
- package/native/core/src/host-state.cpp +8 -0
- package/native/core/src/image-source.cpp +90 -0
- package/native/core/src/input-dispatcher.cpp +27 -5
- package/native/core/src/input-script.cpp +3 -2
- package/native/core/src/launch-settings.cpp +76 -0
- package/native/core/src/libraries/react-native-reanimated.cpp +6 -1
- package/native/core/src/modules/app-info.cpp +55 -6
- package/native/core/src/modules/app-modules.cpp +1 -1
- package/native/core/src/modules/audio.cpp +4 -2
- package/native/core/src/modules/camera.cpp +8 -11
- package/native/core/src/modules/desktop-expo.cpp +10 -5
- package/native/core/src/modules/desktop-modules.cpp +106 -41
- package/native/core/src/modules/file-photo-picker.cpp +408 -0
- package/native/core/src/modules/notifications.cpp +13 -17
- package/native/core/src/modules/photo-library.cpp +42 -13
- package/native/core/src/modules/web-browser.cpp +89 -0
- package/native/core/src/mounting-manager.cpp +12 -0
- package/native/core/src/native-controls.cpp +42 -1
- package/native/core/src/notification-schedule.cpp +429 -0
- package/native/core/src/openssl-update-crypto.cpp +83 -0
- package/native/core/src/posix-locale.cpp +192 -0
- package/native/core/src/runtime.cpp +30 -1
- package/native/core/src/safe-areas.cpp +19 -4
- package/native/core/src/spawn-rules.cpp +4 -1
- package/native/core/src/split-view.cpp +93 -0
- package/native/core/src/system.cpp +19 -0
- package/native/core/src/text-input.cpp +18 -1
- package/native/core/src/text-units.cpp +99 -0
- package/native/core/src/updates.cpp +76 -17
- package/native/core/src/view-box.cpp +75 -40
- package/native/core/src/view-transform.cpp +28 -0
- package/native/docker/Dockerfile +38 -0
- package/native/docker/Dockerfile.fedora +36 -0
- package/native/docker/glibc-floor.sh +49 -0
- package/native/gtk/CMakeLists.txt +137 -0
- package/native/gtk/accent-colour.cpp +57 -0
- package/native/gtk/accent-colour.h +41 -0
- package/native/gtk/accessibility-settings.cpp +159 -0
- package/native/gtk/accessibility-settings.h +62 -0
- package/native/gtk/accessible-text.cpp +151 -0
- package/native/gtk/accessible-text.h +49 -0
- package/native/gtk/accessible.cpp +306 -0
- package/native/gtk/accessible.h +75 -0
- package/native/gtk/alerts.cpp +267 -0
- package/native/gtk/alerts.h +30 -0
- package/native/gtk/animation-frames.cpp +159 -0
- package/native/gtk/animation-frames.h +20 -0
- package/native/gtk/app-info.cpp +91 -0
- package/native/gtk/app-info.h +25 -0
- package/native/gtk/app-windows.cpp +439 -0
- package/native/gtk/app-windows.h +150 -0
- package/native/gtk/audio.cpp +370 -0
- package/native/gtk/audio.h +54 -0
- package/native/gtk/auth-session.cpp +73 -0
- package/native/gtk/auth-session.h +16 -0
- package/native/gtk/battery.cpp +110 -0
- package/native/gtk/battery.h +19 -0
- package/native/gtk/box-paint.cpp +262 -0
- package/native/gtk/box-paint.h +32 -0
- package/native/gtk/cairo-canvas.cpp +755 -0
- package/native/gtk/cairo-canvas.h +49 -0
- package/native/gtk/camera.cpp +909 -0
- package/native/gtk/camera.h +69 -0
- package/native/gtk/capture.cpp +46 -0
- package/native/gtk/capture.h +19 -0
- package/native/gtk/clock-format.cpp +151 -0
- package/native/gtk/clock-format.h +36 -0
- package/native/gtk/crypto.cpp +75 -0
- package/native/gtk/crypto.h +14 -0
- package/native/gtk/dbus-properties.cpp +131 -0
- package/native/gtk/dbus-properties.h +61 -0
- package/native/gtk/drag-and-drop.cpp +339 -0
- package/native/gtk/drag-and-drop.h +30 -0
- package/native/gtk/file-dialogs.cpp +239 -0
- package/native/gtk/file-dialogs.h +21 -0
- package/native/gtk/file-system.cpp +212 -0
- package/native/gtk/file-system.h +25 -0
- package/native/gtk/focus.cpp +282 -0
- package/native/gtk/focus.h +37 -0
- package/native/gtk/fonts.cpp +89 -0
- package/native/gtk/fonts.h +22 -0
- package/native/gtk/gst-frames.cpp +150 -0
- package/native/gtk/gst-frames.h +47 -0
- package/native/gtk/gst-playback.cpp +496 -0
- package/native/gtk/gst-playback.h +81 -0
- package/native/gtk/gtk-backend.cpp +690 -0
- package/native/gtk/gtk-backend.h +134 -0
- package/native/gtk/host-sources.cpp +354 -0
- package/native/gtk/host-sources.h +46 -0
- package/native/gtk/image-manipulator.cpp +254 -0
- package/native/gtk/image-manipulator.h +30 -0
- package/native/gtk/image-view.cpp +256 -0
- package/native/gtk/image-view.h +54 -0
- package/native/gtk/input-replay.cpp +299 -0
- package/native/gtk/input-replay.h +36 -0
- package/native/gtk/launcher-badge.cpp +29 -0
- package/native/gtk/launcher-badge.h +21 -0
- package/native/gtk/locales.cpp +131 -0
- package/native/gtk/locales.h +23 -0
- package/native/gtk/location.cpp +274 -0
- package/native/gtk/location.h +19 -0
- package/native/gtk/main.cpp +1092 -0
- package/native/gtk/menus.cpp +447 -0
- package/native/gtk/menus.h +100 -0
- package/native/gtk/native-controls.cpp +831 -0
- package/native/gtk/native-controls.h +58 -0
- package/native/gtk/network-state.cpp +72 -0
- package/native/gtk/network-state.h +24 -0
- package/native/gtk/notifications.cpp +235 -0
- package/native/gtk/notifications.h +30 -0
- package/native/gtk/pango-text.cpp +274 -0
- package/native/gtk/pango-text.h +73 -0
- package/native/gtk/portal.cpp +451 -0
- package/native/gtk/portal.h +71 -0
- package/native/gtk/printing.cpp +338 -0
- package/native/gtk/printing.h +34 -0
- package/native/gtk/proxy-resolver.cpp +74 -0
- package/native/gtk/proxy-resolver.h +20 -0
- package/native/gtk/screens.cpp +1461 -0
- package/native/gtk/screens.h +274 -0
- package/native/gtk/scroll-view.cpp +414 -0
- package/native/gtk/scroll-view.h +82 -0
- package/native/gtk/secret-store.cpp +120 -0
- package/native/gtk/secret-store.h +27 -0
- package/native/gtk/settings-portal.cpp +129 -0
- package/native/gtk/settings-portal.h +47 -0
- package/native/gtk/split-view.cpp +1105 -0
- package/native/gtk/split-view.h +195 -0
- package/native/gtk/status-notifier.cpp +487 -0
- package/native/gtk/status-notifier.h +43 -0
- package/native/gtk/surface-input.cpp +251 -0
- package/native/gtk/surface-input.h +57 -0
- package/native/gtk/system-access.cpp +295 -0
- package/native/gtk/system-access.h +37 -0
- package/native/gtk/text-field.cpp +827 -0
- package/native/gtk/text-field.h +78 -0
- package/native/gtk/video.cpp +527 -0
- package/native/gtk/video.h +47 -0
- package/native/gtk/view-widget.cpp +431 -0
- package/native/gtk/view-widget.h +105 -0
- package/native/gtk/window-scale.cpp +95 -0
- package/native/gtk/window-scale.h +35 -0
- package/native/scripts/atspi-check.py +310 -0
- package/native/scripts/atspi-check.test.py +48 -0
- package/native/scripts/build.sh +20 -3
- package/native/scripts/compilers.sh +17 -0
- package/native/scripts/deb-depends-check.sh +22 -0
- package/native/scripts/fetch.sh +23 -2
- package/native/scripts/launch-cell.sh +157 -0
- package/native/scripts/launch-probe.sh +14 -3
- package/native/scripts/make-prebuilt.mjs +133 -44
- package/native/scripts/prebuilt-host-cache.mjs +71 -40
- package/native/scripts/reset-for-compilers.sh +44 -0
- package/native/scripts/start-xvfb.sh +35 -0
- package/native/shim/paragraph-platform/react/renderer/components/text/HostPlatformParagraphProps.h +35 -0
- package/native/shim/view-platform/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +5 -2
- package/native/shim/worklets/linux-reanimated-props.h +14 -0
- package/native/shim/worklets/linux-worklets.h +23 -0
- package/package.json +6 -3
- package/prebuilt.json +70 -6
|
@@ -0,0 +1,1562 @@
|
|
|
1
|
+
#include "ngn/curl-network.h"
|
|
2
|
+
|
|
3
|
+
#include "ngn/bytes.h"
|
|
4
|
+
|
|
5
|
+
#include <curl/curl.h>
|
|
6
|
+
|
|
7
|
+
#include <fcntl.h>
|
|
8
|
+
#include <sys/stat.h>
|
|
9
|
+
#include <unistd.h>
|
|
10
|
+
|
|
11
|
+
#include <algorithm>
|
|
12
|
+
#include <cctype>
|
|
13
|
+
#include <atomic>
|
|
14
|
+
#include <chrono>
|
|
15
|
+
#include <cstdlib>
|
|
16
|
+
#include <cstring>
|
|
17
|
+
#include <ctime>
|
|
18
|
+
#include <deque>
|
|
19
|
+
#include <filesystem>
|
|
20
|
+
#include <fstream>
|
|
21
|
+
#include <map>
|
|
22
|
+
#include <mutex>
|
|
23
|
+
#include <string_view>
|
|
24
|
+
#include <thread>
|
|
25
|
+
#include <vector>
|
|
26
|
+
|
|
27
|
+
namespace ngn {
|
|
28
|
+
|
|
29
|
+
namespace {
|
|
30
|
+
|
|
31
|
+
using Clock = std::chrono::steady_clock;
|
|
32
|
+
using std::chrono::milliseconds;
|
|
33
|
+
|
|
34
|
+
// How long the desktop's proxy answer for an origin is used before it is asked again.
|
|
35
|
+
constexpr auto kProxyKept = std::chrono::seconds(30);
|
|
36
|
+
|
|
37
|
+
// NSURLSession's request timeout on macOS (network.mm): a dev server's first bundle can take
|
|
38
|
+
// minutes before its first byte.
|
|
39
|
+
constexpr milliseconds kDefaultIdle = std::chrono::seconds(300);
|
|
40
|
+
// How long a WebSocket's opening handshake may take.
|
|
41
|
+
constexpr milliseconds kHandshakeTimeout = std::chrono::seconds(60);
|
|
42
|
+
// How long a close this side started waits for the server's close frame.
|
|
43
|
+
constexpr milliseconds kCloseWait = std::chrono::seconds(5);
|
|
44
|
+
// The longest WebSocket message taken, as macOS's maximumMessageSize.
|
|
45
|
+
constexpr size_t kMaxMessage = 64 * 1024 * 1024;
|
|
46
|
+
// The redirects followed before giving up, as browsers count them.
|
|
47
|
+
constexpr long kMaxRedirects = 20;
|
|
48
|
+
// The reads one WebSocket gets in one pass of the thread (up to 4 MB), so a server that keeps
|
|
49
|
+
// sending cannot hold up every other request and connection.
|
|
50
|
+
constexpr int kReceiveBudget = 64;
|
|
51
|
+
|
|
52
|
+
void initCurl() {
|
|
53
|
+
static std::once_flag once;
|
|
54
|
+
std::call_once(once, [] { curl_global_init(CURL_GLOBAL_DEFAULT); });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// NSURLSession's English descriptions of the matching NSURLError, which is what JavaScript gets on
|
|
58
|
+
// macOS. libcurl is built without its own messages (cmake/curl.cmake).
|
|
59
|
+
std::string errorText(CURLcode code) {
|
|
60
|
+
switch (code) {
|
|
61
|
+
case CURLE_OPERATION_TIMEDOUT:
|
|
62
|
+
return "The request timed out.";
|
|
63
|
+
case CURLE_COULDNT_RESOLVE_HOST:
|
|
64
|
+
case CURLE_COULDNT_RESOLVE_PROXY:
|
|
65
|
+
return "A server with the specified hostname could not be found.";
|
|
66
|
+
case CURLE_COULDNT_CONNECT:
|
|
67
|
+
return "Could not connect to the server.";
|
|
68
|
+
case CURLE_SSL_CONNECT_ERROR:
|
|
69
|
+
case CURLE_PEER_FAILED_VERIFICATION:
|
|
70
|
+
case CURLE_SSL_CERTPROBLEM:
|
|
71
|
+
case CURLE_SSL_CIPHER:
|
|
72
|
+
case CURLE_SSL_CACERT_BADFILE:
|
|
73
|
+
case CURLE_SSL_PINNEDPUBKEYNOTMATCH:
|
|
74
|
+
case CURLE_SSL_INVALIDCERTSTATUS:
|
|
75
|
+
return "An SSL error has occurred and a secure connection to the server cannot be made.";
|
|
76
|
+
case CURLE_TOO_MANY_REDIRECTS:
|
|
77
|
+
return "too many HTTP redirects";
|
|
78
|
+
case CURLE_UNSUPPORTED_PROTOCOL:
|
|
79
|
+
case CURLE_URL_MALFORMAT:
|
|
80
|
+
return "unsupported URL";
|
|
81
|
+
case CURLE_GOT_NOTHING:
|
|
82
|
+
case CURLE_RECV_ERROR:
|
|
83
|
+
case CURLE_SEND_ERROR:
|
|
84
|
+
case CURLE_PARTIAL_FILE:
|
|
85
|
+
case CURLE_HTTP2:
|
|
86
|
+
case CURLE_HTTP2_STREAM:
|
|
87
|
+
return "The network connection was lost.";
|
|
88
|
+
case CURLE_BAD_CONTENT_ENCODING:
|
|
89
|
+
return "cannot decode raw data";
|
|
90
|
+
case CURLE_FILE_COULDNT_READ_FILE:
|
|
91
|
+
return "The requested URL was not found on this server.";
|
|
92
|
+
case CURLE_HTTP_RETURNED_ERROR:
|
|
93
|
+
case CURLE_WEIRD_SERVER_REPLY:
|
|
94
|
+
return "There was a bad response from the server.";
|
|
95
|
+
default:
|
|
96
|
+
return "A network error occurred (libcurl error " + std::to_string(static_cast<int>(code)) + ").";
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Whether a cookie line in libcurl's (Netscape's) format is one to keep past this launch: one with
|
|
101
|
+
// an expiry still to come. A session cookie's expiry is 0. `#HttpOnly_` lines are cookies; other `#`
|
|
102
|
+
// lines and blank ones are not.
|
|
103
|
+
bool lastingCookie(std::string_view line, time_t now) {
|
|
104
|
+
if (line.empty() || (line[0] == '#' && line.rfind("#HttpOnly_", 0) != 0)) {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
size_t at = 0;
|
|
108
|
+
for (int field = 0; field < 4; ++field) {
|
|
109
|
+
at = line.find('\t', at);
|
|
110
|
+
if (at == std::string_view::npos) {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
++at;
|
|
114
|
+
}
|
|
115
|
+
auto end = line.find('\t', at);
|
|
116
|
+
if (end == std::string_view::npos) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
long long expires = 0;
|
|
120
|
+
for (char c : line.substr(at, end - at)) {
|
|
121
|
+
if (c < '0' || c > '9') {
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
expires = expires * 10 + (c - '0');
|
|
125
|
+
}
|
|
126
|
+
return expires > now;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
bool startsWithNoCase(std::string_view text, std::string_view prefix) {
|
|
130
|
+
return text.size() >= prefix.size() &&
|
|
131
|
+
std::equal(prefix.begin(), prefix.end(), text.begin(), [](char a, char b) { return std::tolower(a) == std::tolower(b); });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
bool sameName(std::string_view a, std::string_view b) {
|
|
135
|
+
return a.size() == b.size() && startsWithNoCase(a, b);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
std::string_view trimmed(std::string_view s) {
|
|
139
|
+
while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) {
|
|
140
|
+
s.remove_prefix(1);
|
|
141
|
+
}
|
|
142
|
+
while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\r' || s.back() == '\n')) {
|
|
143
|
+
s.remove_suffix(1);
|
|
144
|
+
}
|
|
145
|
+
return s;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
std::string upper(std::string s) {
|
|
149
|
+
for (auto &c : s) {
|
|
150
|
+
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
|
|
151
|
+
}
|
|
152
|
+
return s;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// A url curl can parse, whatever its scheme: macOS's NSURL refuses only what is not a url.
|
|
156
|
+
bool parses(const std::string &url) {
|
|
157
|
+
CURLU *u = curl_url();
|
|
158
|
+
bool ok = curl_url_set(u, CURLUPART_URL, url.c_str(), CURLU_NON_SUPPORT_SCHEME) == CURLUE_OK;
|
|
159
|
+
curl_url_cleanup(u);
|
|
160
|
+
return ok;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// A WebSocket url with an http or https scheme as ws or wss, which NSURLSession's WebSocket task
|
|
164
|
+
// takes and curl's does not. React Native's HMR client opens Metro's /hot by the bundle's http url.
|
|
165
|
+
std::string webSocketUrl(const std::string &url) {
|
|
166
|
+
if (startsWithNoCase(url, "http://")) {
|
|
167
|
+
return "ws://" + url.substr(7);
|
|
168
|
+
}
|
|
169
|
+
if (startsWithNoCase(url, "https://")) {
|
|
170
|
+
return "wss://" + url.substr(8);
|
|
171
|
+
}
|
|
172
|
+
return url;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Whether a `file:` url names a regular file. Anything else (a FIFO with no writer, a device)
|
|
176
|
+
// can block the open that curl makes on the thread every request shares, so it is refused first.
|
|
177
|
+
bool regularFile(const std::string &url) {
|
|
178
|
+
CURLU *u = curl_url();
|
|
179
|
+
char *path = nullptr;
|
|
180
|
+
bool ok = curl_url_set(u, CURLUPART_URL, url.c_str(), 0) == CURLUE_OK &&
|
|
181
|
+
curl_url_get(u, CURLUPART_PATH, &path, CURLU_URLDECODE) == CURLUE_OK;
|
|
182
|
+
struct stat st {};
|
|
183
|
+
ok = ok && stat(path, &st) == 0 && S_ISREG(st.st_mode);
|
|
184
|
+
curl_free(path);
|
|
185
|
+
curl_url_cleanup(u);
|
|
186
|
+
return ok;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// At most `limit` bytes of UTF-8 `text`, cut before a character rather than inside one.
|
|
190
|
+
std::string utf8Prefix(const std::string &text, size_t limit) {
|
|
191
|
+
if (text.size() <= limit) {
|
|
192
|
+
return text;
|
|
193
|
+
}
|
|
194
|
+
size_t n = limit;
|
|
195
|
+
while (n > 0 && (static_cast<unsigned char>(text[n]) & 0xC0) == 0x80) {
|
|
196
|
+
--n;
|
|
197
|
+
}
|
|
198
|
+
return text.substr(0, n);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Whether `text` is well-formed UTF-8: no overlong forms, surrogates or code points past U+10FFFF.
|
|
202
|
+
bool validUtf8(std::string_view text) {
|
|
203
|
+
size_t i = 0;
|
|
204
|
+
while (i < text.size()) {
|
|
205
|
+
auto c = static_cast<unsigned char>(text[i]);
|
|
206
|
+
size_t extra;
|
|
207
|
+
unsigned char low = 0x80, high = 0xBF;
|
|
208
|
+
if (c < 0x80) {
|
|
209
|
+
++i;
|
|
210
|
+
continue;
|
|
211
|
+
} else if (c >= 0xC2 && c <= 0xDF) {
|
|
212
|
+
extra = 1;
|
|
213
|
+
} else if (c >= 0xE0 && c <= 0xEF) {
|
|
214
|
+
extra = 2;
|
|
215
|
+
low = c == 0xE0 ? 0xA0 : 0x80;
|
|
216
|
+
high = c == 0xED ? 0x9F : 0xBF;
|
|
217
|
+
} else if (c >= 0xF0 && c <= 0xF4) {
|
|
218
|
+
extra = 3;
|
|
219
|
+
low = c == 0xF0 ? 0x90 : 0x80;
|
|
220
|
+
high = c == 0xF4 ? 0x8F : 0xBF;
|
|
221
|
+
} else {
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
if (text.size() - i <= extra) {
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
for (size_t k = 1; k <= extra; ++k) {
|
|
228
|
+
auto b = static_cast<unsigned char>(text[i + k]);
|
|
229
|
+
unsigned char lo = k == 1 ? low : 0x80, hi = k == 1 ? high : 0xBF;
|
|
230
|
+
if (b < lo || b > hi) {
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
i += extra + 1;
|
|
235
|
+
}
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// A `data:` url's bytes: `data:[<type>][;base64],<data>`, its data percent-decoded. A fragment
|
|
240
|
+
// (from the first `#`) is not part of it; `%23` is a `#` in the data.
|
|
241
|
+
std::optional<std::string> dataUriBytes(const std::string &url) {
|
|
242
|
+
const std::string uri = url.substr(0, url.find('#'));
|
|
243
|
+
auto comma = uri.find(',');
|
|
244
|
+
if (comma == std::string::npos) {
|
|
245
|
+
return std::nullopt;
|
|
246
|
+
}
|
|
247
|
+
std::string_view meta(uri.data() + 5, comma - 5);
|
|
248
|
+
bool base64 = meta.size() >= 7 && sameName(meta.substr(meta.size() - 7), ";base64");
|
|
249
|
+
std::string data;
|
|
250
|
+
for (size_t i = comma + 1; i < uri.size(); ++i) {
|
|
251
|
+
char c = uri[i];
|
|
252
|
+
if (c == '%' && i + 2 < uri.size() && std::isxdigit(static_cast<unsigned char>(uri[i + 1])) &&
|
|
253
|
+
std::isxdigit(static_cast<unsigned char>(uri[i + 2]))) {
|
|
254
|
+
data += static_cast<char>(std::stoi(uri.substr(i + 1, 2), nullptr, 16));
|
|
255
|
+
i += 2;
|
|
256
|
+
} else {
|
|
257
|
+
data += c;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (!base64) {
|
|
261
|
+
return data;
|
|
262
|
+
}
|
|
263
|
+
std::erase_if(data, [](char c) { return std::isspace(static_cast<unsigned char>(c)); });
|
|
264
|
+
return base64Decode(data);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
struct HttpState {
|
|
268
|
+
// Held while a callback runs and while cancel marks the request done, so none runs after cancel
|
|
269
|
+
// returns. Recursive, since a callback may cancel its own request.
|
|
270
|
+
std::recursive_mutex mutex;
|
|
271
|
+
HttpCallbacks callbacks;
|
|
272
|
+
bool done{false};
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
struct SocketState {
|
|
276
|
+
std::recursive_mutex mutex;
|
|
277
|
+
WebSocketCallbacks callbacks;
|
|
278
|
+
bool finished{false};
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
class Engine;
|
|
282
|
+
|
|
283
|
+
// One request on the thread.
|
|
284
|
+
struct Transfer {
|
|
285
|
+
~Transfer() {
|
|
286
|
+
curl_slist_free_all(headers);
|
|
287
|
+
curl_easy_cleanup(easy);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
void touch() {
|
|
291
|
+
lastActivity = Clock::now();
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// The response JavaScript sees: the last one, after any 1xx and followed redirects.
|
|
295
|
+
void respond(uint16_t status) {
|
|
296
|
+
responded = true;
|
|
297
|
+
if (!http) {
|
|
298
|
+
// A `file:` url answers with no headers, as a non-HTTP response does on macOS.
|
|
299
|
+
headerLines.clear();
|
|
300
|
+
}
|
|
301
|
+
HttpResponse response{.status = status, .headers = std::move(headerLines)};
|
|
302
|
+
char *url = nullptr;
|
|
303
|
+
curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &url);
|
|
304
|
+
response.url = url ? url : "";
|
|
305
|
+
std::lock_guard lock(state->mutex);
|
|
306
|
+
if (!state->done && state->callbacks.onResponse) {
|
|
307
|
+
state->callbacks.onResponse(response);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
CURL *easy{curl_easy_init()};
|
|
312
|
+
curl_slist *headers{nullptr};
|
|
313
|
+
std::shared_ptr<HttpState> state;
|
|
314
|
+
// The body, which curl reads in place.
|
|
315
|
+
std::string body;
|
|
316
|
+
bool http{true};
|
|
317
|
+
Headers headerLines;
|
|
318
|
+
bool responded{false};
|
|
319
|
+
curl_off_t sentReported{0};
|
|
320
|
+
milliseconds idle{kDefaultIdle};
|
|
321
|
+
Clock::time_point lastActivity{Clock::now()};
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
// One WebSocket on the thread.
|
|
325
|
+
struct Socket {
|
|
326
|
+
enum class Phase { Connecting, Open };
|
|
327
|
+
struct Frame {
|
|
328
|
+
unsigned flags;
|
|
329
|
+
std::string bytes;
|
|
330
|
+
size_t offset{0};
|
|
331
|
+
// Handed to curl at least once, after which curl takes nothing else until it is all sent.
|
|
332
|
+
bool started{false};
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
~Socket() {
|
|
336
|
+
curl_slist_free_all(headers);
|
|
337
|
+
curl_easy_cleanup(easy);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
CURL *easy{curl_easy_init()};
|
|
341
|
+
curl_slist *headers{nullptr};
|
|
342
|
+
std::shared_ptr<SocketState> state;
|
|
343
|
+
Phase phase{Phase::Connecting};
|
|
344
|
+
Clock::time_point started{Clock::now()};
|
|
345
|
+
// The subprotocols offered, and the one the server chose.
|
|
346
|
+
std::vector<std::string> offered;
|
|
347
|
+
std::string protocol;
|
|
348
|
+
curl_socket_t fd{CURL_SOCKET_BAD};
|
|
349
|
+
// What is still to send, oldest first; held until the socket opens.
|
|
350
|
+
std::deque<Frame> outgoing;
|
|
351
|
+
// A message whose fragments are still arriving, and a close frame's payload.
|
|
352
|
+
std::string message;
|
|
353
|
+
unsigned messageFlags{0};
|
|
354
|
+
std::string closePayload;
|
|
355
|
+
// A ping's payload while it arrives, which its pong echoes.
|
|
356
|
+
std::string pingPayload;
|
|
357
|
+
// This side's close frame, queued and then sent, and when to stop waiting for the closing
|
|
358
|
+
// handshake to finish.
|
|
359
|
+
bool closeQueued{false};
|
|
360
|
+
bool closeSent{false};
|
|
361
|
+
Clock::time_point closeDeadline;
|
|
362
|
+
// The server's close frame, once it has come.
|
|
363
|
+
bool peerClosed{false};
|
|
364
|
+
int peerCode{1005};
|
|
365
|
+
std::string peerReason;
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
class Engine : public std::enable_shared_from_this<Engine> {
|
|
369
|
+
public:
|
|
370
|
+
explicit Engine(CurlOptions options) : options_(std::move(options)) {
|
|
371
|
+
initCurl();
|
|
372
|
+
multi_ = curl_multi_init();
|
|
373
|
+
share_ = curl_share_init();
|
|
374
|
+
// Every handle lives on the thread, so the shared cookie store needs no lock.
|
|
375
|
+
curl_share_setopt(share_, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
|
|
376
|
+
ca_ = findCaCertificates();
|
|
377
|
+
useDesktopProxies_ = options_.desktopProxies && !proxyEnvironmentSet([](const char *name) -> std::optional<std::string> {
|
|
378
|
+
const char *value = getenv(name);
|
|
379
|
+
return value ? std::optional<std::string>(value) : std::nullopt;
|
|
380
|
+
});
|
|
381
|
+
if (!options_.cookieFile.empty()) {
|
|
382
|
+
// A handle of its own reads and fills the shared store.
|
|
383
|
+
cookies_ = curl_easy_init();
|
|
384
|
+
useCookies(cookies_);
|
|
385
|
+
loadCookies();
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
~Engine() {
|
|
390
|
+
for (auto &[_, t] : transfers_) {
|
|
391
|
+
curl_multi_remove_handle(multi_, t->easy);
|
|
392
|
+
}
|
|
393
|
+
for (auto &[_, s] : sockets_) {
|
|
394
|
+
curl_multi_remove_handle(multi_, s->easy);
|
|
395
|
+
}
|
|
396
|
+
transfers_.clear();
|
|
397
|
+
sockets_.clear();
|
|
398
|
+
if (cookies_ != nullptr) {
|
|
399
|
+
saveCookies();
|
|
400
|
+
curl_easy_cleanup(cookies_);
|
|
401
|
+
}
|
|
402
|
+
curl_multi_cleanup(multi_);
|
|
403
|
+
curl_share_cleanup(share_);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// Runs `command` on the thread. Any thread; dropped once the engine stops.
|
|
407
|
+
void post(std::function<void()> command) {
|
|
408
|
+
std::lock_guard lock(mutex_);
|
|
409
|
+
if (stopping_) {
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
queue_.push_back(std::move(command));
|
|
413
|
+
curl_multi_wakeup(multi_);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
void stop() {
|
|
417
|
+
std::lock_guard lock(mutex_);
|
|
418
|
+
stopping_ = true;
|
|
419
|
+
queue_.clear();
|
|
420
|
+
curl_multi_wakeup(multi_);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
uint64_t nextId() {
|
|
424
|
+
return ++ids_;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
void run() {
|
|
428
|
+
for (;;) {
|
|
429
|
+
std::vector<std::function<void()>> commands;
|
|
430
|
+
{
|
|
431
|
+
std::lock_guard lock(mutex_);
|
|
432
|
+
if (stopping_) {
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
commands.swap(queue_);
|
|
436
|
+
}
|
|
437
|
+
for (auto &command : commands) {
|
|
438
|
+
command();
|
|
439
|
+
}
|
|
440
|
+
int running = 0;
|
|
441
|
+
curl_multi_perform(multi_, &running);
|
|
442
|
+
finished();
|
|
443
|
+
serviceSockets();
|
|
444
|
+
expire();
|
|
445
|
+
std::vector<curl_waitfd> fds;
|
|
446
|
+
for (auto &[_, s] : sockets_) {
|
|
447
|
+
if (s->phase == Socket::Phase::Open && s->fd != CURL_SOCKET_BAD) {
|
|
448
|
+
// Nothing is read past the server's close frame, so its socket is not waited on to read.
|
|
449
|
+
short events = s->peerClosed ? 0 : CURL_WAIT_POLLIN;
|
|
450
|
+
if (!s->outgoing.empty()) {
|
|
451
|
+
events |= CURL_WAIT_POLLOUT;
|
|
452
|
+
}
|
|
453
|
+
if (events != 0) {
|
|
454
|
+
fds.push_back({.fd = s->fd, .events = events, .revents = 0});
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
curl_multi_poll(multi_, fds.data(), static_cast<unsigned>(fds.size()), nextWaitMs(), nullptr);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// --- HTTP ---------------------------------------------------------------------------------
|
|
463
|
+
|
|
464
|
+
void start(uint64_t id, HttpRequest request, std::shared_ptr<HttpState> state, bool proxyKnown = false) {
|
|
465
|
+
{
|
|
466
|
+
std::lock_guard lock(state->mutex);
|
|
467
|
+
if (state->done) {
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
if (startsWithNoCase(request.url, "data:")) {
|
|
472
|
+
answerDataUri(request.url, *state);
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
if (startsWithNoCase(request.url, "file:") && !regularFile(request.url)) {
|
|
476
|
+
std::lock_guard lock(state->mutex);
|
|
477
|
+
if (!state->done) {
|
|
478
|
+
state->done = true;
|
|
479
|
+
if (state->callbacks.onComplete) {
|
|
480
|
+
state->callbacks.onComplete(errorText(CURLE_FILE_COULDNT_READ_FILE), false);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
bool http = startsWithNoCase(request.url, "http:") || startsWithNoCase(request.url, "https:");
|
|
486
|
+
if (http && !proxyKnown) {
|
|
487
|
+
// The desktop's answer may take seconds: the request starts when it is in, and a cancel meanwhile
|
|
488
|
+
// is seen by the check above.
|
|
489
|
+
auto url = request.url;
|
|
490
|
+
withProxy(url, [this, id, request = std::move(request), state = std::move(state)]() mutable {
|
|
491
|
+
start(id, std::move(request), std::move(state), true);
|
|
492
|
+
});
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
auto t = std::make_unique<Transfer>();
|
|
496
|
+
t->state = std::move(state);
|
|
497
|
+
t->http = http;
|
|
498
|
+
if (request.timeoutMs > 0) {
|
|
499
|
+
t->idle = milliseconds(request.timeoutMs);
|
|
500
|
+
}
|
|
501
|
+
CURL *e = t->easy;
|
|
502
|
+
common(e);
|
|
503
|
+
if (t->http) {
|
|
504
|
+
useProxy(e, request.url);
|
|
505
|
+
}
|
|
506
|
+
curl_easy_setopt(e, CURLOPT_URL, request.url.c_str());
|
|
507
|
+
curl_easy_setopt(e, CURLOPT_PRIVATE, t.get());
|
|
508
|
+
curl_easy_setopt(e, CURLOPT_PROTOCOLS_STR, "http,https,file");
|
|
509
|
+
curl_easy_setopt(e, CURLOPT_REDIR_PROTOCOLS_STR, "http,https");
|
|
510
|
+
curl_easy_setopt(e, CURLOPT_FOLLOWLOCATION, CURLFOLLOW_OBEYCODE);
|
|
511
|
+
curl_easy_setopt(e, CURLOPT_MAXREDIRS, kMaxRedirects);
|
|
512
|
+
// Every encoding curl can decode, decoded, as NSURLSession does.
|
|
513
|
+
curl_easy_setopt(e, CURLOPT_ACCEPT_ENCODING, "");
|
|
514
|
+
curl_easy_setopt(e, CURLOPT_HEADERFUNCTION, &Engine::onHeader);
|
|
515
|
+
curl_easy_setopt(e, CURLOPT_HEADERDATA, t.get());
|
|
516
|
+
curl_easy_setopt(e, CURLOPT_WRITEFUNCTION, &Engine::onWrite);
|
|
517
|
+
curl_easy_setopt(e, CURLOPT_WRITEDATA, t.get());
|
|
518
|
+
curl_easy_setopt(e, CURLOPT_NOPROGRESS, 0L);
|
|
519
|
+
curl_easy_setopt(e, CURLOPT_XFERINFOFUNCTION, &Engine::onProgress);
|
|
520
|
+
curl_easy_setopt(e, CURLOPT_XFERINFODATA, t.get());
|
|
521
|
+
|
|
522
|
+
std::string method = upper(request.method.empty() ? "GET" : request.method);
|
|
523
|
+
bool hasBody = false;
|
|
524
|
+
if (method == "GET") {
|
|
525
|
+
curl_easy_setopt(e, CURLOPT_HTTPGET, 1L);
|
|
526
|
+
} else if (method == "HEAD") {
|
|
527
|
+
curl_easy_setopt(e, CURLOPT_NOBODY, 1L);
|
|
528
|
+
} else {
|
|
529
|
+
if (method != "POST") {
|
|
530
|
+
curl_easy_setopt(e, CURLOPT_CUSTOMREQUEST, request.method.c_str());
|
|
531
|
+
// curl treats this method's body as a POST's, and would make it a GET on a 301 or 302 too.
|
|
532
|
+
// Only POST changes there, as in browsers.
|
|
533
|
+
curl_easy_setopt(e, CURLOPT_POSTREDIR, static_cast<long>(CURL_REDIR_POST_301 | CURL_REDIR_POST_302));
|
|
534
|
+
}
|
|
535
|
+
// A body goes as curl's POST does, under the method named, and POST, PUT and PATCH send an
|
|
536
|
+
// empty one with its length. OBEYCODE above turns a POST into a GET on a 301, 302 or 303,
|
|
537
|
+
// and any method into a GET on a 303, as NSURLSession does.
|
|
538
|
+
if (!request.body.empty() || method == "POST" || method == "PUT" || method == "PATCH") {
|
|
539
|
+
t->body = std::move(request.body);
|
|
540
|
+
curl_easy_setopt(e, CURLOPT_POST, 1L);
|
|
541
|
+
curl_easy_setopt(e, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(t->body.size()));
|
|
542
|
+
curl_easy_setopt(e, CURLOPT_POSTFIELDS, t->body.data());
|
|
543
|
+
hasBody = true;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
bool contentType = false;
|
|
547
|
+
bool expect = false;
|
|
548
|
+
for (const auto &[name, value] : request.headers) {
|
|
549
|
+
contentType = contentType || sameName(name, "content-type");
|
|
550
|
+
expect = expect || sameName(name, "expect");
|
|
551
|
+
// "Name;" is curl's spelling of a header with an empty value; "Name:" would remove it.
|
|
552
|
+
t->headers = curl_slist_append(t->headers, (value.empty() ? name + ";" : name + ": " + value).c_str());
|
|
553
|
+
}
|
|
554
|
+
// curl's own Content-Type for a body (a url-encoded form) and its 100-continue wait for a
|
|
555
|
+
// large one, which NSURLSession sends neither of.
|
|
556
|
+
if (hasBody && !contentType) {
|
|
557
|
+
t->headers = curl_slist_append(t->headers, "Content-Type:");
|
|
558
|
+
}
|
|
559
|
+
if (!expect) {
|
|
560
|
+
t->headers = curl_slist_append(t->headers, "Expect:");
|
|
561
|
+
}
|
|
562
|
+
curl_easy_setopt(e, CURLOPT_HTTPHEADER, t->headers);
|
|
563
|
+
if (request.withCredentials) {
|
|
564
|
+
useCookies(e);
|
|
565
|
+
}
|
|
566
|
+
t->touch();
|
|
567
|
+
curl_multi_add_handle(multi_, e);
|
|
568
|
+
transfers_[id] = std::move(t);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
void drop(uint64_t id) {
|
|
572
|
+
auto it = transfers_.find(id);
|
|
573
|
+
if (it != transfers_.end()) {
|
|
574
|
+
curl_multi_remove_handle(multi_, it->second->easy);
|
|
575
|
+
transfers_.erase(it);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
void clearCookies(const std::function<void(bool)> &done) {
|
|
580
|
+
CURL *e = curl_easy_init();
|
|
581
|
+
useCookies(e);
|
|
582
|
+
curl_slist *cookies = nullptr;
|
|
583
|
+
curl_easy_getinfo(e, CURLINFO_COOKIELIST, &cookies);
|
|
584
|
+
bool any = cookies != nullptr;
|
|
585
|
+
curl_slist_free_all(cookies);
|
|
586
|
+
curl_easy_setopt(e, CURLOPT_COOKIELIST, "ALL");
|
|
587
|
+
curl_easy_cleanup(e);
|
|
588
|
+
// Cleared for the next launch too.
|
|
589
|
+
saveCookies();
|
|
590
|
+
if (done) {
|
|
591
|
+
done(any);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// --- WebSocket ----------------------------------------------------------------------------
|
|
596
|
+
|
|
597
|
+
void connect(uint64_t id, const std::string &url, const std::vector<std::string> &protocols, const Headers &headers,
|
|
598
|
+
std::shared_ptr<SocketState> state) {
|
|
599
|
+
{
|
|
600
|
+
std::lock_guard lock(state->mutex);
|
|
601
|
+
if (state->finished) {
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
auto s = std::make_unique<Socket>();
|
|
606
|
+
s->state = std::move(state);
|
|
607
|
+
s->offered = protocols;
|
|
608
|
+
CURL *e = s->easy;
|
|
609
|
+
common(e);
|
|
610
|
+
// The desktop names proxies for http and https; a WebSocket starts as one of those.
|
|
611
|
+
auto ws = webSocketUrl(url);
|
|
612
|
+
auto proxyUrl = startsWithNoCase(ws, "wss:") ? "https:" + ws.substr(4) : "http:" + ws.substr(3);
|
|
613
|
+
curl_easy_setopt(e, CURLOPT_URL, ws.c_str());
|
|
614
|
+
curl_easy_setopt(e, CURLOPT_PROTOCOLS_STR, "ws,wss");
|
|
615
|
+
// The handshake through the multi handle, then frames by curl_ws_send and curl_ws_recv.
|
|
616
|
+
curl_easy_setopt(e, CURLOPT_CONNECT_ONLY, 2L);
|
|
617
|
+
// A ping is answered through the outgoing queue: curl's own pong waits for a send or a read
|
|
618
|
+
// that finds more, which an idle connection never makes.
|
|
619
|
+
curl_easy_setopt(e, CURLOPT_WS_OPTIONS, static_cast<long>(CURLWS_NOAUTOPONG));
|
|
620
|
+
curl_easy_setopt(e, CURLOPT_HEADERFUNCTION, &Engine::onSocketHeader);
|
|
621
|
+
curl_easy_setopt(e, CURLOPT_HEADERDATA, s.get());
|
|
622
|
+
// A refused upgrade's body, which would otherwise go to stdout.
|
|
623
|
+
curl_easy_setopt(e, CURLOPT_WRITEFUNCTION, &Engine::discard);
|
|
624
|
+
for (const auto &[name, value] : headers) {
|
|
625
|
+
s->headers = curl_slist_append(s->headers, (value.empty() ? name + ";" : name + ": " + value).c_str());
|
|
626
|
+
}
|
|
627
|
+
if (!protocols.empty()) {
|
|
628
|
+
std::string joined;
|
|
629
|
+
for (const auto &p : protocols) {
|
|
630
|
+
joined += (joined.empty() ? "" : ", ") + p;
|
|
631
|
+
}
|
|
632
|
+
s->headers = curl_slist_append(s->headers, ("Sec-WebSocket-Protocol: " + joined).c_str());
|
|
633
|
+
}
|
|
634
|
+
curl_easy_setopt(e, CURLOPT_HTTPHEADER, s->headers);
|
|
635
|
+
// The handshake carries the cookie store's cookies, as NSURLSession's does.
|
|
636
|
+
useCookies(e);
|
|
637
|
+
// Held, not yet running, until the desktop's proxy is known; a send meanwhile queues, and a close
|
|
638
|
+
// ends it, as for a handshake in progress.
|
|
639
|
+
sockets_[id] = std::move(s);
|
|
640
|
+
withProxy(proxyUrl, [this, id, proxyUrl] {
|
|
641
|
+
auto it = sockets_.find(id);
|
|
642
|
+
if (it == sockets_.end()) {
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
useProxy(it->second->easy, proxyUrl);
|
|
646
|
+
curl_multi_add_handle(multi_, it->second->easy);
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
void send(uint64_t id, unsigned flags, std::string bytes) {
|
|
651
|
+
auto it = sockets_.find(id);
|
|
652
|
+
if (it == sockets_.end() || it->second->closeQueued || it->second->peerClosed) {
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
it->second->outgoing.push_back({.flags = flags, .bytes = std::move(bytes)});
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
void close(uint64_t id, int code, const std::string &reason) {
|
|
659
|
+
auto it = sockets_.find(id);
|
|
660
|
+
if (it == sockets_.end()) {
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
Socket &s = *it->second;
|
|
664
|
+
if (s.phase == Socket::Phase::Connecting) {
|
|
665
|
+
// As NSURLSession cancels a task that has not opened.
|
|
666
|
+
fail(id, "cancelled");
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
if (s.closeQueued || s.peerClosed) {
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
// A close frame's payload is at most 125 bytes: the code's two and 123 of reason, which stays
|
|
673
|
+
// valid UTF-8.
|
|
674
|
+
queueClose(s, closePayload(code, utf8Prefix(reason, 123)));
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
private:
|
|
678
|
+
void common(CURL *e) {
|
|
679
|
+
curl_easy_setopt(e, CURLOPT_NOSIGNAL, 1L);
|
|
680
|
+
// A proxy's answer to CONNECT is not the response.
|
|
681
|
+
curl_easy_setopt(e, CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L);
|
|
682
|
+
// NSURLSession always names the app, and some servers refuse a request that names nothing. A
|
|
683
|
+
// User-Agent header of the request's own replaces it.
|
|
684
|
+
curl_easy_setopt(e, CURLOPT_USERAGENT, userAgent_.c_str());
|
|
685
|
+
if (!ca_.file.empty()) {
|
|
686
|
+
curl_easy_setopt(e, CURLOPT_CAINFO, ca_.file.c_str());
|
|
687
|
+
}
|
|
688
|
+
if (!ca_.directory.empty()) {
|
|
689
|
+
curl_easy_setopt(e, CURLOPT_CAPATH, ca_.directory.c_str());
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
static std::string originOf(const std::string &url) {
|
|
694
|
+
return url.substr(0, url.find('/', url.find("://") + 3));
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// Runs `resume` on the thread once the desktop's proxy for `url`'s origin is known: at once when it
|
|
698
|
+
// is kept, else after a lookup on a thread of its own, since the answer may take a portal's PAC
|
|
699
|
+
// script and the network thread must go on serving every other transfer meanwhile. Asked once per
|
|
700
|
+
// origin (scheme, host and port) for kProxyKept, so a changed setting arrives within it; one lookup
|
|
701
|
+
// serves every request waiting on its origin.
|
|
702
|
+
void withProxy(const std::string &url, std::function<void()> resume) {
|
|
703
|
+
if (!useDesktopProxies_) {
|
|
704
|
+
resume();
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
auto now = Clock::now();
|
|
708
|
+
std::erase_if(proxies_, [now](const auto &entry) { return now - entry.second.asked >= kProxyKept; });
|
|
709
|
+
auto origin = originOf(url);
|
|
710
|
+
if (proxies_.contains(origin)) {
|
|
711
|
+
resume();
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
auto &waiting = lookups_[origin];
|
|
715
|
+
waiting.push_back(std::move(resume));
|
|
716
|
+
if (waiting.size() > 1) {
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
// The thread holds the engine only while it posts the answer back, and a stopped engine drops it.
|
|
720
|
+
std::thread([weak = weak_from_this(), lookup = options_.desktopProxies, origin, url] {
|
|
721
|
+
auto proxy = curlProxyFor(lookup(url));
|
|
722
|
+
if (auto engine = weak.lock()) {
|
|
723
|
+
engine->post([raw = engine.get(), origin, proxy = std::move(proxy)] { raw->proxyFound(origin, proxy); });
|
|
724
|
+
}
|
|
725
|
+
}).detach();
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
void proxyFound(const std::string &origin, const std::optional<std::string> &proxy) {
|
|
729
|
+
proxies_[origin] = KeptProxy{Clock::now(), proxy};
|
|
730
|
+
auto waiting = std::move(lookups_[origin]);
|
|
731
|
+
lookups_.erase(origin);
|
|
732
|
+
for (auto &resume : waiting) {
|
|
733
|
+
resume();
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
// The kept desktop proxy for `url`, unless the environment names one (libcurl reads it itself); a
|
|
738
|
+
// redirect keeps the first url's proxy.
|
|
739
|
+
void useProxy(CURL *e, const std::string &url) {
|
|
740
|
+
auto it = proxies_.find(originOf(url));
|
|
741
|
+
if (useDesktopProxies_ && it != proxies_.end() && it->second.proxy) {
|
|
742
|
+
curl_easy_setopt(e, CURLOPT_PROXY, it->second.proxy->c_str());
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
void useCookies(CURL *e) {
|
|
747
|
+
curl_easy_setopt(e, CURLOPT_SHARE, share_);
|
|
748
|
+
// An empty name turns the cookie engine on without reading a file.
|
|
749
|
+
curl_easy_setopt(e, CURLOPT_COOKIEFILE, "");
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// The cookie file's lasting cookies into the store.
|
|
753
|
+
void loadCookies() {
|
|
754
|
+
std::ifstream in(options_.cookieFile);
|
|
755
|
+
std::string line;
|
|
756
|
+
time_t now = time(nullptr);
|
|
757
|
+
while (std::getline(in, line)) {
|
|
758
|
+
if (lastingCookie(line, now)) {
|
|
759
|
+
curl_easy_setopt(cookies_, CURLOPT_COOKIELIST, line.c_str());
|
|
760
|
+
saved_ += line + "\n";
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
// The store's lasting cookies into the cookie file, when they differ from what it holds: written
|
|
766
|
+
// beside it, readable by the user alone, then moved over it, so a crash leaves one or the other.
|
|
767
|
+
void saveCookies() {
|
|
768
|
+
if (cookies_ == nullptr) {
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
curl_slist *list = nullptr;
|
|
772
|
+
curl_easy_getinfo(cookies_, CURLINFO_COOKIELIST, &list);
|
|
773
|
+
std::string text;
|
|
774
|
+
time_t now = time(nullptr);
|
|
775
|
+
for (auto *item = list; item != nullptr; item = item->next) {
|
|
776
|
+
if (lastingCookie(item->data, now)) {
|
|
777
|
+
text += std::string(item->data) + "\n";
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
curl_slist_free_all(list);
|
|
781
|
+
if (text == saved_) {
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
std::error_code error;
|
|
785
|
+
std::filesystem::path file(options_.cookieFile);
|
|
786
|
+
std::filesystem::create_directories(file.parent_path(), error);
|
|
787
|
+
auto partial = options_.cookieFile + ".partial";
|
|
788
|
+
int fd = open(partial.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
|
|
789
|
+
if (fd < 0) {
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
std::string out = "# Netscape HTTP Cookie File\n" + text;
|
|
793
|
+
bool written = ::write(fd, out.data(), out.size()) == static_cast<ssize_t>(out.size());
|
|
794
|
+
written = ::close(fd) == 0 && written;
|
|
795
|
+
if (written && rename(partial.c_str(), options_.cookieFile.c_str()) == 0) {
|
|
796
|
+
saved_ = std::move(text);
|
|
797
|
+
} else {
|
|
798
|
+
unlink(partial.c_str());
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// Sends a close frame after what is already queued, and waits kCloseWait for the handshake.
|
|
803
|
+
static void queueClose(Socket &s, std::string payload) {
|
|
804
|
+
s.closeQueued = true;
|
|
805
|
+
s.closeDeadline = Clock::now() + kCloseWait;
|
|
806
|
+
s.outgoing.push_back({.flags = CURLWS_CLOSE, .bytes = std::move(payload)});
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
static std::string closePayload(int code, const std::string &reason) {
|
|
810
|
+
std::string out;
|
|
811
|
+
out += static_cast<char>((code >> 8) & 0xff);
|
|
812
|
+
out += static_cast<char>(code & 0xff);
|
|
813
|
+
return out + reason;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
void answerDataUri(const std::string &uri, HttpState &state) {
|
|
817
|
+
auto bytes = dataUriBytes(uri);
|
|
818
|
+
std::lock_guard lock(state.mutex);
|
|
819
|
+
if (state.done) {
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
if (!bytes) {
|
|
823
|
+
state.done = true;
|
|
824
|
+
if (state.callbacks.onComplete) {
|
|
825
|
+
state.callbacks.onComplete("Invalid URL: " + uri, false);
|
|
826
|
+
}
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
if (state.callbacks.onResponse) {
|
|
830
|
+
state.callbacks.onResponse({.status = 200, .url = uri});
|
|
831
|
+
}
|
|
832
|
+
if (!state.done && !bytes->empty() && state.callbacks.onData) {
|
|
833
|
+
auto size = static_cast<int64_t>(bytes->size());
|
|
834
|
+
state.callbacks.onData(std::move(*bytes), size);
|
|
835
|
+
}
|
|
836
|
+
if (!state.done) {
|
|
837
|
+
state.done = true;
|
|
838
|
+
if (state.callbacks.onComplete) {
|
|
839
|
+
state.callbacks.onComplete("", false);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
static size_t onHeader(char *buffer, size_t size, size_t count, void *data) {
|
|
845
|
+
auto *t = static_cast<Transfer *>(data);
|
|
846
|
+
size_t length = size * count;
|
|
847
|
+
t->touch();
|
|
848
|
+
if (t->responded) {
|
|
849
|
+
// Trailers after the body.
|
|
850
|
+
return length;
|
|
851
|
+
}
|
|
852
|
+
std::string_view line(buffer, length);
|
|
853
|
+
if (line.starts_with("HTTP/")) {
|
|
854
|
+
t->headerLines.clear();
|
|
855
|
+
return length;
|
|
856
|
+
}
|
|
857
|
+
if (trimmed(line).empty()) {
|
|
858
|
+
long status = 0;
|
|
859
|
+
curl_easy_getinfo(t->easy, CURLINFO_RESPONSE_CODE, &status);
|
|
860
|
+
bool interim = status >= 100 && status < 200;
|
|
861
|
+
// What curl follows: any 3xx with a Location that is not empty.
|
|
862
|
+
bool redirect = status >= 300 && status < 400 &&
|
|
863
|
+
std::any_of(t->headerLines.begin(), t->headerLines.end(),
|
|
864
|
+
[](const auto &h) { return sameName(h.first, "location") && !h.second.empty(); });
|
|
865
|
+
if (interim || redirect) {
|
|
866
|
+
// curl goes on to the next response.
|
|
867
|
+
t->headerLines.clear();
|
|
868
|
+
} else if (t->http) {
|
|
869
|
+
t->respond(static_cast<uint16_t>(status));
|
|
870
|
+
}
|
|
871
|
+
return length;
|
|
872
|
+
}
|
|
873
|
+
if ((line.front() == ' ' || line.front() == '\t') && !t->headerLines.empty()) {
|
|
874
|
+
// An obsolete folded line continues the header before it.
|
|
875
|
+
t->headerLines.back().second += " " + std::string(trimmed(line));
|
|
876
|
+
return length;
|
|
877
|
+
}
|
|
878
|
+
auto colon = line.find(':');
|
|
879
|
+
if (colon != std::string_view::npos) {
|
|
880
|
+
t->headerLines.emplace_back(std::string(trimmed(line.substr(0, colon))), std::string(trimmed(line.substr(colon + 1))));
|
|
881
|
+
}
|
|
882
|
+
return length;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
static size_t onWrite(char *buffer, size_t size, size_t count, void *data) {
|
|
886
|
+
auto *t = static_cast<Transfer *>(data);
|
|
887
|
+
size_t length = size * count;
|
|
888
|
+
t->touch();
|
|
889
|
+
if (!t->responded) {
|
|
890
|
+
if (t->http) {
|
|
891
|
+
// A redirect's own body.
|
|
892
|
+
return length;
|
|
893
|
+
}
|
|
894
|
+
t->respond(200);
|
|
895
|
+
}
|
|
896
|
+
curl_off_t expected = -1;
|
|
897
|
+
curl_easy_getinfo(t->easy, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &expected);
|
|
898
|
+
std::lock_guard lock(t->state->mutex);
|
|
899
|
+
if (!t->state->done && t->state->callbacks.onData) {
|
|
900
|
+
t->state->callbacks.onData(std::string(buffer, length), expected < 0 ? -1 : static_cast<int64_t>(expected));
|
|
901
|
+
}
|
|
902
|
+
return length;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
static int onProgress(void *data, curl_off_t, curl_off_t, curl_off_t total, curl_off_t sent) {
|
|
906
|
+
auto *t = static_cast<Transfer *>(data);
|
|
907
|
+
if (total > 0 && sent > t->sentReported) {
|
|
908
|
+
t->touch();
|
|
909
|
+
t->sentReported = sent;
|
|
910
|
+
std::lock_guard lock(t->state->mutex);
|
|
911
|
+
if (!t->state->done && t->state->callbacks.onUploadProgress) {
|
|
912
|
+
t->state->callbacks.onUploadProgress(sent, total);
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
return 0;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
static size_t discard(char *, size_t size, size_t count, void *) {
|
|
919
|
+
return size * count;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
static size_t onSocketHeader(char *buffer, size_t size, size_t count, void *data) {
|
|
923
|
+
auto *s = static_cast<Socket *>(data);
|
|
924
|
+
std::string_view line(buffer, size * count);
|
|
925
|
+
if (line.starts_with("HTTP/")) {
|
|
926
|
+
s->protocol.clear();
|
|
927
|
+
}
|
|
928
|
+
auto colon = line.find(':');
|
|
929
|
+
if (colon != std::string_view::npos && sameName(trimmed(line.substr(0, colon)), "sec-websocket-protocol")) {
|
|
930
|
+
s->protocol = std::string(trimmed(line.substr(colon + 1)));
|
|
931
|
+
}
|
|
932
|
+
return size * count;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
void finish(Transfer &t, const std::string &error, bool timedOut) {
|
|
936
|
+
std::lock_guard lock(t.state->mutex);
|
|
937
|
+
if (t.state->done) {
|
|
938
|
+
return;
|
|
939
|
+
}
|
|
940
|
+
t.state->done = true;
|
|
941
|
+
if (t.state->callbacks.onComplete) {
|
|
942
|
+
t.state->callbacks.onComplete(error, timedOut);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
void finished() {
|
|
947
|
+
int left = 0;
|
|
948
|
+
bool any = false;
|
|
949
|
+
while (CURLMsg *msg = curl_multi_info_read(multi_, &left)) {
|
|
950
|
+
if (msg->msg != CURLMSG_DONE) {
|
|
951
|
+
continue;
|
|
952
|
+
}
|
|
953
|
+
any = true;
|
|
954
|
+
CURL *e = msg->easy_handle;
|
|
955
|
+
CURLcode result = msg->data.result;
|
|
956
|
+
if (auto t = takeTransfer(e)) {
|
|
957
|
+
curl_multi_remove_handle(multi_, e);
|
|
958
|
+
if (result == CURLE_OK) {
|
|
959
|
+
if (!t->responded) {
|
|
960
|
+
// A `file:` url with an empty file, or a response with no header block end.
|
|
961
|
+
long status = 200;
|
|
962
|
+
if (t->http) {
|
|
963
|
+
curl_easy_getinfo(e, CURLINFO_RESPONSE_CODE, &status);
|
|
964
|
+
}
|
|
965
|
+
t->respond(static_cast<uint16_t>(status));
|
|
966
|
+
}
|
|
967
|
+
finish(*t, "", false);
|
|
968
|
+
} else {
|
|
969
|
+
finish(*t, errorText(result), result == CURLE_OPERATION_TIMEDOUT);
|
|
970
|
+
}
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
for (auto &[id, s] : sockets_) {
|
|
974
|
+
if (s->easy != e) {
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
if (result != CURLE_OK) {
|
|
978
|
+
fail(id, errorText(result));
|
|
979
|
+
} else {
|
|
980
|
+
opened(id, *s);
|
|
981
|
+
}
|
|
982
|
+
break;
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
// A response or a handshake may have set cookies.
|
|
986
|
+
if (any) {
|
|
987
|
+
saveCookies();
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
std::unique_ptr<Transfer> takeTransfer(CURL *e) {
|
|
992
|
+
for (auto it = transfers_.begin(); it != transfers_.end(); ++it) {
|
|
993
|
+
if (it->second->easy == e) {
|
|
994
|
+
auto t = std::move(it->second);
|
|
995
|
+
transfers_.erase(it);
|
|
996
|
+
return t;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
return nullptr;
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
void opened(uint64_t id, Socket &s) {
|
|
1003
|
+
// The handle stays in the multi handle, whose connection pool keeps the connection
|
|
1004
|
+
// curl_ws_recv and curl_ws_send find.
|
|
1005
|
+
if (!s.protocol.empty() && std::find(s.offered.begin(), s.offered.end(), s.protocol) == s.offered.end()) {
|
|
1006
|
+
// A subprotocol the client never offered fails the connection, as a browser's does.
|
|
1007
|
+
fail(id, errorText(CURLE_WEIRD_SERVER_REPLY));
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
curl_easy_getinfo(s.easy, CURLINFO_ACTIVESOCKET, &s.fd);
|
|
1011
|
+
s.phase = Socket::Phase::Open;
|
|
1012
|
+
std::lock_guard lock(s.state->mutex);
|
|
1013
|
+
if (!s.state->finished && s.state->callbacks.onOpen) {
|
|
1014
|
+
s.state->callbacks.onOpen(s.protocol);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// Ends a socket with its error. Nothing follows.
|
|
1019
|
+
void fail(uint64_t id, const std::string &message) {
|
|
1020
|
+
auto it = sockets_.find(id);
|
|
1021
|
+
if (it == sockets_.end()) {
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
auto s = std::move(it->second);
|
|
1025
|
+
sockets_.erase(it);
|
|
1026
|
+
curl_multi_remove_handle(multi_, s->easy);
|
|
1027
|
+
std::lock_guard lock(s->state->mutex);
|
|
1028
|
+
if (!s->state->finished) {
|
|
1029
|
+
s->state->finished = true;
|
|
1030
|
+
if (s->state->callbacks.onError) {
|
|
1031
|
+
s->state->callbacks.onError(message);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
void closed(uint64_t id, int code, const std::string &reason) {
|
|
1037
|
+
auto it = sockets_.find(id);
|
|
1038
|
+
if (it == sockets_.end()) {
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
auto s = std::move(it->second);
|
|
1042
|
+
sockets_.erase(it);
|
|
1043
|
+
curl_multi_remove_handle(multi_, s->easy);
|
|
1044
|
+
std::lock_guard lock(s->state->mutex);
|
|
1045
|
+
if (!s->state->finished) {
|
|
1046
|
+
s->state->finished = true;
|
|
1047
|
+
if (s->state->callbacks.onClose) {
|
|
1048
|
+
s->state->callbacks.onClose(code, reason);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
void serviceSockets() {
|
|
1054
|
+
more_ = false;
|
|
1055
|
+
std::vector<uint64_t> open;
|
|
1056
|
+
for (auto &[id, s] : sockets_) {
|
|
1057
|
+
if (s->phase == Socket::Phase::Open) {
|
|
1058
|
+
open.push_back(id);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
// A callback may close or drop any socket, so each is found again by its id.
|
|
1062
|
+
for (uint64_t id : open) {
|
|
1063
|
+
if (!flush(id)) {
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
auto it = sockets_.find(id);
|
|
1067
|
+
// Past the server's close frame there is nothing to read.
|
|
1068
|
+
if (it != sockets_.end() && !it->second->peerClosed && receive(id)) {
|
|
1069
|
+
// curl may hold the rest already, which no poll would wake for.
|
|
1070
|
+
more_ = true;
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// Sends what curl takes now; false once the socket is gone.
|
|
1076
|
+
bool flush(uint64_t id) {
|
|
1077
|
+
auto it = sockets_.find(id);
|
|
1078
|
+
if (it == sockets_.end()) {
|
|
1079
|
+
return false;
|
|
1080
|
+
}
|
|
1081
|
+
Socket &s = *it->second;
|
|
1082
|
+
while (!s.outgoing.empty()) {
|
|
1083
|
+
auto &frame = s.outgoing.front();
|
|
1084
|
+
size_t sent = 0;
|
|
1085
|
+
CURLcode rc = curl_ws_send(
|
|
1086
|
+
s.easy, frame.bytes.data() + frame.offset, frame.bytes.size() - frame.offset, &sent, 0, frame.flags);
|
|
1087
|
+
if (rc == CURLE_AGAIN) {
|
|
1088
|
+
frame.started = true;
|
|
1089
|
+
return true;
|
|
1090
|
+
}
|
|
1091
|
+
if (rc != CURLE_OK) {
|
|
1092
|
+
if (s.peerClosed) {
|
|
1093
|
+
// The server closed, and went before this side's answer did.
|
|
1094
|
+
closed(id, s.peerCode, s.peerReason);
|
|
1095
|
+
} else {
|
|
1096
|
+
fail(id, errorText(rc));
|
|
1097
|
+
}
|
|
1098
|
+
return false;
|
|
1099
|
+
}
|
|
1100
|
+
frame.started = true;
|
|
1101
|
+
frame.offset += sent;
|
|
1102
|
+
if (frame.offset < frame.bytes.size()) {
|
|
1103
|
+
// The rest of this frame when the socket can take it.
|
|
1104
|
+
return true;
|
|
1105
|
+
}
|
|
1106
|
+
bool close = (frame.flags & CURLWS_CLOSE) != 0;
|
|
1107
|
+
s.outgoing.pop_front();
|
|
1108
|
+
if (close) {
|
|
1109
|
+
s.closeSent = true;
|
|
1110
|
+
if (s.peerClosed) {
|
|
1111
|
+
closed(id, s.peerCode, s.peerReason);
|
|
1112
|
+
return false;
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
return true;
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
// Reads what has come, up to kReceiveBudget reads; true when the budget ran out first.
|
|
1120
|
+
bool receive(uint64_t id) {
|
|
1121
|
+
char buffer[64 * 1024];
|
|
1122
|
+
for (int reads = 0; reads < kReceiveBudget; ++reads) {
|
|
1123
|
+
auto it = sockets_.find(id);
|
|
1124
|
+
if (it == sockets_.end()) {
|
|
1125
|
+
return false;
|
|
1126
|
+
}
|
|
1127
|
+
Socket &s = *it->second;
|
|
1128
|
+
size_t n = 0;
|
|
1129
|
+
const curl_ws_frame *meta = nullptr;
|
|
1130
|
+
CURLcode rc = curl_ws_recv(s.easy, buffer, sizeof buffer, &n, &meta);
|
|
1131
|
+
if (rc == CURLE_AGAIN) {
|
|
1132
|
+
return false;
|
|
1133
|
+
}
|
|
1134
|
+
if (rc != CURLE_OK || meta == nullptr) {
|
|
1135
|
+
if (s.closeQueued) {
|
|
1136
|
+
// The server went without its close frame: 1006, an abnormal closure.
|
|
1137
|
+
closed(id, 1006, "");
|
|
1138
|
+
} else {
|
|
1139
|
+
fail(id, rc == CURLE_GOT_NOTHING || rc == CURLE_OK ? "The network connection was lost." : errorText(rc));
|
|
1140
|
+
}
|
|
1141
|
+
return false;
|
|
1142
|
+
}
|
|
1143
|
+
if (meta->flags & CURLWS_CLOSE) {
|
|
1144
|
+
s.closePayload.append(buffer, n);
|
|
1145
|
+
if (meta->bytesleft == 0) {
|
|
1146
|
+
serverClosed(id, s);
|
|
1147
|
+
return false;
|
|
1148
|
+
}
|
|
1149
|
+
continue;
|
|
1150
|
+
}
|
|
1151
|
+
if (meta->flags & CURLWS_PING) {
|
|
1152
|
+
s.pingPayload.append(buffer, n);
|
|
1153
|
+
if (meta->bytesleft == 0) {
|
|
1154
|
+
queuePong(s);
|
|
1155
|
+
}
|
|
1156
|
+
continue;
|
|
1157
|
+
}
|
|
1158
|
+
if (meta->flags & CURLWS_PONG) {
|
|
1159
|
+
continue;
|
|
1160
|
+
}
|
|
1161
|
+
if (s.message.empty()) {
|
|
1162
|
+
s.messageFlags = meta->flags & (CURLWS_TEXT | CURLWS_BINARY);
|
|
1163
|
+
}
|
|
1164
|
+
s.message.append(buffer, n);
|
|
1165
|
+
if (s.message.size() > kMaxMessage) {
|
|
1166
|
+
fail(id, "Message too long");
|
|
1167
|
+
return false;
|
|
1168
|
+
}
|
|
1169
|
+
if (meta->bytesleft == 0 && !(meta->flags & CURLWS_CONT) && !deliver(id, s)) {
|
|
1170
|
+
return false;
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
return true;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
// The pong to the ping just read, ahead of anything not yet begun and of this side's close.
|
|
1177
|
+
static void queuePong(Socket &s) {
|
|
1178
|
+
std::string payload;
|
|
1179
|
+
payload.swap(s.pingPayload);
|
|
1180
|
+
if (s.closeSent) {
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
// One pong waits at most: a later ping's replaces it, as RFC 6455 allows, so a peer that
|
|
1184
|
+
// pings without reading cannot grow the queue.
|
|
1185
|
+
for (auto &frame : s.outgoing) {
|
|
1186
|
+
if (!frame.started && (frame.flags & CURLWS_PONG)) {
|
|
1187
|
+
frame.bytes = std::move(payload);
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
auto at = s.outgoing.begin();
|
|
1192
|
+
if (at != s.outgoing.end() && at->started) {
|
|
1193
|
+
++at;
|
|
1194
|
+
}
|
|
1195
|
+
s.outgoing.insert(at, {.flags = CURLWS_PONG, .bytes = std::move(payload)});
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// False once a text message that is not UTF-8 has failed the socket.
|
|
1199
|
+
bool deliver(uint64_t id, Socket &s) {
|
|
1200
|
+
std::string message;
|
|
1201
|
+
message.swap(s.message);
|
|
1202
|
+
if ((s.messageFlags & CURLWS_TEXT) && !validUtf8(message)) {
|
|
1203
|
+
// As a browser fails the connection on a text message that is not UTF-8.
|
|
1204
|
+
fail(id, "Invalid UTF-8 in a text message");
|
|
1205
|
+
return false;
|
|
1206
|
+
}
|
|
1207
|
+
std::lock_guard lock(s.state->mutex);
|
|
1208
|
+
if (s.state->finished) {
|
|
1209
|
+
return true;
|
|
1210
|
+
}
|
|
1211
|
+
if (s.messageFlags & CURLWS_TEXT) {
|
|
1212
|
+
if (s.state->callbacks.onText) {
|
|
1213
|
+
s.state->callbacks.onText(message);
|
|
1214
|
+
}
|
|
1215
|
+
} else if (s.state->callbacks.onBinary) {
|
|
1216
|
+
s.state->callbacks.onBinary(message);
|
|
1217
|
+
}
|
|
1218
|
+
return true;
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
// The server's close frame. The socket closes with its code once this side's close frame has
|
|
1222
|
+
// gone, or kCloseWait after.
|
|
1223
|
+
void serverClosed(uint64_t id, Socket &s) {
|
|
1224
|
+
s.peerClosed = true;
|
|
1225
|
+
// 1005: the frame named no code.
|
|
1226
|
+
if (s.closePayload.size() >= 2) {
|
|
1227
|
+
s.peerCode = (static_cast<unsigned char>(s.closePayload[0]) << 8) | static_cast<unsigned char>(s.closePayload[1]);
|
|
1228
|
+
s.peerReason = s.closePayload.substr(2);
|
|
1229
|
+
}
|
|
1230
|
+
if (s.closeSent) {
|
|
1231
|
+
closed(id, s.peerCode, s.peerReason);
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
// Only a frame curl has begun still goes, then this side's close frame: the one queued, else
|
|
1235
|
+
// the closing handshake's answer, echoing the server's code.
|
|
1236
|
+
std::erase_if(s.outgoing, [](const Socket::Frame &f) { return !f.started && !(f.flags & CURLWS_CLOSE); });
|
|
1237
|
+
if (!s.closeQueued) {
|
|
1238
|
+
queueClose(s, s.peerCode == 1005 ? "" : closePayload(s.peerCode, ""));
|
|
1239
|
+
}
|
|
1240
|
+
flush(id);
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
void expire() {
|
|
1244
|
+
auto now = Clock::now();
|
|
1245
|
+
std::vector<uint64_t> late;
|
|
1246
|
+
for (auto &[id, t] : transfers_) {
|
|
1247
|
+
if (now - t->lastActivity >= t->idle) {
|
|
1248
|
+
late.push_back(id);
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
for (uint64_t id : late) {
|
|
1252
|
+
auto it = transfers_.find(id);
|
|
1253
|
+
auto t = std::move(it->second);
|
|
1254
|
+
transfers_.erase(it);
|
|
1255
|
+
curl_multi_remove_handle(multi_, t->easy);
|
|
1256
|
+
finish(*t, errorText(CURLE_OPERATION_TIMEDOUT), true);
|
|
1257
|
+
}
|
|
1258
|
+
std::vector<uint64_t> unopened, unanswered;
|
|
1259
|
+
for (auto &[id, s] : sockets_) {
|
|
1260
|
+
if (s->phase == Socket::Phase::Connecting && now - s->started >= kHandshakeTimeout) {
|
|
1261
|
+
unopened.push_back(id);
|
|
1262
|
+
} else if (s->closeQueued && now >= s->closeDeadline) {
|
|
1263
|
+
unanswered.push_back(id);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
for (uint64_t id : unopened) {
|
|
1267
|
+
fail(id, errorText(CURLE_OPERATION_TIMEDOUT));
|
|
1268
|
+
}
|
|
1269
|
+
for (uint64_t id : unanswered) {
|
|
1270
|
+
auto &s = *sockets_.at(id);
|
|
1271
|
+
if (s.peerClosed) {
|
|
1272
|
+
closed(id, s.peerCode, s.peerReason);
|
|
1273
|
+
} else {
|
|
1274
|
+
// No close frame from the server: 1006, an abnormal closure.
|
|
1275
|
+
closed(id, 1006, "");
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
int nextWaitMs() const {
|
|
1281
|
+
if (more_) {
|
|
1282
|
+
return 0;
|
|
1283
|
+
}
|
|
1284
|
+
auto now = Clock::now();
|
|
1285
|
+
auto next = now + std::chrono::seconds(60);
|
|
1286
|
+
for (auto &[_, t] : transfers_) {
|
|
1287
|
+
next = std::min(next, t->lastActivity + t->idle);
|
|
1288
|
+
}
|
|
1289
|
+
for (auto &[_, s] : sockets_) {
|
|
1290
|
+
if (s->phase == Socket::Phase::Connecting) {
|
|
1291
|
+
next = std::min(next, s->started + kHandshakeTimeout);
|
|
1292
|
+
} else if (s->closeQueued) {
|
|
1293
|
+
next = std::min(next, s->closeDeadline);
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
auto wait = std::chrono::duration_cast<milliseconds>(next - now).count();
|
|
1297
|
+
return static_cast<int>(std::max<int64_t>(wait + 1, 0));
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
CurlOptions options_;
|
|
1301
|
+
std::string userAgent_{curlUserAgent(options_.appName, options_.appVersion)};
|
|
1302
|
+
bool useDesktopProxies_{false};
|
|
1303
|
+
struct KeptProxy {
|
|
1304
|
+
Clock::time_point asked;
|
|
1305
|
+
std::optional<std::string> proxy;
|
|
1306
|
+
};
|
|
1307
|
+
// The desktop's answers by origin, while they are fresh.
|
|
1308
|
+
std::map<std::string, KeptProxy> proxies_;
|
|
1309
|
+
// The requests waiting on a lookup, by origin.
|
|
1310
|
+
std::map<std::string, std::vector<std::function<void()>>> lookups_;
|
|
1311
|
+
CURLM *multi_;
|
|
1312
|
+
CURLSH *share_;
|
|
1313
|
+
// Reads and fills the store for the cookie file, with what the file last held.
|
|
1314
|
+
CURL *cookies_{nullptr};
|
|
1315
|
+
std::string saved_;
|
|
1316
|
+
CaCertificates ca_;
|
|
1317
|
+
std::mutex mutex_;
|
|
1318
|
+
std::vector<std::function<void()>> queue_;
|
|
1319
|
+
bool stopping_{false};
|
|
1320
|
+
// A socket's receive budget ran out with more to read, so the next poll does not wait.
|
|
1321
|
+
bool more_{false};
|
|
1322
|
+
std::atomic<uint64_t> ids_{0};
|
|
1323
|
+
std::map<uint64_t, std::unique_ptr<Transfer>> transfers_;
|
|
1324
|
+
std::map<uint64_t, std::unique_ptr<Socket>> sockets_;
|
|
1325
|
+
};
|
|
1326
|
+
|
|
1327
|
+
// Owns the thread. The thread holds the engine until it returns, so a last owner let go on the
|
|
1328
|
+
// thread itself (a callback dropping a client) leaves it to finish on its own.
|
|
1329
|
+
class Client {
|
|
1330
|
+
public:
|
|
1331
|
+
explicit Client(CurlOptions options) : engine_(std::make_shared<Engine>(std::move(options))) {
|
|
1332
|
+
thread_ = std::thread([engine = engine_] { engine->run(); });
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
~Client() {
|
|
1336
|
+
engine_->stop();
|
|
1337
|
+
if (thread_.get_id() == std::this_thread::get_id()) {
|
|
1338
|
+
thread_.detach();
|
|
1339
|
+
} else {
|
|
1340
|
+
thread_.join();
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
const std::shared_ptr<Engine> &engine() const {
|
|
1345
|
+
return engine_;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
private:
|
|
1349
|
+
std::shared_ptr<Engine> engine_;
|
|
1350
|
+
std::thread thread_;
|
|
1351
|
+
};
|
|
1352
|
+
|
|
1353
|
+
struct Task final : HttpTask {
|
|
1354
|
+
Task(std::weak_ptr<Engine> engine, uint64_t id, std::shared_ptr<HttpState> state)
|
|
1355
|
+
: engine(std::move(engine)), id(id), state(std::move(state)) {}
|
|
1356
|
+
void cancel() override {
|
|
1357
|
+
{
|
|
1358
|
+
std::lock_guard lock(state->mutex);
|
|
1359
|
+
state->done = true;
|
|
1360
|
+
}
|
|
1361
|
+
if (auto e = engine.lock()) {
|
|
1362
|
+
e->post([raw = e.get(), id = id] { raw->drop(id); });
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
std::weak_ptr<Engine> engine;
|
|
1366
|
+
uint64_t id;
|
|
1367
|
+
std::shared_ptr<HttpState> state;
|
|
1368
|
+
};
|
|
1369
|
+
|
|
1370
|
+
class CurlHttp final : public Http {
|
|
1371
|
+
public:
|
|
1372
|
+
explicit CurlHttp(std::shared_ptr<Client> client) : client_(std::move(client)) {}
|
|
1373
|
+
|
|
1374
|
+
std::unique_ptr<HttpTask> send(HttpRequest request, HttpCallbacks callbacks) override {
|
|
1375
|
+
auto state = std::make_shared<HttpState>();
|
|
1376
|
+
state->callbacks = std::move(callbacks);
|
|
1377
|
+
if (!startsWithNoCase(request.url, "data:") && !parses(request.url)) {
|
|
1378
|
+
if (state->callbacks.onComplete) {
|
|
1379
|
+
state->callbacks.onComplete("Invalid URL: " + request.url, false);
|
|
1380
|
+
}
|
|
1381
|
+
return nullptr;
|
|
1382
|
+
}
|
|
1383
|
+
auto &engine = client_->engine();
|
|
1384
|
+
uint64_t id = engine->nextId();
|
|
1385
|
+
engine->post([raw = engine.get(), id, request = std::move(request), state]() mutable {
|
|
1386
|
+
raw->start(id, std::move(request), state);
|
|
1387
|
+
});
|
|
1388
|
+
return std::make_unique<Task>(engine, id, std::move(state));
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
void clearCookies(std::function<void(bool cleared)> done) override {
|
|
1392
|
+
auto &engine = client_->engine();
|
|
1393
|
+
engine->post([raw = engine.get(), done = std::move(done)] { raw->clearCookies(done); });
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
private:
|
|
1397
|
+
std::shared_ptr<Client> client_;
|
|
1398
|
+
};
|
|
1399
|
+
|
|
1400
|
+
struct Connection final : WebSocketConnection {
|
|
1401
|
+
Connection(std::weak_ptr<Engine> engine, uint64_t id) : engine(std::move(engine)), id(id) {}
|
|
1402
|
+
~Connection() override {
|
|
1403
|
+
close(1001, "");
|
|
1404
|
+
}
|
|
1405
|
+
void sendText(const std::string &text) override {
|
|
1406
|
+
send(CURLWS_TEXT, text);
|
|
1407
|
+
}
|
|
1408
|
+
void sendBinary(const std::string &bytes) override {
|
|
1409
|
+
send(CURLWS_BINARY, bytes);
|
|
1410
|
+
}
|
|
1411
|
+
void ping() override {
|
|
1412
|
+
send(CURLWS_PING, "");
|
|
1413
|
+
}
|
|
1414
|
+
void close(int code, const std::string &reason) override {
|
|
1415
|
+
if (auto e = engine.lock()) {
|
|
1416
|
+
e->post([raw = e.get(), id = id, code, reason] { raw->close(id, code, reason); });
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
void send(unsigned flags, std::string bytes) {
|
|
1420
|
+
if (auto e = engine.lock()) {
|
|
1421
|
+
e->post([raw = e.get(), id = id, flags, bytes = std::move(bytes)]() mutable { raw->send(id, flags, std::move(bytes)); });
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
std::weak_ptr<Engine> engine;
|
|
1425
|
+
uint64_t id;
|
|
1426
|
+
};
|
|
1427
|
+
|
|
1428
|
+
class CurlWebSockets final : public WebSockets {
|
|
1429
|
+
public:
|
|
1430
|
+
explicit CurlWebSockets(std::shared_ptr<Client> client) : client_(std::move(client)) {}
|
|
1431
|
+
|
|
1432
|
+
std::unique_ptr<WebSocketConnection> connect(
|
|
1433
|
+
const std::string &url,
|
|
1434
|
+
const std::vector<std::string> &protocols,
|
|
1435
|
+
const Headers &headers,
|
|
1436
|
+
WebSocketCallbacks callbacks) override {
|
|
1437
|
+
auto state = std::make_shared<SocketState>();
|
|
1438
|
+
state->callbacks = std::move(callbacks);
|
|
1439
|
+
if (!parses(url)) {
|
|
1440
|
+
if (state->callbacks.onError) {
|
|
1441
|
+
state->callbacks.onError("Invalid URL: " + url);
|
|
1442
|
+
}
|
|
1443
|
+
return nullptr;
|
|
1444
|
+
}
|
|
1445
|
+
auto &engine = client_->engine();
|
|
1446
|
+
uint64_t id = engine->nextId();
|
|
1447
|
+
engine->post([raw = engine.get(), id, url, protocols, headers, state] { raw->connect(id, url, protocols, headers, state); });
|
|
1448
|
+
return std::make_unique<Connection>(engine, id);
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
private:
|
|
1452
|
+
std::shared_ptr<Client> client_;
|
|
1453
|
+
};
|
|
1454
|
+
|
|
1455
|
+
} // namespace
|
|
1456
|
+
|
|
1457
|
+
CurlNetwork makeCurlNetwork(CurlOptions options) {
|
|
1458
|
+
auto client = std::make_shared<Client>(std::move(options));
|
|
1459
|
+
return {.http = std::make_shared<CurlHttp>(client), .webSockets = std::make_shared<CurlWebSockets>(client)};
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
// `text` as one HTTP token (RFC 9110's tchar, but `/`, which ends a product's name), with what a
|
|
1463
|
+
// token cannot hold percent-encoded, as CFNetwork encodes an app's name.
|
|
1464
|
+
static std::string tokenOf(const std::string &text) {
|
|
1465
|
+
std::string out;
|
|
1466
|
+
for (unsigned char c : text) {
|
|
1467
|
+
if ((c < 0x80 && std::isalnum(c)) || std::string_view("!#$&'*+-.^_`|~").find(static_cast<char>(c)) != std::string_view::npos) {
|
|
1468
|
+
out += static_cast<char>(c);
|
|
1469
|
+
} else {
|
|
1470
|
+
static const char *hex = "0123456789ABCDEF";
|
|
1471
|
+
out += '%';
|
|
1472
|
+
out += hex[c >> 4];
|
|
1473
|
+
out += hex[c & 15];
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
return out;
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
std::string curlUserAgent(const std::string &appName, const std::string &appVersion) {
|
|
1480
|
+
std::string agent = "ng-native libcurl/" LIBCURL_VERSION;
|
|
1481
|
+
if (appName.empty()) {
|
|
1482
|
+
return agent;
|
|
1483
|
+
}
|
|
1484
|
+
return tokenOf(appName) + (appVersion.empty() ? "" : "/" + tokenOf(appVersion)) + " " + agent;
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
std::optional<std::string> curlProxyFor(const std::vector<std::string> &proxies) {
|
|
1488
|
+
for (const auto &proxy : proxies) {
|
|
1489
|
+
if (startsWithNoCase(proxy, "direct://")) {
|
|
1490
|
+
return std::string();
|
|
1491
|
+
}
|
|
1492
|
+
// GLib's SOCKS 5 hands the proxy the host name to resolve; libcurl's `socks5://` resolves it here,
|
|
1493
|
+
// so a host only the proxy's side knows would fail.
|
|
1494
|
+
for (const char *scheme : {"socks://", "socks5://"}) {
|
|
1495
|
+
if (startsWithNoCase(proxy, scheme)) {
|
|
1496
|
+
return "socks5h://" + proxy.substr(std::strlen(scheme));
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
for (const char *scheme : {"http://", "https://", "socks4://", "socks4a://", "socks5h://"}) {
|
|
1500
|
+
if (startsWithNoCase(proxy, scheme)) {
|
|
1501
|
+
return proxy;
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
return std::nullopt;
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
bool proxyEnvironmentSet(const std::function<std::optional<std::string>(const char *name)> &env) {
|
|
1509
|
+
for (const char *name : {"http_proxy", "https_proxy", "HTTPS_PROXY", "ws_proxy", "wss_proxy", "WS_PROXY", "WSS_PROXY", "all_proxy", "ALL_PROXY"}) {
|
|
1510
|
+
if (auto value = env(name); value && !value->empty()) {
|
|
1511
|
+
return true;
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
return false;
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
CaCertificates findCaCertificates(const CaProbe &probe) {
|
|
1518
|
+
auto file = probe.env("SSL_CERT_FILE");
|
|
1519
|
+
auto directory = probe.env("SSL_CERT_DIR");
|
|
1520
|
+
if ((file && !file->empty()) || (directory && !directory->empty())) {
|
|
1521
|
+
return {.file = file.value_or(""), .directory = directory.value_or("")};
|
|
1522
|
+
}
|
|
1523
|
+
for (const char *path : {
|
|
1524
|
+
"/etc/ssl/certs/ca-certificates.crt", // Debian, Ubuntu, Arch, Gentoo, the Flatpak runtimes
|
|
1525
|
+
"/etc/pki/tls/certs/ca-bundle.crt", // Fedora, RHEL and its rebuilds
|
|
1526
|
+
"/etc/ssl/ca-bundle.pem", // openSUSE
|
|
1527
|
+
"/etc/pki/tls/cacert.pem", // OpenELEC
|
|
1528
|
+
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // CentOS and RHEL 7
|
|
1529
|
+
"/etc/ssl/cert.pem", // Alpine, and macOS for a GTK build there
|
|
1530
|
+
}) {
|
|
1531
|
+
if (probe.isFile(path)) {
|
|
1532
|
+
return {.file = path};
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
for (const char *path : {"/etc/ssl/certs", "/etc/pki/tls/certs"}) {
|
|
1536
|
+
if (probe.isDirectory(path)) {
|
|
1537
|
+
return {.directory = path};
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
return {};
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
CaCertificates findCaCertificates() {
|
|
1544
|
+
return findCaCertificates({
|
|
1545
|
+
.env = [](const char *name) -> std::optional<std::string> {
|
|
1546
|
+
const char *value = std::getenv(name);
|
|
1547
|
+
return value ? std::optional<std::string>(value) : std::nullopt;
|
|
1548
|
+
},
|
|
1549
|
+
.isFile =
|
|
1550
|
+
[](const std::string &path) {
|
|
1551
|
+
struct stat st {};
|
|
1552
|
+
return stat(path.c_str(), &st) == 0 && S_ISREG(st.st_mode) && access(path.c_str(), R_OK) == 0;
|
|
1553
|
+
},
|
|
1554
|
+
.isDirectory =
|
|
1555
|
+
[](const std::string &path) {
|
|
1556
|
+
struct stat st {};
|
|
1557
|
+
return stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
|
|
1558
|
+
},
|
|
1559
|
+
});
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
} // namespace ngn
|