-
Notifications
You must be signed in to change notification settings - Fork 22
/
evision_precompiled.erl
420 lines (385 loc) · 16.5 KB
/
evision_precompiled.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
-module(evision_precompiled).
-export([is_precompiled_binary_available/0, install_precompiled_binary_if_available/0]).
-import(checksum, [checksum/0]).
-define(PRECOMPILED_TARBALL_NAME, "evision-nif_~s-~s-~s").
-define(PRECOMPILED_DOWNLOAD_URL, "https://github.com/cocoa-xu/evision/releases/download/v~s/~s").
-define(EVISION_SO_FILE, "priv/evision.so").
-define(EVISION_DLL_FILE, "priv/evision.dll").
-define(ERLANG_GENERATED_SOURCE_DIR, "src/generated").
-include_lib("kernel/include/file.hrl").
app_version() ->
{ok, Cwd} = file:get_cwd(),
Src = filename:join([Cwd, "src", "evision.app.src"]),
case file:read_file(Src) of
{ok, BinContent} ->
Content = binary_to_list(BinContent),
case erl_scan:string(Content) of
{ok, Tokens, _} ->
case erl_parse:parse_term(Tokens) of
{ok, {application, evision, App}} ->
case proplists:get_value(vsn, App) of
undefined ->
"unknown";
Version ->
case is_list(Version) of
true ->
Version;
false ->
"unknown"
end
end;
{error, _} ->
"unknown"
end;
{error, _} ->
"unknown"
end;
{error, _} ->
"unknown"
end.
is_dev() ->
AppVersion = app_version(),
case string:find(AppVersion, "-dev") of
nomatch ->
{false, AppVersion};
_ ->
{true, AppVersion}
end.
only_darwin(DarwinABI) ->
case string:prefix(DarwinABI, "darwin") of
nomatch ->
DarwinABI;
_ ->
"darwin"
end.
maybe_override_by_env(EnvName, Default) ->
case os:getenv(EnvName) of
false ->
Default;
Value ->
Value
end.
get_target() ->
TargetParts = string:split(erlang:system_info(system_architecture), "-", all),
[G_ARCH, G_OS, G_ABI] = case length(TargetParts) of
4 ->
[T_ARCH, _, T_OS, T_ABI] = TargetParts,
[T_ARCH, T_OS, only_darwin(T_ABI)];
3 ->
[T_ARCH, T_OS, T_ABI] = TargetParts,
[T_ARCH, T_OS, only_darwin(T_ABI)];
1 ->
case TargetParts of
["win32"] ->
WIN_ARCH = case maybe_override_by_env("PROCESSOR_ARCHITECTURE", "x86_64") of
"ARM64" ->
"aarch64";
PROCESSOR_ARCHITECTURE ->
PROCESSOR_ARCHITECTURE
end,
[WIN_ARCH, "windows", "msvc"];
_ ->
["unknown", "unknown", "unknown"]
end
end,
ARCH = maybe_override_by_env("TARGET_ARCH", G_ARCH),
OS = maybe_override_by_env("TARGET_OS", G_OS),
ABI = maybe_override_by_env("TARGET_ABI", G_ABI),
TRIPLET = io_lib:fwrite("~s-~s-~s", [ARCH, OS, ABI]),
TRIPLET.
get_nif_version() ->
erlang:system_info(nif_version).
get_expected_checksum(TarballFilename) ->
Map = checksum:checksum(),
case maps:is_key(TarballFilename, Map) of
true ->
AlgoAndChecksum = maps:get(TarballFilename, Map),
case string:split(AlgoAndChecksum, ":") of
[Algo, Checksum] ->
{Algo, Checksum};
_ ->
false
end;
false ->
false
end.
is_precompiled_binary_available() ->
case is_dev() of
{true, _} ->
false;
{false, AppVersion} ->
Target = get_target(),
NifVersion = get_nif_version(),
Name = lists:flatten(io_lib:fwrite(?PRECOMPILED_TARBALL_NAME, [NifVersion, Target, AppVersion])),
TarballFilename = lists:flatten(io_lib:fwrite("~s.tar.gz", [Name])),
case get_expected_checksum(TarballFilename) of
false ->
{error, lists:flatten(io_lib:fwrite("Cannot find checksum for ~s~n", [Name]))};
{Algo, Checksum} ->
TarballURL = lists:flatten(io_lib:fwrite(?PRECOMPILED_DOWNLOAD_URL, [AppVersion, TarballFilename])),
{true, Name, TarballFilename, TarballURL, Algo, Checksum}
end
end.
cache_opts() ->
case os:getenv("MIX_XDG") of
false ->
#{};
_ ->
#{os => linux}
end.
%% code from https://erlangforums.com/t/base-16-in-erlang/1468/3
base16_loop(Bin) when is_binary(Bin) ->
base16_loop(Bin, <<>>).
base16_loop(<<N:8/unit:4,Rest/bitstring>>, Acc) ->
Hex = integer_to_binary(N, 16),
PadLen = 8 - byte_size(Hex),
base16_loop(Rest, <<Acc/binary,
<<"00000000">>:PadLen/binary,
(integer_to_binary(N, 16))/binary>>);
base16_loop(<<N:1/unit:4,Rest/bitstring>>, Acc) ->
base16_loop(Rest, <<Acc/binary, (integer_to_binary(N, 16))/binary>>);
base16_loop(<<>>, Acc) ->
Acc.
compute_checksum(ChecksumAlgo, Filepath) ->
case file:read_file(Filepath) of
{ok, BinContent} ->
Hash = crypto:hash(list_to_atom(ChecksumAlgo), BinContent),
Checksum = string:to_lower(binary_to_list(base16_loop(Hash))),
{Filepath, ChecksumAlgo, Checksum};
_ ->
{Filepath, nil, nil}
end.
verify_cached_file(GetChecksumIfExists, ChecksumAlgo, CacheTo) ->
case GetChecksumIfExists and filelib:is_regular(CacheTo) of
true ->
compute_checksum(ChecksumAlgo, CacheTo);
false ->
{CacheTo, nil, nil}
end.
get_cached_path(Filename) ->
CacheBaseDir = filename:basedir(user_cache, "", cache_opts()),
CacheDir = maybe_override_by_env("ELIXIR_MAKE_CACHE_DIR", CacheBaseDir),
file:make_dir(CacheDir),
{CacheDir, filename:join([CacheDir, Filename])}.
cache_path(Filename, ChecksumAlgo, GetChecksumIfExists) ->
{CacheDir, FullPath} = get_cached_path(Filename),
case filelib:is_dir(CacheDir) of
true ->
verify_cached_file(GetChecksumIfExists, ChecksumAlgo, FullPath);
false ->
{FullPath, nil, nil}
end.
download_precompiled_binary(URL, CacheTo, ChecksumAlgo) ->
case do_download(URL) of
{ok, Body} ->
file:write_file(CacheTo, Body),
{FullPath, _, Checksum} = verify_cached_file(true, ChecksumAlgo, CacheTo),
io:fwrite("[INFO] Precompiled binary tarball downloaded and saved to ~s, ~s=~s~n", [FullPath, ChecksumAlgo, Checksum]),
{FullPath, ChecksumAlgo, Checksum};
{error, DownloadError} ->
io:fwrite("[ERROR] Cannot download precompiled binary from ~p: ~p~n", [URL, DownloadError]),
{CacheTo, nil, nil}
end.
download(URL, CacheFilename, ChecksumAlgo, ExpectedChecksum, Overwrite) ->
{CacheTo, Algo, CachedFileChecksum} = cache_path(CacheFilename, ChecksumAlgo, not Overwrite),
case CachedFileChecksum of
nil ->
io:fwrite("[INFO] not downloaded, will download!~n"),
download_precompiled_binary(URL, CacheTo, ChecksumAlgo);
_ ->
case ExpectedChecksum == CachedFileChecksum of
true ->
io:fwrite("[INFO] Precompiled binary tarball cached at ~s, checksum[~p]=~p\r\n", [CacheTo, Algo, CachedFileChecksum]),
{CacheTo, Algo, CachedFileChecksum};
false ->
io:fwrite("[ERROR] Checksum mismatched ~s[~s=~s], expected:[~p=~p]\r\n", [CacheTo, Algo, CachedFileChecksum, Algo, ExpectedChecksum]),
io:fwrite("[WARNING] Will delete cached tarball ~s and re-download", [CacheTo]),
file:delete(CacheTo),
download_precompiled_binary(URL, CacheTo, ChecksumAlgo)
end
end.
certificate_store() ->
PossibleLocations = [
%% Configured cacertfile
os:getenv("ELIXIR_MAKE_CACERT"),
%% Debian/Ubuntu/Gentoo etc.
"/etc/ssl/certs/ca-certificates.crt",
%% Fedora/RHEL 6
"/etc/pki/tls/certs/ca-bundle.crt",
%5 OpenSUSE
"/etc/ssl/ca-bundle.pem",
%% OpenELEC
"/etc/pki/tls/cacert.pem",
%% CentOS/RHEL 7
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
%% Open SSL on MacOS
"/usr/local/etc/openssl/cert.pem",
%% MacOS & Alpine Linux
"/etc/ssl/cert.pem"
],
CheckExistance = lists:map(fun (F) ->
{filelib:is_file(F), F}
end, PossibleLocations),
ExistingOnes = lists:dropwhile(fun ({X, _}) -> X == false end, CheckExistance),
case length(ExistingOnes) of
Len when Len > 0 ->
{_, Cert} = hd(ExistingOnes),
Cert;
_ ->
io:fwrite("[WARNING] Cannot find CA certificate store in default locations: ~p~n", [PossibleLocations]),
io:fwrite("You can set environment variable ELIXIR_MAKE_CACERT to the SSL cert on your system.~n"),
nil
end.
preferred_ciphers() ->
PreferredCiphers = [
%% Cipher suites (TLS 1.3): TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
#{cipher => aes_128_gcm, key_exchange => any, mac => aead, prf => sha256},
#{cipher => aes_256_gcm, key_exchange => any, mac => aead, prf => sha384},
#{cipher => chacha20_poly1305, key_exchange => any, mac => aead, prf => sha256},
%% Cipher suites (TLS 1.2): ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:
%% ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:
%% ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
#{cipher => aes_128_gcm, key_exchange => ecdhe_ecdsa, mac => aead, prf => sha256},
#{cipher => aes_128_gcm, key_exchange => ecdhe_rsa, mac => aead, prf => sha256},
#{cipher => aes_256_gcm, key_exchange => ecdh_ecdsa, mac => aead, prf => sha384},
#{cipher => aes_256_gcm, key_exchange => ecdh_rsa, mac => aead, prf => sha384},
#{cipher => chacha20_poly1305, key_exchange => ecdhe_ecdsa, mac => aead, prf => sha256},
#{cipher => chacha20_poly1305, key_exchange => ecdhe_rsa, mac => aead, prf => sha256},
#{cipher => aes_128_gcm, key_exchange => dhe_rsa, mac => aead, prf => sha256},
#{cipher => aes_256_gcm, key_exchange => dhe_rsa, mac => aead, prf => sha384}
],
ssl:filter_cipher_suites(PreferredCiphers, []).
protocol_versions() ->
case list_to_integer(erlang:system_info(otp_release)) of
Version when Version < 25 ->
['tlsv1.2'];
_ ->
['tlsv1.2', 'tlsv1.3']
end.
preferred_eccs() ->
%% TLS curves: X25519, prime256v1, secp384r1
PreferredECCS = [secp256r1, secp384r1],
ssl:eccs() -- ssl:eccs() -- PreferredECCS.
secure_ssl() ->
case os:getenv("ELIXIR_MAKE_UNSAFE_HTTPS") of
nil -> true;
"FALSE" -> false;
"false" -> false;
"nil" -> false;
"NIL" -> false;
_ -> true
end.
https_opts(Hostname) ->
CertFile = certificate_store(),
case {secure_ssl(), is_list(CertFile)} of
{true, true} ->
[
{
ssl, [
{verify, verify_peer},
{cacertfile, CertFile},
{depth, 4},
{ciphers, preferred_ciphers()},
{versions, protocol_versions()},
{eccs, preferred_eccs()},
{reuse_sessions, true},
{server_name_indication, Hostname},
{secure_renegotiate, true},
{customize_hostname_check, [
{match_fun, public_key:pkix_verify_hostname_match_fun(https)}
]}
]
}
];
_ ->
[
{
ssl, [
{verify, verify_none},
{ciphers, preferred_ciphers()},
{versions, protocol_versions()},
{reuse_sessions, true},
{server_name_indication, Hostname},
{secure_renegotiate, true}
]
}
]
end.
do_download(URL) ->
application:ensure_started(inets),
ssl:start(),
HttpOtps = https_opts("github.com"),
Request = {URL, []},
case httpc:request(get, Request, HttpOtps, [{body_format, binary}]) of
{ok, {{_, 200, _}, _, Body}} ->
{ok, Body};
{error, Reason} ->
{error, Reason};
Err ->
{error, lists:flatten(io_lib:fwrite("Cannot download file from ~s: ~p~n", [URL, Err]))}
end.
is_already_installed() ->
case string:find(get_target(), "windows-msvc") of
nomatch ->
filelib:is_regular(?EVISION_SO_FILE);
_ ->
filelib:is_regular(?EVISION_DLL_FILE)
end.
install_precompiled_binary_if_available() ->
case is_already_installed() of
false ->
case is_precompiled_binary_available() of
{true, Name, TarballFilename, TarballURL, ExpectedAlgo, ExpectedChecksum} ->
case download(TarballURL, TarballFilename, ExpectedAlgo, ExpectedChecksum, false) of
{_, _, nil} ->
exit(failed);
{TarballFileFullPath, _, ExpectedChecksum} ->
file:del_dir_r("tmp_priv"),
Status =
case erl_tar:extract(TarballFileFullPath, [compressed, {cwd, "tmp_priv"}]) of
ok ->
file:del_dir_r(?ERLANG_GENERATED_SOURCE_DIR),
file:del_dir_r("priv"),
TmpSrc = filename:join(["tmp_priv", Name, "erlang_generated"]),
TmpPriv = filename:join(["tmp_priv", Name, "priv"]),
io:fwrite("[INFO] Moving generated Erlang binding files: ~p => ~p~n", [TmpSrc, ?ERLANG_GENERATED_SOURCE_DIR]),
SrcRenameOk = file:rename(TmpSrc, ?ERLANG_GENERATED_SOURCE_DIR),
case SrcRenameOk of
{error, SrcError} ->
io:fwrite("[ERROR] Failed to move generated Erlang binding files: ~p~n", [SrcError]);
_ ->
ok
end,
io:fwrite("[INFO] Moving priv directory: ~p => ~p~n", [TmpSrc, "priv"]),
PrivRenameOk = file:rename(TmpPriv, "priv"),
case PrivRenameOk of
{error, PrivError} ->
io:fwrite("[ERROR] Failed to move priv directory: ~p~n", [PrivError]);
_ ->
ok
end,
case {SrcRenameOk, PrivRenameOk} of
{ok, ok} ->
ok;
_ ->
failed
end;
Error ->
io:fwrite("[ERROR] Failed to unarchive tarball file: ~s, error: ~p~n", [TarballFileFullPath, Error]),
failed
end,
file:del_dir_r("tmp_priv"),
case Status of
failed ->
exit(failed);
_ ->
ok
end
end;
What ->
io:fwrite("[INFO] Cannot find precompiled binary: ~p~n", [What]),
exit(failed)
end;
true ->
ok
end.