Commit c83a61011ad7213dc64f57a2b9c498bfda78d914

Parents: b8e58b1abf62553192a5bd578f6cb55b48ef15ca

From: Moritz Poldrack <git@moritz.sh>
Date: Sun Jun 12 20:25:04 2022 +0700

added capability parser
The CAPABILITIES command is what allows us to check beforehand if a
command can be run on a server. The capabilities are cached when they
are fetched which automatically happens on first connection.

Stats

README.md +1/-1
capabilities.go +219/-0
capabilities_test.go +104/-0
conn-options.go +5/-0
conn.go +19/-7
status.go +12/-0

Changeset

  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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
diff --git a/README.md b/README.md
index 59620e15f3578192ca10dc43684e778e5413eba5..61a211bcedd1404d13948cb4bb6d2aad233fb15c 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ ## TODO
 
 | Command           | Capability    | Implemented | Standard |
 |-------------------|---------------|-------------|----------|
-| CAPABILITIES      | mandatory     |            | RFC3977  |
+| CAPABILITIES      | mandatory     | 🗸           | RFC3977  |
 | HEAD              | mandatory     |            | RFC3977  |
 | HELP              | mandatory     |            | RFC3977  |
 | QUIT              | mandatory     |            | RFC3977  |
diff --git a/capabilities.go b/capabilities.go
new file mode 100644
index 0000000000000000000000000000000000000000..c96d5a26c92cf92541c3bcb3364c546358723ee0
--- /dev/null
+++ b/capabilities.go
@@ -0,0 +1,219 @@
+package nntp
+
+import (
+	"bytes"
+	"context"
+	"errors"
+	"fmt"
+	"strings"
+)
+
+// Capability is a bitmap indicating available commands of the server
+type Capability uint
+
+const (
+	CapReader Capability = 1 << iota
+	CapHDR
+	CapIHave
+	CapList
+	CapModeReader
+	CapNewNews
+	CapOver
+	CapPost
+	CapListActive
+	CapListActiveTimes
+	CapListDistribPats
+	CapListHeaders
+	CapListNewsgroups
+	CapListOverviewFmt
+	CapAuthInfoUser
+	CapAuthInfoSASL
+	CapSASL = CapAuthInfoSASL
+)
+
+// Capabilities retrieves the server's available commands and updates them in
+// the connection to make their functions available.
+func (c *Conn) Capabilities(ctx context.Context) (Capability, error) {
+	r, err := c.Cmd(ctx, "CAPABILITIES")
+	if err != nil {
+		c.caps = 0
+		return 0, fmt.Errorf("failed to get capabilities: %v", err)
+	}
+
+	var cap Capability
+	for _, line := range bytes.Split(r.Body, []byte{'\n'}) {
+		parts := strings.SplitN(string(line), " ", 2)
+		entry := capMap[parts[0]]
+		if entry == nil {
+			continue
+		}
+
+		if entry.parser != nil {
+			if len(parts) < 2 {
+				continue
+			}
+			cap |= entry.parser(parts[1])
+		}
+		cap |= entry.cap
+	}
+
+	if c.caps != ^Capability(0) {
+		c.caps = cap
+	}
+	return cap, nil
+}
+
+// String returns a string representation of the capability bitmap. Useful for
+// debugging.
+func (c Capability) String() string {
+	var res string
+	if c&CapReader > 0 {
+		res += "Reader"
+	}
+	if c&CapHDR > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "HDR"
+	}
+	if c&CapIHave > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "IHave"
+	}
+	if c&CapList > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "List"
+	}
+	if c&CapModeReader > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "ModeReader"
+	}
+	if c&CapNewNews > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "NewNews"
+	}
+	if c&CapOver > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "Over"
+	}
+	if c&CapPost > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "Post"
+	}
+	if c&CapListActive > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "ListActive"
+	}
+	if c&CapListActiveTimes > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "ListActiveTimes"
+	}
+	if c&CapListDistribPats > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "ListDistribPats"
+	}
+	if c&CapListHeaders > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "ListHeaders"
+	}
+	if c&CapListNewsgroups > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "ListNewsgroups"
+	}
+	if c&CapListOverviewFmt > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "ListOverviewFmt"
+	}
+	if c&CapAuthInfoUser > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "AuthInfoUser"
+	}
+	if c&CapAuthInfoSASL > 0 {
+		if res != "" {
+			res += "|"
+		}
+		res += "AuthInfoSASL"
+	}
+	return res
+}
+
+type capMapEntry struct {
+	cap    Capability
+	parser func(string) Capability
+}
+
+var capMap = map[string]*capMapEntry{
+	"MODE-READER": {cap: CapModeReader},
+	"READER":      {cap: CapReader},
+	"XHDR":        {cap: CapHDR}, // for RFC2980 compability
+	"HDR":         {cap: CapHDR},
+	"XOVER":       {cap: CapOver}, // for RFC2980 compability
+	"OVER":        {cap: CapOver},
+	"POST":        {cap: CapPost},
+	"LIST":        {parser: listParser},
+	"AUTHINFO":    {parser: authInfoParser},
+}
+
+func listParser(remainder string) Capability {
+	cap := CapList
+	for _, val := range strings.Split(remainder, " ") {
+		switch strings.ToUpper(val) {
+		case "ACTIVE":
+			cap |= CapListActive
+		case "ACTIVE.TIMES":
+			cap |= CapListActiveTimes
+		case "DISTRIB.PATS":
+			cap |= CapListDistribPats
+		case "HEADERS":
+			cap |= CapListHeaders
+		case "NEWSGROUPS":
+			cap |= CapListNewsgroups
+		case "OVERVIEW.FMT":
+			cap |= CapListOverviewFmt
+		}
+	}
+	return cap
+}
+
+func authInfoParser(remainder string) Capability {
+	var cap Capability
+	for _, val := range strings.Split(remainder, " ") {
+		switch strings.ToUpper(val) {
+		case "USER":
+			cap |= CapAuthInfoUser
+		case "SASL":
+			cap |= CapAuthInfoSASL
+		}
+	}
+	return cap
+}
+
+// ErrCapabilityNotSupported is returned when a server does not advertise a
+// capability as supported
+var ErrCapabilityNotSupported = errors.New("server does not support operation")
diff --git a/capabilities_test.go b/capabilities_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bcf309bb467021780e99b89267a1774d25756659
--- /dev/null
+++ b/capabilities_test.go
@@ -0,0 +1,104 @@
+package nntp_test
+
+import (
+	"context"
+	"testing"
+	"time"
+
+	"mpldr.codes/usenet/nntp"
+)
+
+func TestCapabilities(t *testing.T) {
+	tests := []struct {
+		name     string
+		host     string
+		options  []nntp.ConnOption
+		expected nntp.Capability
+	}{
+		{
+			name:     "eweka-unauthenticated",
+			host:     "news.eweka.nl:119",
+			options:  []nntp.ConnOption{nntp.OptionUnencrypted},
+			expected: nntp.CapAuthInfoUser,
+		},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			c, err := nntp.Dial(test.host, test.options...)
+			if err != nil {
+				t.Logf("failed to connect to host: %v", err)
+				t.SkipNow()
+			}
+
+			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+			defer cancel()
+			caps, err := c.Capabilities(ctx)
+			if err != nil {
+				t.Errorf("failed to run command: %v", err)
+				t.FailNow()
+			}
+
+			if caps&test.expected != test.expected {
+				t.Errorf("did not receive expected caps:\n\tgot:      %s\n\texpected: %s", caps, test.expected)
+				t.FailNow()
+			}
+		})
+	}
+}
+
+func TestCapabilityString(t *testing.T) {
+	tests := []struct {
+		name     string
+		caps     nntp.Capability
+		expected string
+	}{
+		{
+			name:     "empty",
+			caps:     0,
+			expected: "",
+		},
+		{
+			name: "eweka",
+			caps: nntp.CapModeReader |
+				nntp.CapReader |
+				nntp.CapList |
+				nntp.CapListActive |
+				nntp.CapListActiveTimes |
+				nntp.CapListNewsgroups |
+				nntp.CapListOverviewFmt |
+				nntp.CapHDR |
+				nntp.CapOver |
+				nntp.CapPost,
+			expected: "Reader|HDR|List|ModeReader|Over|Post|ListActive|ListActiveTimes|ListNewsgroups|ListOverviewFmt",
+		},
+		{
+			name: "full",
+			caps: nntp.CapReader |
+				nntp.CapHDR |
+				nntp.CapIHave |
+				nntp.CapList |
+				nntp.CapModeReader |
+				nntp.CapNewNews |
+				nntp.CapOver |
+				nntp.CapPost |
+				nntp.CapListActive |
+				nntp.CapListActiveTimes |
+				nntp.CapListDistribPats |
+				nntp.CapListHeaders |
+				nntp.CapListNewsgroups |
+				nntp.CapListOverviewFmt |
+				nntp.CapAuthInfoUser |
+				nntp.CapAuthInfoSASL,
+			expected: "Reader|HDR|IHave|List|ModeReader|NewNews|Over|Post|ListActive|ListActiveTimes|ListDistribPats|ListHeaders|ListNewsgroups|ListOverviewFmt|AuthInfoUser|AuthInfoSASL",
+		},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			if test.caps.String() != test.expected {
+				t.Errorf("unexpected result:\n\tgot:     %s\n\texpected: %s", test.caps.String(), test.expected)
+			}
+		})
+	}
+}
diff --git a/conn-options.go b/conn-options.go
index f71ddb51409a6b2bf9f08285c20ade7ccb171ade..d35bdaeadf6c70ff47142547601a421e456fdb5a 100644
--- a/conn-options.go
+++ b/conn-options.go
@@ -6,6 +6,7 @@
 type optionset struct {
 	unencrypted      bool
 	skipVerification bool
+	caps             Capability
 }
 
 var (
@@ -13,4 +14,8 @@ 	// OptionUnencrypted disables TLS for the given Conn
 	OptionUnencrypted ConnOption = func(o *optionset) { o.unencrypted = true }
 	// OptionInsecure disables TLS cert verification for the given Conn
 	OptionInsecure ConnOption = func(o *optionset) { o.skipVerification = true }
+	// OptionNoCapabilities disables the capability check before running
+	// commands in case a server does not accurately report it's
+	// capabilities.
+	OptionNoCapabilities ConnOption = func(o *optionset) { o.caps = ^Capability(0) }
 )
