build.zig 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. const std = @import("std");
  2. const Builder = std.build.Builder;
  3. const Pkg = std.build.Pkg;
  4. pub fn build(b: *Builder) !void {
  5. const optional_ssl_backend = getSslBackend(b);
  6. const target = b.standardTargetOptions(.{});
  7. const mode = b.standardReleaseOptions();
  8. const exe = b.addExecutable("ziget", "ziget-cmdline.zig");
  9. exe.setTarget(target);
  10. exe.single_threaded = true;
  11. exe.setBuildMode(mode);
  12. exe.addPackage(
  13. if (optional_ssl_backend) |ssl_backend| try addSslBackend(exe, ssl_backend, ".")
  14. else Pkg { .name = "ssl", .path = .{ .path = "nossl/ssl.zig" } }
  15. );
  16. exe.install();
  17. const run_cmd = exe.run();
  18. run_cmd.step.dependOn(b.getInstallStep());
  19. const run_step = b.step("run", "Run the app");
  20. run_step.dependOn(&run_cmd.step);
  21. addTests(b, target, mode);
  22. }
  23. fn addTests(b: *Builder, target: std.zig.CrossTarget, mode: std.builtin.Mode) void {
  24. const test_exe = b.addExecutable("test", "test.zig");
  25. test_exe.setTarget(target);
  26. test_exe.setBuildMode(mode);
  27. const test_step = b.step("test", "Run all the 'Enabled' tests");
  28. inline for (ssl_backends) |field| {
  29. const enum_value = @field(SslBackend, field.name);
  30. const enabled_by_default =
  31. if (enum_value == .wolfssl) false
  32. else if (enum_value == .schannel and std.builtin.os.tag != .windows) false
  33. else true;
  34. addTest(test_step, test_exe, field.name, enabled_by_default);
  35. }
  36. addTest(test_step, test_exe, "nossl", true);
  37. }
  38. fn addTest(test_step: *std.build.Step, test_exe: *std.build.LibExeObjStep, comptime backend_name: []const u8, comptime enabled_by_default: bool) void {
  39. const b = test_exe.builder;
  40. const run_cmd = test_exe.run();
  41. run_cmd.addArg(backend_name);
  42. run_cmd.step.dependOn(b.getInstallStep());
  43. const enabled_prefix = if (enabled_by_default) "Enabled " else "Disabled";
  44. const test_backend_step = b.step("test-" ++ backend_name,
  45. enabled_prefix ++ ": test ziget with the '" ++ backend_name ++ "' ssl backend");
  46. test_backend_step.dependOn(&run_cmd.step);
  47. if (enabled_by_default) {
  48. test_step.dependOn(&run_cmd.step);
  49. }
  50. }
  51. pub fn unwrapOptionalBool(optionalBool: ?bool) bool {
  52. if (optionalBool) |b| return b;
  53. return false;
  54. }
  55. pub const SslBackend = enum {
  56. openssl,
  57. opensslstatic,
  58. wolfssl,
  59. iguana,
  60. schannel,
  61. };
  62. pub const ssl_backends = @typeInfo(SslBackend).Enum.fields;
  63. pub fn getSslBackend(b: *Builder) ?SslBackend {
  64. var backend: ?SslBackend = null;
  65. var backend_infos : [ssl_backends.len]struct {
  66. enabled: bool,
  67. name: []const u8,
  68. } = undefined;
  69. var backend_enabled_count: u32 = 0;
  70. inline for (ssl_backends) |field, i| {
  71. const enabled = unwrapOptionalBool(b.option(bool, field.name, "enable ssl backend: " ++ field.name));
  72. if (enabled) {
  73. backend = @field(SslBackend, field.name);
  74. backend_enabled_count += 1;
  75. }
  76. backend_infos[i] = .{
  77. .enabled = enabled,
  78. .name = field.name,
  79. };
  80. }
  81. if (backend_enabled_count > 1) {
  82. std.log.err("only one ssl backend may be enabled, can't provide these options at the same time:", .{});
  83. for (backend_infos) |info| {
  84. if (info.enabled) {
  85. std.log.err(" -D{s}", .{info.name});
  86. }
  87. }
  88. std.os.exit(1);
  89. }
  90. return backend;
  91. }
  92. //
  93. // NOTE: the ziget_repo argument is here so this function can be used by other projects, not just this repo
  94. //
  95. pub fn addSslBackend(step: *std.build.LibExeObjStep, backend: SslBackend, ziget_repo: []const u8) !Pkg {
  96. const b = step.builder;
  97. switch (backend) {
  98. .openssl => {
  99. step.linkSystemLibrary("c");
  100. if (std.builtin.os.tag == .windows) {
  101. step.linkSystemLibrary("libcrypto");
  102. step.linkSystemLibrary("libssl");
  103. try setupOpensslWindows(step);
  104. } else {
  105. step.linkSystemLibrary("crypto");
  106. step.linkSystemLibrary("ssl");
  107. }
  108. return Pkg {
  109. .name = "ssl",
  110. .path = .{ .path = try std.fs.path.join(b.allocator, &[_][]const u8 { ziget_repo, "openssl/ssl.zig" }) },
  111. };
  112. },
  113. .opensslstatic => {
  114. const openssl_repo = try (GitRepo {
  115. .url = "https://github.com/openssl/openssl",
  116. .branch = "OpenSSL_1_1_1j",
  117. .sha = "52c587d60be67c337364b830dd3fdc15404a2f04",
  118. }).resolve(b.allocator);
  119. // TODO: should we implement something to cache the configuration?
  120. // can the configure output be in a different directory?
  121. {
  122. const configure_openssl = std.build.RunStep.create(b, "configure openssl");
  123. configure_openssl.cwd = openssl_repo;
  124. configure_openssl.addArgs(&[_][]const u8 {
  125. "./config",
  126. // just a temporary path for now
  127. //"--openssl",
  128. //"/tmp/ziget-openssl-static-dir1",
  129. "-static",
  130. // just disable everything for now
  131. "no-threads",
  132. "no-shared",
  133. "no-asm",
  134. "no-sse2",
  135. "no-aria",
  136. "no-bf",
  137. "no-camellia",
  138. "no-cast",
  139. "no-des",
  140. "no-dh",
  141. "no-dsa",
  142. "no-ec",
  143. "no-idea",
  144. "no-md2",
  145. "no-mdc2",
  146. "no-rc2",
  147. "no-rc4",
  148. "no-rc5",
  149. "no-seed",
  150. "no-sm2",
  151. "no-sm3",
  152. "no-sm4",
  153. });
  154. configure_openssl.stdout_action = .{
  155. .expect_matches = &[_][]const u8 { "OpenSSL has been successfully configured" },
  156. };
  157. const make_openssl = std.build.RunStep.create(b, "configure openssl");
  158. make_openssl.cwd = openssl_repo;
  159. make_openssl.addArgs(&[_][]const u8 {
  160. "make",
  161. "include/openssl/opensslconf.h",
  162. "include/crypto/bn_conf.h",
  163. "include/crypto/dso_conf.h",
  164. });
  165. make_openssl.step.dependOn(&configure_openssl.step);
  166. step.step.dependOn(&make_openssl.step);
  167. }
  168. step.addIncludeDir(openssl_repo);
  169. step.addIncludeDir(try std.fs.path.join(b.allocator, &[_][]const u8 { openssl_repo, "include" }));
  170. step.addIncludeDir(try std.fs.path.join(b.allocator, &[_][]const u8 { openssl_repo, "crypto", "modes" }));
  171. const cflags = &[_][]const u8 {
  172. "-Wall",
  173. // TODO: is this the right way to do this? is it a config option?
  174. "-DOPENSSL_NO_ENGINE",
  175. // TODO: --openssldir doesn't seem to be setting this?
  176. "-DOPENSSLDIR=\"/tmp/ziget-openssl-static-dir2\"",
  177. };
  178. {
  179. const sources = @embedFile("openssl/sources");
  180. var source_lines = std.mem.split(u8, sources, "\n");
  181. while (source_lines.next()) |src| {
  182. if (src.len == 0 or src[0] == '#') continue;
  183. step.addCSourceFile(try std.fs.path.join(b.allocator, &[_][]const u8 { openssl_repo, src }), cflags);
  184. }
  185. }
  186. step.linkLibC();
  187. return Pkg {
  188. .name = "ssl",
  189. .path = .{ .path = try std.fs.path.join(b.allocator, &[_][]const u8 { ziget_repo, "openssl/ssl.zig" }) },
  190. };
  191. },
  192. .wolfssl => {
  193. std.log.err("-Dwolfssl is not implemented", .{});
  194. std.os.exit(1);
  195. },
  196. .iguana => {
  197. const iguana_index_file = try (GitRepo {
  198. .url = "https://github.com/alexnask/iguanaTLS",
  199. .branch = null,
  200. .sha = @embedFile("iguanasha"),
  201. }).resolveOneFile(b.allocator, "src" ++ std.fs.path.sep_str ++ "main.zig");
  202. var p = Pkg {
  203. .name = "ssl",
  204. .path = .{ .path = try std.fs.path.join(b.allocator, &[_][]const u8 { ziget_repo, "iguana", "ssl.zig" }) },
  205. .dependencies = &[_]Pkg {
  206. .{ .name = "iguana", .path = .{ .path = iguana_index_file } },
  207. },
  208. };
  209. // NOTE: I don't know why I need to call dupePkg, I think this is a bug
  210. return b.dupePkg(p);
  211. },
  212. .schannel => {
  213. {
  214. // NOTE: for now I'm using msspi from https://github.com/deemru/msspi
  215. // I'll probably port this to Zig at some point
  216. // Once I do remove this build config
  217. // NOTE: I tested using this commit: 7338760a4a2c6fb80c47b24a2abba32d5fc40635 tagged at version 0.1.42
  218. const msspi_repo = try (GitRepo {
  219. .url = "https://github.com/deemru/msspi",
  220. .branch = "0.1.42",
  221. .sha = "7338760a4a2c6fb80c47b24a2abba32d5fc40635"
  222. }).resolve(b.allocator);
  223. const msspi_src_dir = try std.fs.path.join(b.allocator, &[_][]const u8 { msspi_repo, "src" });
  224. const msspi_main_cpp = try std.fs.path.join(b.allocator, &[_][]const u8 { msspi_src_dir, "msspi.cpp" });
  225. const msspi_third_party_include = try std.fs.path.join(b.allocator, &[_][]const u8 { msspi_repo, "third_party", "cprocsp", "include" });
  226. step.addCSourceFile(msspi_main_cpp, &[_][]const u8 { });
  227. step.addIncludeDir(msspi_src_dir);
  228. step.addIncludeDir(msspi_third_party_include);
  229. step.linkLibC();
  230. step.linkSystemLibrary("ws2_32");
  231. step.linkSystemLibrary("crypt32");
  232. step.linkSystemLibrary("advapi32");
  233. }
  234. // TODO: this will be needed if/when msspi is ported to Zig
  235. //const zigwin32_index_file = try getGitRepoFile(b.allocator,
  236. // "https://github.com/marlersoft/zigwin32",
  237. // "src" ++ std.fs.path.sep_str ++ "win32.zig");
  238. return Pkg {
  239. .name = "ssl",
  240. .path = .{ .path = try std.fs.path.join(b.allocator, &[_][]const u8 { ziget_repo, "schannel", "ssl.zig" }) },
  241. //.dependencies = &[_]Pkg {
  242. // .{ .name = "win32", .path = .{ .path = zigwin32_index_file } },
  243. //},
  244. };
  245. }
  246. }
  247. }
  248. pub fn setupOpensslWindows(step: *std.build.LibExeObjStep) !void {
  249. const b = step.builder;
  250. const openssl_path = b.option([]const u8, "openssl-path", "path to openssl (for Windows)") orelse {
  251. std.debug.print("Error: -Dopenssl on windows requires -Dopenssl-path=DIR to be specified\n", .{});
  252. std.os.exit(1);
  253. };
  254. // NOTE: right now these files are hardcoded to the files expected when installing SSL via
  255. // this web page: https://slproweb.com/products/Win32OpenSSL.html and installed using
  256. // this exe installer: https://slproweb.com/download/Win64OpenSSL-1_1_1g.exe
  257. step.addIncludeDir(try std.fs.path.join(b.allocator, &[_][]const u8 {openssl_path, "include"}));
  258. step.addLibPath(try std.fs.path.join(b.allocator, &[_][]const u8 {openssl_path, "lib"}));
  259. // install dlls to the same directory as executable
  260. for ([_][]const u8 {"libcrypto-1_1-x64.dll", "libssl-1_1-x64.dll"}) |dll| {
  261. step.step.dependOn(
  262. &b.addInstallFileWithDir(
  263. .{ .path = try std.fs.path.join(b.allocator, &[_][]const u8 {openssl_path, dll}) },
  264. .bin,
  265. dll,
  266. ).step
  267. );
  268. }
  269. }
  270. pub const GitRepo = struct {
  271. url: []const u8,
  272. branch: ?[]const u8,
  273. sha: []const u8,
  274. path: ?[]const u8 = null,
  275. pub fn defaultReposDir(allocator: *std.mem.Allocator) ![]const u8 {
  276. const cwd = try std.process.getCwdAlloc(allocator);
  277. defer allocator.free(cwd);
  278. return try std.fs.path.join(allocator, &[_][]const u8 { cwd, "dep" });
  279. }
  280. pub fn resolve(self: GitRepo, allocator: *std.mem.Allocator) ![]const u8 {
  281. var optional_repos_dir_to_clean: ?[]const u8 = null;
  282. defer {
  283. if (optional_repos_dir_to_clean) |p| {
  284. allocator.free(p);
  285. }
  286. }
  287. const path = if (self.path) |p| try allocator.dupe(u8, p) else blk: {
  288. const repos_dir = try defaultReposDir(allocator);
  289. optional_repos_dir_to_clean = repos_dir;
  290. break :blk try std.fs.path.join(allocator, &[_][]const u8{ repos_dir, std.fs.path.basename(self.url) });
  291. };
  292. errdefer allocator.free(path);
  293. std.fs.accessAbsolute(path, std.fs.File.OpenFlags { .read = true }) catch {
  294. std.debug.print("Error: repository '{s}' does not exist\n", .{path});
  295. std.debug.print(" Run the following to clone it:\n", .{});
  296. const branch_args = if (self.branch) |b| &[2][]const u8 {" -b ", b} else &[2][]const u8 {"", ""};
  297. std.debug.print(" git clone {s}{s}{s} {s} && git -C {3s} checkout {s} -b for_ziget\n",
  298. .{self.url, branch_args[0], branch_args[1], path, self.sha});
  299. std.os.exit(1);
  300. };
  301. // TODO: check if the SHA matches an print a message and/or warning if it is different
  302. return path;
  303. }
  304. pub fn resolveOneFile(self: GitRepo, allocator: *std.mem.Allocator, index_sub_path: []const u8) ![]const u8 {
  305. const repo_path = try self.resolve(allocator);
  306. defer allocator.free(repo_path);
  307. return try std.fs.path.join(allocator, &[_][]const u8 { repo_path, index_sub_path });
  308. }
  309. };