Skip to content

Commit d0214ae

Browse files
NZSmartieReto Zingg
authored andcommitted
Use bufio for reading libassuan files (see jstarks#2)
1 parent dd28ff1 commit d0214ae

File tree

1 file changed

+21
-20
lines changed

1 file changed

+21
-20
lines changed

npiperelay.go

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
package main
22

33
import (
4+
"bufio"
45
"errors"
56
"flag"
67
"io"
78
"log"
89
"os"
910
"strconv"
10-
"strings"
1111
"sync"
1212
"syscall"
1313
"time"
@@ -28,6 +28,7 @@ var (
2828
closeOnEOF = flag.Bool("ep", false, "terminate on EOF reading from the pipe, even if there is more data to write")
2929
closeOnStdinEOF = flag.Bool("ei", false, "terminate on EOF reading from stdin, even if there is more data to write")
3030
verbose = flag.Bool("v", false, "verbose output on stderr")
31+
assuan = flag.Bool("a", false, "treat the target as a libassuan file socket (Used by GnuPG)")
3132
)
3233

3334
func dialPipe(p string, poll bool) (*overlappedFile, error) {
@@ -113,37 +114,37 @@ func main() {
113114
log.Fatalln(err)
114115
}
115116

116-
// Not a named pipe, so attempt to read contents and connect to a TCP port for LibAssaaun
117-
if !strings.HasPrefix("//./", args[0]) {
118-
tmp := make([]byte, 22) // 5 bytes for ascii port number, 1 for newline, 16 for nonce
119-
117+
// LibAssaaun file socket: Attempt to read contents of the target file and connect to a TCP port
118+
if *assuan {
120119
var port int
121120
var nonce [16]byte
122121

123-
_, err := conn.Read(tmp)
122+
reader := bufio.NewReader(conn)
123+
124+
// Read the target port number from the first line
125+
tmp, _, err := reader.ReadLine()
126+
port, err = strconv.Atoi(string(tmp))
124127
if err != nil {
125-
log.Fatalln("Could not open file", err)
128+
log.Fatalln(err)
126129
}
127130

128-
for i, c := range tmp {
129-
// Find the new line
130-
if c == 0x0A {
131-
port, err = strconv.Atoi(string(tmp[:i]))
132-
if err != nil {
133-
log.Fatalln(err)
134-
}
131+
// Read the rest of the nonce from the file
132+
n, err := reader.Read(nonce[:])
133+
if err != nil {
134+
log.Fatalln(err)
135+
}
135136

136-
copy(nonce[:], tmp[i+1:])
137+
if n != 16 {
138+
log.Fatalf("Read incorrect number of bytes for nonce. Expected 16, got %d (0x%X)", n, nonce)
139+
}
137140

138-
if *verbose {
139-
log.Printf("Port: %d, Nonce: %X", port, nonce)
140-
}
141-
break
142-
}
141+
if *verbose {
142+
log.Printf("Port: %d, Nonce: %X", port, nonce)
143143
}
144144

145145
_ = conn.Close()
146146

147+
// Try to connect to the libassaun TCP socket hosted on localhost
147148
conn, err = dialPort(port, *poll)
148149

149150
if *poll && (err == WSAETIMEDOUT || err == WSAECONNREFUSED || err == WSAENETUNREACH || err == ERROR_CONNECTION_REFUSED) {

0 commit comments

Comments
 (0)