diff --git a/conn.go b/conn.go
index 98eb793565f3c765ca0515ad9b7bcd82d2ac36d6..455c002a21599a1362513cdc4511acf00c52132f 100644
--- a/conn.go
+++ b/conn.go
@@ -6,9 +6,9 @@ 	"context"
 	"crypto/tls"
 	"errors"
 	"fmt"
-	"io"
 	"net"
 	"net/textproto"
+	"time"
 )
 
 // Conn represents a connection to a newsserver. Since NNTP connections have a
@@ -18,9 +18,7 @@ 	c      *textproto.Conn
 	ctx    context.Context
 	cancel context.CancelFunc
 
-	capabilities int
-
-	input io.Writer
+	caps Capability
 }
 
 // Dial creates a new connection to an NNTP server
@@ -64,14 +62,28 @@ 	c := &Conn{
 		c:      textproto.NewConn(conn),
 		ctx:    ctx,
 		cancel: cancel,
+		caps:   o.caps,
 	}
 
-	_, _, err := c.c.ReadCodeLine(2)
+	code, _, _ := c.c.ReadCodeLine(-1)
+
+	ctxt, cancel := context.WithTimeout(context.Background(), 16*time.Second)
+	_, err := c.Capabilities(ctxt)
+	cancel()
 	if err != nil {
-		return nil, fmt.Errorf("server sent unexpected status code: %w", err)
+		return nil, fmt.Errorf("failed to retrieve capabilities: %w", err)
 	}
 
-	return c, nil
+	switch code {
+	case StatusServiceAvailable, StatusServiceNoPosting:
+		return c, nil
+	case StatusTemporarilyUnavailable:
+		return nil, ErrTemporarilyUnavailable
+	case StatusPermanentlyUnavailable:
+		return nil, ErrPermanentlyUnavailable
+	default:
+		return nil, fmt.Errorf("%w: %d", ErrUnexpectedResponse, code)
+	}
 }
 
 func (c *Conn) Close(ctx context.Context) error {
diff --git a/status.go b/status.go
new file mode 100644
index 0000000000000000000000000000000000000000..a58f745ed06a656eab5361488e71b1089e38c33a
--- /dev/null
+++ b/status.go
@@ -0,0 +1,12 @@
+package nntp
+
+import "errors"
+
+const (
+	StatusServiceAvailable       = 200
+	StatusServiceNoPosting       = 201
+	StatusTemporarilyUnavailable = 400
+	StatusPermanentlyUnavailable = 502
+)
+
+var ErrUnexpectedResponse = errors.New("received unexpected response code")