-
Notifications
You must be signed in to change notification settings - Fork 2
/
otrcat.go
322 lines (288 loc) · 7.78 KB
/
otrcat.go
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
// "otrcat" is a general purpose communication tool using the Off-The-Record
// protocol.
//
// Copyright (C) 2014 Andrew Clausen
// This program may be distributed under the BSD-style licence that Go is
// released under; see https://golang.org/LICENSE.
package main
import (
"code.google.com/p/go.crypto/otr"
"crypto/rand"
"flag"
"fmt"
"net"
"os"
"strings"
)
// TODO: figure out a good default port
const OTRPort = ":2147"
type Command struct {
call func()
name string
desc string
args []string
flags *flag.FlagSet
}
var (
privateKey otr.PrivateKey
// Contacts, loaded by default from ~/.otrcat/contacts
contacts map[string]string = make(map[string]string) // name -> fingerprint
contactsReverse map[string]string = make(map[string]string) // fingerprint -> name
// Things parsed from command-line arguments
cmd *Command
args []string // Non-flag arguments
dir string
privateKeyPath string
contactsPath string
address string = OTRPort
anyone bool
remember string
expect string
execCommand string
forever bool
cmds []Command // Commands (effectively a constant)
)
// Command-line flags
func dirFlag(f *flag.FlagSet) {
f.StringVar(&dir, "dir", "$HOME/.otrcat",
"where keys and contacts are stored")
}
func keyFileFlag(f *flag.FlagSet) {
f.StringVar(&privateKeyPath, "key", "", "the private key file")
}
func contactsFileFlag(f *flag.FlagSet) {
f.StringVar(&contactsPath, "contacts", "", "the contacts file")
}
func anyoneFlag(f *flag.FlagSet) {
f.BoolVar(&anyone, "anyone", false, "converse with anyone, not just known contacts")
}
func rememberFlag(f *flag.FlagSet) {
f.StringVar(&remember, "remember", "", "name to remember the contact by; implies -anyone")
}
func expectFlag(f *flag.FlagSet) {
f.StringVar(&expect, "expect", "", "contact to expect; abort if it's someone else")
}
func execFlag(f *flag.FlagSet) {
f.StringVar(&execCommand, "exec", "", "shell command to execute with sh(1); the contact is $1")
}
func foreverFlag(f *flag.FlagSet) {
f.BoolVar(&forever, "forever", false, "listen forever; requires -exec")
}
// A flag.FlagSet constructor.
func flags(cmd string, flags ...func(*flag.FlagSet)) *flag.FlagSet {
fs := flag.NewFlagSet(cmd, flag.ExitOnError)
for _, flag := range flags {
flag(fs)
}
return fs
}
func exitError(err error) {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(1)
}
func exitPrintf(errFormat string, args ...interface{}) {
fmt.Fprintf(os.Stderr, errFormat, args...)
os.Exit(1)
}
// Generates a new private key
func genkey() {
// Key generation takes a long time, so it's polite to check the user's
// request makes sense first.
establishDir(true)
if _, err := os.Lstat(privateKeyPath); err == nil {
exitPrintf("Error: The private key file (%s) already exists.\n",
privateKeyPath)
}
fmt.Fprintf(os.Stderr, "Generating a new private key (%s)...", privateKeyPath)
privateKey.Generate(rand.Reader)
fmt.Fprintf(os.Stderr, "\n")
saveKey(privateKeyPath, &privateKey)
}
// Parses and checks the flags that are relevant for listen/connect/proxy.
// This uses the contacts information from ~/.otrcat
func parseConversationFlags() {
if remember != "" {
anyone = true
}
if expect != "" && remember != "" {
exitPrintf("The -expect and -remember options are mutually exclusive.\n")
}
if anyone && expect != "" {
exitPrintf("The -expect and -anyone options are mutually exclusive.\n")
}
if expect != "" {
if _, known := contacts[expect]; !known {
exitPrintf("Can't expect unknown contact '%s'.\n", expect)
}
}
if remember != "" {
if _, known := contacts[remember]; known {
exitPrintf("Can't re-remember an already known contact '%s'.\n",
remember)
}
}
if cmd.name == "proxy" {
return
}
if len(args) == 1 {
address = args[0]
if address == "" {
address = OTRPort
}
if cmd.name == "listen" {
if !strings.HasPrefix(address, ":") {
exitPrintf("Can't listen on a remote address (%s). "+
"Specify a local port with ':port'.\n", address)
}
}
if !strings.Contains(address, ":") {
address += OTRPort
}
}
}
// Selects a private key for use in the conversation
func useKey(key *otr.PrivateKey) {
privateKey = *key
fingerprint := string(key.PublicKey.Fingerprint())
if _, ok := contacts[fingerprint]; !ok {
contacts["me"] = fingerprint
contactsReverse[fingerprint] = "me"
}
}
func connect() {
useKey(loadKey(privateKeyPath))
loadContacts(contactsPath)
parseConversationFlags()
conn, err := net.Dial("tcp", address)
if err != nil {
exitError(err)
}
mainLoop(privateKey, conn)
conn.Close()
}
func listen() {
useKey(loadKey(privateKeyPath))
loadContacts(contactsPath)
parseConversationFlags()
if forever && execCommand == "" {
exitPrintf("-forever requires -exec.\n")
}
ln, err := net.Listen("tcp", address)
if err != nil {
exitError(err)
}
if forever {
for {
conn, err := ln.Accept()
if err != nil {
exitError(err)
}
go func() {
mainLoop(privateKey, conn)
conn.Close()
}()
}
} else {
conn, err := ln.Accept()
if err != nil {
exitError(err)
}
mainLoop(privateKey, conn)
conn.Close()
}
}
func proxy() {
useKey(loadKey(privateKeyPath))
loadContacts(contactsPath)
parseConversationFlags()
cmd, conn, err := startProxy(args)
if err != nil {
exitError(err)
}
mainLoop(privateKey, conn)
closeProxy(cmd, conn)
}
// Lists all known contacts (including "me")
func fingerprints() {
useKey(loadKey(privateKeyPath))
loadContacts(contactsPath)
for name, fingerprint := range contacts {
fmt.Printf("%-20s %x\n", name, fingerprint)
}
}
func matchCommand(name string) *Command {
for _, cmd := range cmds {
if cmd.name == name {
return &cmd
}
}
return nil
}
func help() {
if cmd != nil && cmd.name == "help" {
if len(args) > 0 {
cmd = matchCommand(args[0])
if cmd != nil {
helpCommand(cmd)
}
}
}
fmt.Fprintf(os.Stderr, "Usage:\n")
for _, cmd := range cmds {
fmt.Fprintf(os.Stderr, "otrcat %-15s %s\n", cmd.name, cmd.desc)
}
os.Exit(1)
}
func helpCommand(cmd *Command) {
fmt.Fprintf(os.Stderr, "Usage: otrcat %s", cmd.name)
for _, arg := range cmd.args {
fmt.Fprintf(os.Stderr, " %s", arg)
}
fmt.Fprintf(os.Stderr, " [options]\n")
cmd.flags.PrintDefaults()
os.Exit(1)
}
func main() {
cmds = []Command{
Command{connect, "connect", "start a conversation", []string{"[host][:port]"},
flags("connect", dirFlag, keyFileFlag, anyoneFlag, rememberFlag, contactsFileFlag, expectFlag, execFlag)},
Command{fingerprints, "fingerprints", "show contacts' fingerprints", []string{},
flags("fingerprints", dirFlag, keyFileFlag, contactsFileFlag)},
Command{genkey, "genkey", "create a new private key", []string{},
flags("genkey", dirFlag, keyFileFlag)},
Command{help, "help", "help on each command", []string{"[command]"}, flags("help")},
Command{listen, "listen", "wait for someone to start a conversation", []string{"[:port]"},
flags("listen", dirFlag, keyFileFlag, anyoneFlag, rememberFlag, contactsFileFlag, expectFlag, execFlag, foreverFlag)},
Command{proxy, "proxy", "connect with a proxy command", []string{"command", "[args]"},
flags("proxy", dirFlag, keyFileFlag, anyoneFlag, rememberFlag, contactsFileFlag, expectFlag, execFlag)},
}
if len(os.Args) < 2 {
help()
}
cmd = matchCommand(os.Args[1])
if cmd == nil {
help()
}
cmd.flags.Parse(os.Args[2:])
args = cmd.flags.Args()
if cmd.name == "proxy" {
if len(args) == 0 {
fmt.Fprintf(os.Stderr, "'proxy' needs a command to be specified.\n")
helpCommand(cmd)
}
} else {
if len(args) > len(cmd.args) {
fmt.Fprintf(os.Stderr, "%s only takes up to %d parameters.\n",
cmd.name, len(cmd.name))
helpCommand(cmd)
}
}
dir = os.ExpandEnv(dir)
if privateKeyPath == "" {
privateKeyPath = dir + "/id.priv"
}
if contactsPath == "" {
contactsPath = dir + "/contacts"
}
cmd.call()
}