-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.zig
More file actions
359 lines (305 loc) · 10.8 KB
/
main.zig
File metadata and controls
359 lines (305 loc) · 10.8 KB
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
const std = @import("std");
const net = std.net;
const posix = std.posix;
const mem = std.mem;
const ArgError = error{
MissingMap,
UnknownArgument,
MissingValue,
InvalidMap,
InvalidPort,
};
const ListenerConfig = struct {
socket_path: []const u8,
host: []const u8,
port: u16,
};
const Config = struct {
mappings: []ListenerConfig,
};
fn printUsage() void {
std.debug.print(
\\Usage:
\\ socketcp --map /path/to.sock=HOST:PORT [--map /other.sock=HOST:PORT ...]
\\
\\Examples:
\\ socketcp --map /var/run/docker.sock=0.0.0.0:8080
\\ socketcp \\
\\ --map /var/run/docker.sock=0.0.0.0:8080 \\
\\ --map /var/run/docker2.sock=0.0.0.0:8081
\\
\\Options:
\\ --map <unix_path>=<host:port> Add a Unix<->TCP mapping
\\ -h, --help Show this help
\\
,
.{},
);
}
fn printBanner() void {
std.debug.print(
\\
\\███████╗ ██████╗ ██████╗██╗ ██╗███████╗████████╗ ██████╗██████╗
\\██╔════╝██╔═══██╗██╔════╝██║ ██╔╝██╔════╝╚══██╔══╝██╔════╝██╔══██╗
\\███████╗██║ ██║██║ █████╔╝ █████╗ ██║ ██║ ██████╔╝
\\╚════██║██║ ██║██║ ██╔═██╗ ██╔══╝ ██║ ██║ ██╔═══╝
\\███████║╚██████╔╝╚██████╗██║ ██╗███████╗ ██║ ╚██████╗██║
\\╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝╚═╝
\\
\\socketcp - Ultra-fast Unix Socket → TCP Proxy
\\
\\
,
.{},
);
}
fn parseHostPort(allocator: mem.Allocator, input: []const u8) !struct {
host: []const u8,
port: u16,
} {
const idx_opt = mem.lastIndexOfScalar(u8, input, ':') orelse {
std.debug.print("Invalid host:port (missing colon): {s}\n", .{input});
return ArgError.InvalidMap;
};
const host_part = input[0..idx_opt];
const port_str = input[idx_opt + 1 ..];
if (host_part.len == 0 or port_str.len == 0) {
std.debug.print("Invalid host:port: {s}\n", .{input});
return ArgError.InvalidMap;
}
const host = try allocator.dupe(u8, host_part);
const port = std.fmt.parseUnsigned(u16, port_str, 10) catch |err| {
std.debug.print("Invalid port in host:port '{s}': {s}\n", .{ input, @errorName(err) });
return ArgError.InvalidPort;
};
if (port == 0) return ArgError.InvalidPort;
return .{
.host = host,
.port = port,
};
}
fn parseArgs(allocator: mem.Allocator) !Config {
var args = try std.process.argsWithAllocator(allocator);
defer args.deinit();
// Skip program name.
_ = args.next() orelse return ArgError.MissingMap;
var mappings_list = std.ArrayListUnmanaged(ListenerConfig){};
while (args.next()) |arg| {
if (mem.eql(u8, arg, "--map")) {
const spec = args.next() orelse return ArgError.MissingValue;
const eq_idx = mem.indexOfScalar(u8, spec, '=') orelse {
std.debug.print("Invalid --map spec (missing '='): {s}\n", .{spec});
return ArgError.InvalidMap;
};
const socket_path_slice = spec[0..eq_idx];
const host_port_slice = spec[eq_idx + 1 ..];
if (socket_path_slice.len == 0 or host_port_slice.len == 0) {
std.debug.print("Invalid --map spec: {s}\n", .{spec});
return ArgError.InvalidMap;
}
const socket_path = try allocator.dupe(u8, socket_path_slice);
const parsed = try parseHostPort(allocator, host_port_slice);
try mappings_list.append(allocator, .{
.socket_path = socket_path,
.host = parsed.host,
.port = parsed.port,
});
} else if (mem.eql(u8, arg, "--help") or mem.eql(u8, arg, "-h")) {
printUsage();
std.process.exit(0);
} else {
std.debug.print("Unknown argument: {s}\n", .{arg});
return ArgError.UnknownArgument;
}
}
if (mappings_list.items.len == 0) {
std.debug.print("At least one --map is required\n", .{});
return ArgError.MissingMap;
}
const mappings_slice = try mappings_list.toOwnedSlice(allocator);
return Config{
.mappings = mappings_slice,
};
}
/// Write entire buffer to fd, handling short writes.
fn writeAll(fd: posix.fd_t, data: []const u8) !void {
var offset: usize = 0;
while (offset < data.len) {
const wrote = try posix.write(fd, data[offset..]);
if (wrote == 0) return error.UnexpectedWriteZero;
offset += wrote;
}
}
/// Bi-directional copy between two fds until one side closes.
///
/// fd_a <-> fd_b
fn pumpDuplex(fd_a: posix.fd_t, fd_b: posix.fd_t) !void {
var fds = [_]posix.pollfd{
.{ .fd = fd_a, .events = posix.POLL.IN, .revents = 0 },
.{ .fd = fd_b, .events = posix.POLL.IN, .revents = 0 },
};
var buf: [4096]u8 = undefined;
while (true) {
for (&fds) |*p| p.revents = 0;
const n_ready = try posix.poll(&fds, -1);
if (n_ready == 0) continue;
// a -> b
if (fds[0].revents & posix.POLL.IN == posix.POLL.IN) {
const n = try posix.read(fd_a, &buf);
if (n == 0) break; // EOF
try writeAll(fd_b, buf[0..n]);
} else if (fds[0].revents & (posix.POLL.ERR | posix.POLL.HUP) != 0) {
break;
}
// b -> a
if (fds[1].revents & posix.POLL.IN == posix.POLL.IN) {
const n2 = try posix.read(fd_b, &buf);
if (n2 == 0) break; // EOF
try writeAll(fd_a, buf[0..n2]);
} else if (fds[1].revents & (posix.POLL.ERR | posix.POLL.HUP) != 0) {
break;
}
}
}
const ListenerContext = struct {
allocator: mem.Allocator,
config: ListenerConfig,
};
const ConnContext = struct {
allocator: mem.Allocator,
socket_path: []const u8,
host: []const u8,
port: u16,
stream: net.Stream, // TCP side
};
fn connectionThreadMain(ctx: *ConnContext) void {
std.debug.print(
"[{s}:{d}] Connection start\n",
.{ ctx.host, ctx.port },
);
// Always clean up on exit.
defer {
ctx.stream.close();
std.debug.print(
"[{s}:{d}] Connection closed\n",
.{ ctx.host, ctx.port },
);
ctx.allocator.destroy(ctx);
}
var unix_stream = net.connectUnixSocket(ctx.socket_path) catch |err| {
std.debug.print(
"[{s}:{d}] Failed to connect Unix socket {s}: {s}\n",
.{ ctx.host, ctx.port, ctx.socket_path, @errorName(err) },
);
return;
};
defer unix_stream.close();
const tcp_fd: posix.fd_t = ctx.stream.handle;
const unix_fd: posix.fd_t = unix_stream.handle;
pumpDuplex(tcp_fd, unix_fd) catch |err| {
std.debug.print(
"[{s}:{d}] Pump error: {s}\n",
.{ ctx.host, ctx.port, @errorName(err) },
);
};
}
fn spawnConnectionHandler(
allocator: mem.Allocator,
mapping: ListenerConfig,
tcp_stream: net.Stream,
) !void {
const ctx = try allocator.create(ConnContext);
ctx.* = ConnContext{
.allocator = allocator,
.socket_path = mapping.socket_path,
.host = mapping.host,
.port = mapping.port,
.stream = tcp_stream,
};
var thread = try std.Thread.spawn(.{}, connectionThreadMain, .{ctx});
thread.detach();
}
fn listenerThreadMain(ctx: *ListenerContext) void {
defer {
ctx.allocator.destroy(ctx);
}
const address = net.Address.parseIp(ctx.config.host, ctx.config.port) catch |err| {
std.debug.print(
"Failed to parse address {s}:{d}: {s}\n",
.{ ctx.config.host, ctx.config.port, @errorName(err) },
);
return;
};
var server = address.listen(.{ .reuse_address = true }) catch |err| {
std.debug.print(
"Failed to listen on {s}:{d}: {s}\n",
.{ ctx.config.host, ctx.config.port, @errorName(err) },
);
return;
};
defer server.deinit();
std.debug.print(
"Listening on {s}:{d}, forwarding to Unix socket {s}\n",
.{ ctx.config.host, ctx.config.port, ctx.config.socket_path },
);
while (true) {
const conn = server.accept() catch |err| {
std.debug.print(
"Accept error on {s}:{d}: {s}\n",
.{ ctx.config.host, ctx.config.port, @errorName(err) },
);
continue;
};
const stream = conn.stream;
spawnConnectionHandler(ctx.allocator, ctx.config, stream) catch |err| {
std.debug.print(
"Failed to spawn handler on {s}:{d}: {s}\n",
.{ ctx.config.host, ctx.config.port, @errorName(err) },
);
stream.close();
};
}
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
_ = gpa.deinit();
}
const allocator = gpa.allocator();
const cfg = parseArgs(allocator) catch |err| {
switch (err) {
error.MissingMap,
error.UnknownArgument,
error.MissingValue,
error.InvalidMap,
error.InvalidPort,
=> {
printUsage();
return;
},
else => {
std.debug.print("Fatal error parsing args: {s}\n", .{@errorName(err)});
return;
},
}
};
// Print banner once args are valid
printBanner();
// One listener thread per mapping; then join (they never exit, so this keeps main alive).
var threads = try allocator.alloc(std.Thread, cfg.mappings.len);
var i: usize = 0;
while (i < cfg.mappings.len) : (i += 1) {
const mapping = cfg.mappings[i];
const ctx = try allocator.create(ListenerContext);
ctx.* = ListenerContext{
.allocator = allocator,
.config = mapping,
};
threads[i] = try std.Thread.spawn(.{}, listenerThreadMain, .{ctx});
}
std.debug.print("Started {d} listener(s)\n", .{cfg.mappings.len});
// Block forever (join on listeners; first one will never return in normal operation).
for (threads) |*t| {
t.join();
}
}