Skip to content

Instantly share code, notes, and snippets.

@bored-engineer
Created March 30, 2020 08:37
Show Gist options
  • Select an option

  • Save bored-engineer/ef577a3409c705cda1c499c1b7991685 to your computer and use it in GitHub Desktop.

Select an option

Save bored-engineer/ef577a3409c705cda1c499c1b7991685 to your computer and use it in GitHub Desktop.

Revisions

  1. bored-engineer created this gist Mar 30, 2020.
    75 changes: 75 additions & 0 deletions controlmaster_pid.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,75 @@
    package main

    import (
    "bytes"
    "encoding/binary"
    "io"
    "log"
    "net"
    "os"
    "time"
    )

    var helloHandshake = []byte{
    // Length
    0, 0, 0, 8,
    // MSG_HELLO
    0, 0, 0, 1,
    // Protocol Version
    0, 0, 0, 4,
    }

    var aliveCheck = []byte{
    // Length
    0, 0, 0, 8,
    // MUX_C_ALIVE_CHECK
    16, 0, 0, 4,
    // Request ID
    1, 2, 3, 4,
    }

    var aliveResponse = []byte{
    // Length
    0, 0, 0, 12,
    // MUX_S_ALIVE
    128, 0, 0, 5,
    // Request ID
    1, 2, 3, 4,
    // PID
    0, 0, 0, 0,
    }

    func main() {
    path := os.Args[1]
    conn, err := net.DialTimeout("unix", path, 3*time.Second)
    if err != nil {
    log.Fatalf("%s: failed to dial ControlMaster: %v", path, err)
    }
    defer conn.Close()
    // Hello handshake
    if _, err := conn.Write(helloHandshake); err != nil {
    log.Fatalf("%s: failed to write hello handshake: %v", path, err)
    }
    // Read the response to our handshake and ensure it is same version
    helloReply := make([]byte, len(helloHandshake))
    if _, err := io.ReadFull(conn, helloReply); err != nil {
    log.Fatalf("%s: failed to read handshake response: %v", path, err)
    }
    if !bytes.Equal(helloHandshake, helloReply) {
    log.Fatalf("%s: did not recieve expected handshake response", path)
    }
    // Send the alive check
    if _, err := conn.Write(aliveCheck); err != nil {
    log.Fatalf("%s: failed to write alive check: %v", path, err)
    }
    // Read the alive response
    aliveReply := make([]byte, len(aliveResponse))
    if _, err := io.ReadFull(conn, aliveReply); err != nil {
    log.Fatalf("%s: failed to read alive response: %v", path, err)
    }
    if !bytes.Equal(aliveResponse[:12], aliveReply[:12]) {
    log.Fatalf("%s: did not recieve expected alive response", path)
    }
    pid := binary.BigEndian.Uint32(aliveReply[12:16])
    log.Printf("PID: %d", pid)
    }