about summary refs log tree commit diff stats
path: root/src/ips/forkserver.nim
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2023-09-14 00:58:33 +0200
committerbptato <nincsnevem662@gmail.com>2023-09-14 00:58:33 +0200
commitc2004e4aba182473e79100759a2d58e1bd7d184c (patch)
tree1c3ebe2ee06471053656e7ee7da1fb27a576c691 /src/ips/forkserver.nim
parentf4a169ebca315246dd547efce181668d83c73d0b (diff)
downloadchawan-c2004e4aba182473e79100759a2d58e1bd7d184c.tar.gz
Switch buffer -> client connection to client -> buffer
We now connect to buffers from the client, instead of connecting
buffers to the client. This has the following advantages:

* Simplifies the client event loop.
* Makes the client a real client (no more serversocket dependency).
* Slightly more secure, as we no longer have to trust buffers not
  lying about their process ids.
* Facilitates the potential future addition of connections from
  several clients to a single buffer.
Diffstat (limited to 'src/ips/forkserver.nim')
-rw-r--r--src/ips/forkserver.nim14
1 files changed, 13 insertions, 1 deletions
diff --git a/src/ips/forkserver.nim b/src/ips/forkserver.nim
index 681b3aa5..cc2d91e0 100644
--- a/src/ips/forkserver.nim
+++ b/src/ips/forkserver.nim
@@ -120,6 +120,9 @@ proc forkBuffer(ctx: var ForkServerContext): Pid =
       proxy: config.proxy,
     )
   )
+  var pipefd: array[2, cint]
+  if pipe(pipefd) == -1:
+    raise newException(Defect, "Failed to open pipe.")
   let pid = fork()
   if pid == -1:
     raise newException(Defect, "Failed to fork process.")
@@ -129,11 +132,16 @@ proc forkBuffer(ctx: var ForkServerContext): Pid =
     for i in 0 ..< ctx.children.len: ctx.children[i] = (Pid(0), Pid(0))
     ctx.children.setLen(0)
     zeroMem(addr ctx, sizeof(ctx))
+    discard close(pipefd[0]) # close read
+    let ssock = initServerSocket(buffered = false)
+    let ps = newPosixStream(pipefd[1])
+    ps.write(char(0))
+    ps.close()
     discard close(stdin.getFileHandle())
     discard close(stdout.getFileHandle())
     let loader = FileLoader(process: loaderPid)
     try:
-      launchBuffer(config, source, attrs, loader, mainproc)
+      launchBuffer(config, source, attrs, loader, ssock)
     except CatchableError:
       let e = getCurrentException()
       # taken from system/excpt.nim
@@ -142,6 +150,10 @@ proc forkBuffer(ctx: var ForkServerContext): Pid =
       stderr.write(msg)
       quit(1)
     doAssert false
+  discard close(pipefd[1]) # close write
+  let ps = newPosixStream(pipefd[0])
+  assert ps.readChar() == char(0)
+  ps.close()
   ctx.children.add((pid, loaderPid))
   return pid