forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.zig
4050 lines (3540 loc) · 167 KB
/
http.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// const c = @import("./c.zig");
const std = @import("std");
const bun = @import("global.zig");
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const FeatureFlags = bun.FeatureFlags;
const stringZ = bun.stringZ;
const StoredFileDescriptorType = bun.StoredFileDescriptorType;
const default_allocator = bun.default_allocator;
const C = bun.C;
const Api = @import("./api/schema.zig").Api;
const ApiReader = @import("./api/schema.zig").Reader;
const ApiWriter = @import("./api/schema.zig").Writer;
const ByteApiWriter = @import("./api/schema.zig").ByteWriter;
const NewApiWriter = @import("./api/schema.zig").Writer;
const js_ast = @import("./js_ast.zig");
const bundler = @import("bundler.zig");
const logger = @import("logger.zig");
const Fs = @import("./fs.zig");
const Options = @import("./options.zig");
const Fallback = @import("./runtime.zig").Fallback;
const ErrorCSS = @import("./runtime.zig").ErrorCSS;
const ErrorJS = @import("./runtime.zig").ErrorJS;
const Runtime = @import("./runtime.zig").Runtime;
const Css = @import("css_scanner.zig");
const NodeModuleBundle = @import("./node_module_bundle.zig").NodeModuleBundle;
const resolve_path = @import("./resolver/resolve_path.zig");
const OutputFile = Options.OutputFile;
const DotEnv = @import("./env_loader.zig");
const mimalloc = @import("./allocators/mimalloc.zig");
const MacroMap = @import("./resolver/package_json.zig").MacroMap;
const Analytics = @import("./analytics/analytics_thread.zig");
const Arena = std.heap.ArenaAllocator;
const ThreadlocalArena = @import("./mimalloc_arena.zig").Arena;
const JSON = @import("./json_parser.zig");
const DateTime = @import("datetime");
const ThreadPool = @import("thread_pool");
const SourceMap = @import("./sourcemap/sourcemap.zig");
const ObjectPool = @import("./pool.zig").ObjectPool;
const Lock = @import("./lock.zig").Lock;
const RequestDataPool = ObjectPool([32_000]u8, null, false, 1);
const ResolveWatcher = @import("./resolver/resolver.zig").ResolveWatcher;
pub fn constStrToU8(s: string) []u8 {
return @intToPtr([*]u8, @ptrToInt(s.ptr))[0..s.len];
}
pub const MutableStringAPIWriter = NewApiWriter(*MutableString);
const tcp = std.x.net.tcp;
const ip = std.x.net.ip;
const IPv4 = std.x.os.IPv4;
const IPv6 = std.x.os.IPv6;
const Socket = std.x.os.Socket;
const os = std.os;
const picohttp = @import("picohttp");
const Header = picohttp.Header;
const Request = picohttp.Request;
const Response = picohttp.Response;
pub const Headers = picohttp.Headers;
pub const MimeType = @import("./http/mime_type.zig");
const Bundler = bundler.Bundler;
const Websocket = @import("./http/websocket.zig");
const JSPrinter = @import("./js_printer.zig");
const watcher = @import("./watcher.zig");
threadlocal var req_headers_buf: [100]picohttp.Header = undefined;
threadlocal var res_headers_buf: [100]picohttp.Header = undefined;
const sync = @import("./sync.zig");
const JavaScript = @import("javascript_core");
const JavaScriptCore = JavaScriptCore.C;
const Syscall = JavaScript.Node.Syscall;
const Router = @import("./router.zig");
pub const Watcher = watcher.NewWatcher(*Server);
const ZigURL = @import("./url.zig").URL;
const HTTPStatusCode = u10;
const URLPath = @import("./http/url_path.zig");
const Method = @import("./http/method.zig").Method;
const SOCKET_FLAGS: u32 = if (Environment.isLinux)
os.SOCK.CLOEXEC | os.MSG.NOSIGNAL
else
os.SOCK.CLOEXEC;
fn disableSIGPIPESoClosingTheTabDoesntCrash(conn: anytype) void {
if (comptime !Environment.isMac) return;
std.os.setsockopt(
conn.client.socket.fd,
std.os.SOL.SOCKET,
std.os.SO.NOSIGPIPE,
&std.mem.toBytes(@as(c_int, 1)),
) catch {};
}
var http_editor_context: EditorContext = EditorContext{};
pub const RequestContext = struct {
request: Request,
method: Method,
url: URLPath,
conn: *tcp.Connection,
allocator: std.mem.Allocator,
arena: ThreadlocalArena,
req_body_node: *RequestDataPool.Node = undefined,
log: logger.Log,
bundler: *Bundler,
keep_alive: bool = true,
status: ?HTTPStatusCode = null,
has_written_last_header: bool = false,
has_called_done: bool = false,
mime_type: MimeType = MimeType.other,
to_plain_text: bool = false,
controlled: bool = false,
watcher: *Watcher,
timer: std.time.Timer,
matched_route: ?Router.Match = null,
origin: ZigURL,
datetime_buf: [512]u8 = undefined,
full_url: [:0]const u8 = "",
res_headers_count: usize = 0,
/// --disable-bun.js propagates here
pub var fallback_only = false;
const default_favicon = @embedFile("favicon.png");
const default_favicon_shasum = "07877ad4cdfe472cc70759d1f237d358ae1f6a9b";
pub fn sendFavicon(ctx: *RequestContext) !void {
ctx.appendHeader("Content-Type", MimeType.byExtension("png").value);
ctx.appendHeader("ETag", default_favicon_shasum);
ctx.appendHeader("Age", "0");
ctx.appendHeader("Cache-Control", "public, max-age=3600");
if (ctx.header("If-None-Match")) |etag_header| {
if (strings.eqlLong(default_favicon_shasum, etag_header, true)) {
try ctx.sendNotModified();
return;
}
}
defer ctx.done();
try ctx.writeStatus(200);
try ctx.prepareToSendBody(default_favicon.len, false);
try ctx.writeBodyBuf(default_favicon);
}
fn parseOrigin(this: *RequestContext) void {
var protocol: ?string = null;
var host: ?string = null;
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
if (this.header("Forwarded")) |forwarded| {
if (strings.indexOf(forwarded, "host=")) |host_start| {
const host_i = host_start + "host=".len;
const host_ = forwarded[host_i..][0 .. strings.indexOfChar(forwarded[host_i..], ';') orelse forwarded[host_i..].len];
if (host_.len > 0) {
host = host_;
}
}
if (strings.indexOf(forwarded, "proto=")) |protocol_start| {
const protocol_i = protocol_start + "proto=".len;
if (strings.eqlComptime(forwarded[protocol_i..][0 .. strings.indexOfChar(forwarded[protocol_i..], ';') orelse forwarded[protocol_i..].len], "https")) {
protocol = "https";
} else {
protocol = "http";
}
}
}
if (protocol == null) {
determine_protocol: {
// Upgrade-Insecure-Requests doesn't work
// Browsers send this header to clients that are not running HTTPS
// We need to use protocol-relative URLs in import statements and in websocket handler, we need to send the absolute URL it received
// That will be our fix
// // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Upgrade-Insecure-Requests
// if (this.header("Upgrade-Insecure-Requests") != null) {
// protocol = "https";
// break :determine_protocol;
// }
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
if (this.header("X-Forwarded-Proto")) |proto| {
if (strings.eqlComptime(proto, "https")) {
protocol = "https";
break :determine_protocol;
}
}
// Microsoft IIS
if (this.header("Front-End-Https")) |proto| {
if (strings.eqlComptime(proto, "on")) {
protocol = "https";
break :determine_protocol;
}
}
}
}
if (host == null) {
determine_host: {
if (this.header("X-Forwarded-Host")) |_host| {
host = _host;
break :determine_host;
}
}
if (protocol == null) {
if (this.header("Origin")) |origin| {
this.origin = ZigURL.parse(origin);
return;
}
}
}
if (host != null or protocol != null) {
// Proxies like Caddy might only send X-Forwarded-Proto if the host matches
const display_protocol = protocol orelse @as(string, "http");
var display_host = host orelse
(if (protocol != null) this.header("Host") else null) orelse
@as(string, this.origin.host);
var display_port = if (this.origin.port.len > 0) this.origin.port else @as(string, "3000");
if (strings.indexOfChar(display_host, ':')) |colon| {
display_port = display_host[colon + 1 .. display_host.len];
display_host = display_host[0..colon];
} else if (this.bundler.options.origin.port_was_automatically_set and protocol != null) {
if (strings.eqlComptime(display_protocol, "https")) {
display_port = "443";
} else {
display_port = "80";
}
}
this.origin = ZigURL.parse(std.fmt.allocPrint(this.allocator, "{s}://{s}:{s}/", .{ display_protocol, display_host, display_port }) catch unreachable);
}
}
pub fn getFullURL(this: *RequestContext) [:0]const u8 {
if (this.full_url.len == 0) {
if (this.origin.isAbsolute()) {
this.full_url = std.fmt.allocPrintZ(this.allocator, "{s}{s}", .{ this.origin.origin, this.request.path }) catch unreachable;
} else {
this.full_url = this.allocator.dupeZ(u8, this.request.path) catch unreachable;
}
}
return this.full_url;
}
pub fn getFullURLForSourceMap(this: *RequestContext) [:0]const u8 {
if (this.full_url.len == 0) {
if (this.origin.isAbsolute()) {
this.full_url = std.fmt.allocPrintZ(this.allocator, "{s}{s}.map", .{ this.origin.origin, this.request.path }) catch unreachable;
} else {
this.full_url = std.fmt.allocPrintZ(this.allocator, "{s}.map", .{this.request.path}) catch unreachable;
}
}
return this.full_url;
}
pub fn handleRedirect(this: *RequestContext, url: string) !void {
this.appendHeader("Location", url);
defer this.done();
try this.writeStatus(302);
try this.flushHeaders();
}
pub fn header(ctx: *RequestContext, comptime name: anytype) ?[]const u8 {
return (ctx.headerEntry(name) orelse return null).value;
}
pub fn headerEntry(ctx: *RequestContext, comptime name: anytype) ?Header {
for (ctx.request.headers) |head| {
if (strings.eqlCaseInsensitiveASCII(head.name, name, true)) {
return head;
}
}
return null;
}
pub fn headerEntryFirst(ctx: *RequestContext, comptime name: []const string) ?Header {
for (ctx.request.headers) |head| {
inline for (name) |match| {
if (strings.eqlCaseInsensitiveASCII(head.name, match, true)) {
return head;
}
}
}
return null;
}
pub fn renderFallback(
this: *RequestContext,
allocator: std.mem.Allocator,
bundler_: *Bundler,
step: Api.FallbackStep,
log: *logger.Log,
err: anyerror,
exceptions: []Api.JsException,
comptime fmt: string,
args: anytype,
) !void {
var route_index: i32 = -1;
const routes: Api.StringMap = if (bundler_.router != null) brk: {
const router = &bundler_.router.?;
break :brk Api.StringMap{
.keys = router.getNames() catch unreachable,
.values = router.getPublicPaths() catch unreachable,
};
} else std.mem.zeroes(Api.StringMap);
var preload: string = "";
var params: Api.StringMap = std.mem.zeroes(Api.StringMap);
if (fallback_entry_point_created == false) {
defer fallback_entry_point_created = true;
defer bundler_.resetStore();
// You'd think: hey we're just importing a file
// Do we really need to run it through the transpiler and linking and printing?
// The answer, however, is yes.
// What if you're importing a fallback that's in node_modules?
try fallback_entry_point.generate(bundler_.options.framework.?.fallback.path, Bundler, bundler_);
const bundler_parse_options = Bundler.ParseOptions{
.allocator = default_allocator,
.path = fallback_entry_point.source.path,
.loader = .js,
.macro_remappings = .{},
.dirname_fd = 0,
.jsx = bundler_.options.jsx,
};
if (bundler_.parse(
bundler_parse_options,
@as(?*bundler.FallbackEntryPoint, &fallback_entry_point),
)) |*result| {
try bundler_.linker.linkAllowImportingFromBundle(
fallback_entry_point.source.path,
result,
this.origin,
.absolute_url,
false,
false,
false,
);
var buffer_writer = try JSPrinter.BufferWriter.init(default_allocator);
var writer = JSPrinter.BufferPrinter.init(buffer_writer);
_ = try bundler_.print(
result.*,
@TypeOf(&writer),
&writer,
.esm,
);
var slice = writer.ctx.buffer.toOwnedSliceLeaky();
fallback_entry_point.built_code = try default_allocator.dupe(u8, slice);
writer.ctx.buffer.deinit();
}
}
this.appendHeader("Content-Type", MimeType.html.value);
var link_stack_buf: [2048]u8 = undefined;
var remaining: []u8 = link_stack_buf[0..];
if (this.bundler.options.node_modules_bundle_url.len > 0) {
add_preload: {
const node_modules_preload_header_value = std.fmt.bufPrint(remaining, "<{s}>; rel=modulepreload", .{
this.bundler.options.node_modules_bundle_url,
}) catch break :add_preload;
this.appendHeader("Link", node_modules_preload_header_value);
remaining = remaining[node_modules_preload_header_value.len..];
}
}
if (this.matched_route) |match| {
if (match.params.len > 0) {
params.keys = match.params.items(.name);
params.values = match.params.items(.value);
}
if (this.bundler.router.?.routeIndexByHash(match.hash)) |ind| {
route_index = @intCast(i32, ind);
}
module_preload: {
if (strings.hasPrefix(match.file_path, Fs.FileSystem.instance.top_level_dir)) {
var stream = std.io.fixedBufferStream(remaining);
var writer = stream.writer();
writer.writeAll("<") catch break :module_preload;
writer.writeAll(std.mem.trimRight(u8, this.bundler.options.origin.href, "/")) catch break :module_preload;
writer.writeAll("/") catch break :module_preload;
if (this.bundler.options.routes.asset_prefix_path.len > 0) {
writer.writeAll(std.mem.trim(u8, this.bundler.options.routes.asset_prefix_path, "/")) catch break :module_preload;
}
// include that trailing slash
// this should never overflow because the directory will be "/" if it's a root
if (comptime Environment.isDebug) std.debug.assert(Fs.FileSystem.instance.top_level_dir.len > 0);
writer.writeAll(match.file_path[Fs.FileSystem.instance.top_level_dir.len - 1 ..]) catch break :module_preload;
writer.writeAll(">; rel=modulepreload") catch break :module_preload;
this.appendHeader(
"Link",
remaining[0..stream.pos],
);
remaining = remaining[stream.pos..];
}
}
}
var fallback_container = try allocator.create(Api.FallbackMessageContainer);
defer allocator.destroy(fallback_container);
fallback_container.* = Api.FallbackMessageContainer{
.message = try std.fmt.allocPrint(allocator, fmt, args),
.router = if (routes.keys.len > 0)
Api.Router{ .route = route_index, .params = params, .routes = routes }
else
null,
.reason = step,
.cwd = this.bundler.fs.top_level_dir,
.problems = Api.Problems{
.code = @truncate(u16, @errorToInt(err)),
.name = @errorName(err),
.exceptions = exceptions,
.build = try log.toAPI(allocator),
},
};
defer allocator.free(fallback_container.message.?);
defer this.done();
if (RequestContext.fallback_only) {
try this.writeStatus(200);
} else {
try this.writeStatus(500);
}
if (comptime fmt.len > 0) Output.prettyErrorln(fmt, args);
Output.flush();
var bb = std.ArrayList(u8).init(allocator);
defer bb.deinit();
var bb_writer = bb.writer();
try Fallback.render(
allocator,
fallback_container,
preload,
fallback_entry_point.built_code,
@TypeOf(bb_writer),
bb_writer,
);
try this.prepareToSendBody(bb.items.len, false);
try this.writeBodyBuf(bb.items);
}
fn matchPublicFolder(this: *RequestContext, comptime extensionless: bool) ?bundler.ServeResult {
if (!this.bundler.options.routes.static_dir_enabled) return null;
const relative_path = this.url.path;
var extension = this.url.extname;
var tmp_buildfile_buf = std.mem.span(&Bundler.tmp_buildfile_buf);
// On Windows, we don't keep the directory handle open forever because Windows doesn't like that.
const public_dir: std.fs.Dir = this.bundler.options.routes.static_dir_handle orelse std.fs.openDirAbsolute(this.bundler.options.routes.static_dir, .{}) catch |err| {
this.bundler.log.addErrorFmt(null, logger.Loc.Empty, this.allocator, "Opening public directory failed: {s}", .{@errorName(err)}) catch unreachable;
Output.printErrorln("Opening public directory failed: {s}", .{@errorName(err)});
this.bundler.options.routes.static_dir_enabled = false;
return null;
};
var relative_unrooted_path: []u8 = resolve_path.normalizeString(relative_path, false, .auto);
var _file: ?std.fs.File = null;
// Is it the index file?
if (relative_unrooted_path.len == 0) {
// std.mem.copy(u8, &tmp_buildfile_buf, relative_unrooted_path);
// std.mem.copy(u8, tmp_buildfile_buf[relative_unrooted_path.len..], "/"
// Search for /index.html
if (this.bundler.options.routes.single_page_app_routing and
this.bundler.options.routes.single_page_app_fd != 0)
{
this.sendSinglePageHTML() catch {};
return null;
} else if (public_dir.openFile("index.html", .{})) |file| {
var index_path = "index.html".*;
relative_unrooted_path = &(index_path);
_file = file;
extension = "html";
} else |_| {}
// Okay is it actually a full path?
} else if (extension.len > 0 and (!extensionless or strings.eqlComptime(extension, "html"))) {
if (public_dir.openFile(relative_unrooted_path, .{})) |file| {
_file = file;
} else |_| {}
}
// Try some weird stuff.
while (_file == null and relative_unrooted_path.len > 1) {
// When no extension is provided, it might be html
if (extension.len == 0) {
std.mem.copy(u8, tmp_buildfile_buf, relative_unrooted_path[0..relative_unrooted_path.len]);
std.mem.copy(u8, tmp_buildfile_buf[relative_unrooted_path.len..], ".html");
if (public_dir.openFile(tmp_buildfile_buf[0 .. relative_unrooted_path.len + ".html".len], .{})) |file| {
_file = file;
extension = "html";
break;
} else |_| {}
var _path: []u8 = undefined;
if (relative_unrooted_path[relative_unrooted_path.len - 1] == '/') {
std.mem.copy(u8, tmp_buildfile_buf, relative_unrooted_path[0 .. relative_unrooted_path.len - 1]);
std.mem.copy(u8, tmp_buildfile_buf[relative_unrooted_path.len - 1 ..], "/index.html");
_path = tmp_buildfile_buf[0 .. relative_unrooted_path.len - 1 + "/index.html".len];
} else {
std.mem.copy(u8, tmp_buildfile_buf, relative_unrooted_path[0..relative_unrooted_path.len]);
std.mem.copy(u8, tmp_buildfile_buf[relative_unrooted_path.len..], "/index.html");
_path = tmp_buildfile_buf[0 .. relative_unrooted_path.len + "/index.html".len];
}
if (extensionless and !strings.eqlComptime(std.fs.path.extension(_path), ".html")) {
break;
}
if (public_dir.openFile(_path, .{})) |file| {
const __path = _path;
relative_unrooted_path = __path;
extension = "html";
_file = file;
break;
} else |_| {}
}
break;
}
if (_file) |*file| {
var stat = file.stat() catch return null;
var absolute_path = resolve_path.joinAbs(this.bundler.options.routes.static_dir, .auto, relative_unrooted_path);
if (stat.kind == .SymLink) {
file.* = std.fs.openFileAbsolute(absolute_path, .{ .mode = .read_only }) catch return null;
absolute_path = std.os.getFdPath(
file.handle,
&Bundler.tmp_buildfile_buf,
) catch return null;
stat = file.stat() catch return null;
}
if (stat.kind != .File) {
file.close();
return null;
}
var output_file = OutputFile.initFile(file.*, absolute_path, stat.size);
output_file.value.copy.close_handle_on_complete = true;
output_file.value.copy.autowatch = false;
// if it wasn't a symlink, we never got the absolute path
// so it could still be missing a file extension
var ext = std.fs.path.extension(absolute_path);
if (ext.len > 0) ext = ext[1..];
// even if it was an absolute path, the file extension could just be a dot, like "foo."
if (ext.len == 0) ext = extension;
return bundler.ServeResult{
.file = output_file,
.mime_type = MimeType.byExtension(ext),
};
}
return null;
}
pub fn printStatusLine(comptime code: HTTPStatusCode) []const u8 {
const status_text = switch (code) {
101 => "ACTIVATING WEBSOCKET",
200 => "YAY",
201 => "NEW",
204 => "VERY CONTENT",
206 => "MUCH CONTENT",
304 => "NOT MODIFIED",
300...303, 305...399 => "REDIRECT",
404 => "Not Found",
403 => "Not Allowed!",
401 => "Login",
402 => "Pay Me",
400, 405...499 => "bad request :(",
500...599 => "ERR",
else => @compileError("Invalid code passed to printStatusLine"),
};
return std.fmt.comptimePrint("HTTP/1.1 {d} {s}\r\n", .{ code, status_text });
}
pub fn printStatusLineError(err: anyerror, buf: []u8) []const u8 {
return std.fmt.bufPrint(buf, "HTTP/1.1 500 {s}\r\n", .{@errorName(err)}) catch unreachable;
}
pub fn prepareToSendBody(
ctx: *RequestContext,
length: usize,
comptime chunked: bool,
) !void {
var content_length_header_buf: [64]u8 = undefined;
defer {
if (Environment.allow_assert) {
std.debug.assert(!ctx.has_written_last_header);
ctx.has_written_last_header = true;
}
}
if (chunked) {
ctx.appendHeader("Transfer-Encoding", "Chunked");
} else {
ctx.appendHeader("Content-Length", content_length_header_buf[0..std.fmt.formatIntBuf(&content_length_header_buf, length, 10, .upper, .{})]);
}
try ctx.flushHeaders();
}
pub fn clearHeaders(
this: *RequestContext,
) !void {
this.res_headers_count = 0;
}
pub fn appendHeaderSlow(this: *RequestContext, name: string, value: string) !void {
res_headers_buf[this.res_headers_count] = picohttp.Header{ .name = name, .value = value };
this.res_headers_count += 1;
}
threadlocal var resp_header_out_buf: [4096]u8 = undefined;
pub fn flushHeaders(ctx: *RequestContext) !void {
if (ctx.res_headers_count == 0) return;
const headers: []picohttp.Header = res_headers_buf[0..ctx.res_headers_count];
defer ctx.res_headers_count = 0;
var writer = std.io.fixedBufferStream(&resp_header_out_buf);
for (headers) |head| {
_ = writer.write(head.name) catch 0;
_ = writer.write(": ") catch 0;
_ = writer.write(head.value) catch 0;
_ = writer.write("\r\n") catch 0;
}
_ = writer.write("\r\n") catch 0;
_ = try ctx.writeSocket(writer.getWritten(), SOCKET_FLAGS);
}
const AsyncIO = @import("io");
pub fn writeSocket(ctx: *RequestContext, buf: anytype, _: anytype) !usize {
switch (Syscall.send(ctx.conn.client.socket.fd, buf, SOCKET_FLAGS)) {
.err => |err| {
const erro = AsyncIO.asError(err.getErrno());
if (erro == error.EBADF or erro == error.ECONNABORTED or erro == error.ECONNREFUSED) {
return error.SocketClosed;
}
Output.prettyErrorln("send() error: {s}", .{err.toSystemError().message.slice()});
return erro;
},
.result => |written| {
if (written == 0) {
return error.SocketClosed;
}
return written;
},
}
}
pub fn writeBodyBuf(ctx: *RequestContext, body: []const u8) !void {
_ = try ctx.writeSocket(body, SOCKET_FLAGS);
}
pub fn writeStatus(ctx: *RequestContext, comptime code: HTTPStatusCode) !void {
_ = try ctx.writeSocket(comptime printStatusLine(code), SOCKET_FLAGS);
ctx.status = code;
}
pub fn writeStatusError(ctx: *RequestContext, err: anyerror) !void {
var status_line_error_buf: [1024]u8 = undefined;
_ = try ctx.writeSocket(printStatusLineError(err, &status_line_error_buf), SOCKET_FLAGS);
ctx.status = @as(HTTPStatusCode, 500);
}
threadlocal var status_buf: [std.fmt.count("HTTP/1.1 {d} {s}\r\n", .{ 200, "OK" })]u8 = undefined;
pub fn writeStatusSlow(ctx: *RequestContext, code: u16) !void {
_ = try ctx.writeSocket(
try std.fmt.bufPrint(
&status_buf,
"HTTP/1.1 {d} {s}\r\n",
.{ code, if (code > 299) "HM" else "OK" },
),
SOCKET_FLAGS,
);
ctx.status = @truncate(HTTPStatusCode, code);
}
pub fn init(
this: *RequestContext,
req: Request,
arena: ThreadlocalArena,
conn: *tcp.Connection,
bundler_: *Bundler,
watcher_: *Watcher,
timer: std.time.Timer,
) !void {
this.* = RequestContext{
.request = req,
.arena = arena,
.bundler = bundler_,
.log = undefined,
.url = try URLPath.parse(req.path),
.conn = conn,
.allocator = arena.allocator(),
.method = Method.which(req.method) orelse return error.InvalidMethod,
.watcher = watcher_,
.timer = timer,
.origin = bundler_.options.origin,
};
}
// not all browsers send this
pub const BrowserNavigation = enum {
yes,
no,
maybe,
};
pub inline fn isBrowserNavigation(req: *RequestContext) BrowserNavigation {
if (req.header("Sec-Fetch-Mode")) |mode| {
return switch (strings.eqlComptime(mode, "navigate")) {
true => BrowserNavigation.yes,
false => BrowserNavigation.no,
};
}
return .maybe;
}
pub fn sendNotFound(req: *RequestContext) !void {
std.debug.assert(!req.has_called_done);
defer req.done();
try req.writeStatus(404);
try req.flushHeaders();
}
pub fn sendInternalError(ctx: *RequestContext, err: anytype) !void {
defer ctx.done();
try ctx.writeStatusError(err);
const printed = std.fmt.bufPrint(&error_buf, "error: {s}\nPlease see your terminal for more details", .{@errorName(err)}) catch |err2| brk: {
if (Environment.isDebug or Environment.isTest) {
Global.panic("error while printing error: {s}", .{@errorName(err2)});
}
break :brk "Internal error";
};
try ctx.prepareToSendBody(printed.len, false);
try ctx.writeBodyBuf(printed);
}
threadlocal var error_buf: [4096]u8 = undefined;
pub fn sendNotModified(ctx: *RequestContext) !void {
defer ctx.done();
try ctx.writeStatus(304);
try ctx.flushHeaders();
}
pub fn sendNoContent(ctx: *RequestContext) !void {
defer ctx.done();
try ctx.writeStatus(204);
try ctx.flushHeaders();
}
pub fn appendHeader(ctx: *RequestContext, comptime key: string, value: string) void {
if (comptime Environment.allow_assert) std.debug.assert(!ctx.has_written_last_header);
if (comptime Environment.allow_assert) std.debug.assert(ctx.res_headers_count < res_headers_buf.len);
res_headers_buf[ctx.res_headers_count] = Header{ .name = key, .value = value };
ctx.res_headers_count += 1;
}
const file_chunk_size = 16384;
const chunk_preamble_len: usize = brk: {
var buf: [64]u8 = undefined;
break :brk std.fmt.bufPrintIntToSlice(&buf, file_chunk_size, 16, true, .{}).len;
};
threadlocal var file_chunk_buf: [chunk_preamble_len + 2]u8 = undefined;
threadlocal var symlink_buffer: [bun.MAX_PATH_BYTES]u8 = undefined;
threadlocal var weak_etag_buffer: [100]u8 = undefined;
threadlocal var strong_etag_buffer: [100]u8 = undefined;
threadlocal var weak_etag_tmp_buffer: [100]u8 = undefined;
pub fn done(ctx: *RequestContext) void {
std.debug.assert(!ctx.has_called_done);
ctx.conn.deinit();
ctx.has_called_done = true;
}
pub fn sendBadRequest(ctx: *RequestContext) !void {
try ctx.writeStatus(400);
ctx.done();
}
pub fn sendJSB(ctx: *RequestContext) !void {
const node_modules_bundle = ctx.bundler.options.node_modules_bundle orelse unreachable;
if (ctx.header("Open-In-Editor") != null) {
if (http_editor_context.editor == null) {
http_editor_context.detectEditor(ctx.bundler.env);
}
if (http_editor_context.editor.? != .none) {
var buf: string = "";
if (node_modules_bundle.code_string == null) {
buf = try node_modules_bundle.readCodeAsStringSlow(bun.default_allocator);
} else {
buf = node_modules_bundle.code_string.?.str;
}
http_editor_context.openInEditor(
http_editor_context.editor.?,
buf,
std.fs.path.basename(ctx.url.path),
ctx.bundler.fs.tmpdir(),
ctx.header("Editor-Line") orelse "",
ctx.header("Editor-Column") orelse "",
);
if (http_editor_context.editor.? != .none) {
try ctx.sendNoContent();
return;
}
}
}
ctx.appendHeader("ETag", node_modules_bundle.bundle.etag);
ctx.appendHeader("Content-Type", "text/javascript");
ctx.appendHeader("Cache-Control", "immutable, max-age=99999");
if (ctx.header("If-None-Match")) |etag_header| {
if (strings.eqlLong(node_modules_bundle.bundle.etag, etag_header, true)) {
try ctx.sendNotModified();
return;
}
}
defer ctx.done();
const content_length = node_modules_bundle.container.code_length.? - node_modules_bundle.codeStartOffset();
try ctx.writeStatus(200);
try ctx.prepareToSendBody(content_length, false);
_ = try std.os.sendfile(
ctx.conn.client.socket.fd,
node_modules_bundle.fd,
node_modules_bundle.codeStartOffset(),
content_length,
&[_]std.os.iovec_const{},
&[_]std.os.iovec_const{},
0,
);
}
pub fn sendSinglePageHTML(ctx: *RequestContext) !void {
std.debug.assert(ctx.bundler.options.routes.single_page_app_fd > 0);
const file = std.fs.File{ .handle = ctx.bundler.options.routes.single_page_app_fd };
return try sendHTMLFile(ctx, file);
}
pub fn sendHTMLFile(ctx: *RequestContext, file: std.fs.File) !void {
ctx.appendHeader("Content-Type", MimeType.html.value);
ctx.appendHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
defer ctx.done();
const stats = file.stat() catch |err| {
Output.prettyErrorln("<r><red>Error {s}<r> reading index.html", .{@errorName(err)});
ctx.writeStatus(500) catch {};
return;
};
const content_length = stats.size;
try ctx.writeStatus(200);
try ctx.prepareToSendBody(content_length, false);
var remain = content_length;
while (remain > 0) {
const wrote = try std.os.sendfile(
ctx.conn.client.socket.fd,
ctx.bundler.options.routes.single_page_app_fd,
content_length - remain,
remain,
&[_]std.os.iovec_const{},
&[_]std.os.iovec_const{},
0,
);
if (wrote == 0) {
break;
}
remain -|= wrote;
}
}
pub const WatchBuilder = struct {
watcher: *Watcher,
bundler: *Bundler,
allocator: std.mem.Allocator,
printer: JSPrinter.BufferPrinter,
timer: std.time.Timer,
count: usize = 0,
origin: ZigURL,
pub const WatchBuildResult = struct {
value: Value,
id: u32,
timestamp: u32,
log: logger.Log,
bytes: []const u8 = "",
approximate_newline_count: usize = 0,
pub const Value = union(Tag) {
success: Api.WebsocketMessageBuildSuccess,
fail: Api.WebsocketMessageBuildFailure,
};
pub const Tag = enum {
success,
fail,
};
};
pub fn build(this: *WatchBuilder, id: u32, from_timestamp: u32, allocator: std.mem.Allocator) !WatchBuildResult {
defer this.count += 1;
this.printer.ctx.reset();
var log = logger.Log.init(allocator);
var watchlist_slice = this.watcher.watchlist.slice();
const index = std.mem.indexOfScalar(u32, watchlist_slice.items(.hash), id) orelse return error.MissingWatchID;
const file_path_str = watchlist_slice.items(.file_path)[index];
const fd = watchlist_slice.items(.fd)[index];
const loader = watchlist_slice.items(.loader)[index];
const macro_remappings = this.bundler.options.macro_remap;
const path = Fs.Path.init(file_path_str);
var old_log = this.bundler.log;
this.bundler.setLog(&log);
defer {
this.bundler.setLog(old_log);
}
switch (loader) {
.toml, .json, .ts, .tsx, .js, .jsx => {
// Since we already have:
// - The file descriptor
// - The path
// - The loader
// We can skip resolving. We will need special handling for renaming where basically we:
// - Update the watch item.
// - Clear directory cache
this.bundler.resetStore();
var parse_result = this.bundler.parse(
Bundler.ParseOptions{
.allocator = allocator,
.path = path,
.loader = loader,
.dirname_fd = 0,
.file_descriptor = fd,
.file_hash = id,
.macro_remappings = macro_remappings,