CompuServe front end: logon, ESC I, pages, and the B / B Plus protocols

A listener with frontend = compuserve serves the CompuServe Information
Service on the BBS's users: Host Name, User ID (an account's number as a
CompuServe ID, or its name) and Password, ?LOG codes, ESC I terminal
identification, the banner and logoff text, and the ASCII service's menu
and article pages with GO, FIND, T/M/B/F/R/N/P, SET and ; chaining.  CIM
clients are told ?LOG CAI until the HMI service is built.

internal/xfer/cisb.go is CompuServe B, Quick B and B Plus, the host's side
and the terminal's: ENQ start, + parameter negotiation, quoting, all four
check methods, a send window with ENQ resynchronization, downloads and
uploads.  Tested against the spec's checksum and CRC values and over a
noisy loopback.

docs/cis holds the research and design behind it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRRPWCkk1Ro91AuzXFM
This commit is contained in:
Claude committed 2026-11-08 11:16:10 +00:00
1 parent b9a9accf0c
commit 20908882c9
23 files changed
+4571 -4

No files matched your search

+12
View File
@@ -153,6 +153,11 @@ throttle_time = 600
; account (with no password of its own)
; socket_mode = 0660 a unix socket's permissions
; socket_group = ... and its group
; frontend = bbs what callers get: the BBS, or compuserve: the
; CompuServe Information Service (telnet and raw
; listeners; no 3270). See the wiki's CompuServe
; connect = 9600 compuserve: the CONNECT line before Host Name:
; (telnet: 9600; raw: none, the modem says its own)
; keeping callers out: a file of addresses and networks refused, one of
; names no new user may take (* wildcards), the hack log, and how long an
@@ -208,6 +213,13 @@ max_per_ip = 4
type = raw
address = 127.0.0.1:2323
; the CompuServe Information Service, on the BBS's users: Host Name: CIS,
; then a User ID (shown at logon) or BBS name and the BBS password
;[listen cis]
;type = telnet
;address = :2324
;frontend = compuserve
; SSH: the text BBS, encrypted. Users log in with their BBS password or
; a key (bbs sshkey add, or their profile); "new" gets the BBS's prompt
; to sign up. Host keys are made beside the database the first time
+97
View File
@@ -0,0 +1,97 @@
# 01 — History and Original Architecture
This doc is context for the reimplementation: what CompuServe was, what ran it, and how users reached it.
Tags: **[C]** confirmed · **[S]** secondary · **[GAP]** unknown.
## 1. Timeline
| Date | Event | Source |
|---|---|---|
| 1969 | Compu-Serv Network, Inc. founded in Columbus, OH, as a Golden United Life subsidiary (timesharing) | [S] Wikipedia; [C] Trevor memo |
| Feb 1980 | CB Simulator launched | [S] |
| 24 Sep 1979 | MicroNET consumer service launched, sold through Radio Shack | [S] |
| May 1980 | H&R Block buys CompuServe (~$25M) | [S] |
| 1 Jul 1980 | MicroNET renamed **CompuServe Information Service (CIS)** | [S] |
| 1982 | B protocol replaces A [C, Ranshaw]; CompuServe Network Services formed | |
| 15 Jun 1987 | GIF87a released (Steve Wilhite's team) | [S] |
| 1989 | CIM/HMI introduced; Internet mail gateway; The Source bought (23 Jun) and shut down (1 Aug) | [S] |
| Apr 1995 | Peak of ~3M members | [S] |
| 1995–96 | Forums move to the NT-based "NISA" hosts (HMI-only) | [C] cishmi.faq |
| 1996 | CSi rebrand / CompuServe 3.0 | [S] |
| Feb 1998 | WorldCom buys CompuServe; the consumer service goes to AOL | [S] |
| 30 Jun 2009 | CompuServe Classic (HMI) and OurWorld shut down | eWeek, The Register |
| 15 Dec 2017 | Forums closed | [S] |
Wikipedia's claims that "HMI was discontinued in 2004" and that "forums were converted to HTML in 1997" conflict with WinCIM working until 2009. Treat them as unreliable.
## 2. Host hardware and OS
Source: Sandy Trevor, internal memo "We Call Them 10's", 31 Aug 1988, <https://ftp.inwap.com/pdp10/compuserve.txt> [C].
- **Machines:** DEC 36-bit, in this order:
- KA-10 (1969)
- KI-10s (seven by 1974)
- KL / DECSYSTEM-2050s
- **Systems Concepts SC-30** (ordered 1986, arrived late 1987)
- **SC-40** (1993). CompuServe licensed the design and built them in-house. Some were still online after 2005.
- **OS:** heavily modified TOPS-10, the "C/D/E" monitors (E added a class scheduler).
- **Applications:** written in XF4 and Bliss-36, plus Wilhite's BASIC compiler.
- **Front ends:** 680i (PDP-8) front ends, then a PDP-15 comms switch.
- **Sites:** Upper Arlington, Columbus (1973); Dublin (1978); later Hilliard.
- **Mid-90s:** the NISA servers, Windows NT on Intel, ran forums and mail for HMI clients [C, cishmi.faq]. <https://gunkies.org/wiki/CompuServe_recollections> [S]
Primary source not yet explored: 32 GB of raw CompuServe disk images, <https://archive.org/details/2015-05-compuserve-raw-disks>. They use 584-byte sectors in a nonstandard format and are hard to read. They are the best hope for exact host prompts and help text [GAP].
## 3. User IDs
- User IDs were TOPS-10 **PPNs** (project, programmer): `70000,130`, `75116,3524`, and later 10-digit forms like `102345,6789`.
- Internet mail form (from 1989): `70000.130@compuserve.com`. The comma becomes a period.
- The claim that IDs only use octal digits (no 8 or 9) is plausible but not verified. `75116,3524` contains no 8 or 9; other surviving examples should be checked.
**For our server:**
- Allocate IDs as `7xxxx,xxx` (project ≥ 70000).
- Parse with a lenient regex, `^\d{5,6},\d{1,5}$`.
- Accept `.` in place of `,` (`/INT:60`-style options are stripped first).
## 4. Network and access paths
- **CompuServe's own network:** PDP-11 nodes from 1977, later 486/Qbus "Trinodes". It later moved to X.25, Frame Relay, ATM and IP. Users dialled a local node, which prompted `Host Name:`.
- **Partner networks:** Tymnet, Telenet/SprintNet, Datapac, Transpac, Infonet, Mercury. Each had its own login dialogue before reaching CIS (scripts in CompuServe's 1996 CSERVE package).
- **Host names:** `CIS` in the manuals, `CPS` in the 1996 scripts, `CISAGREE` over the Internet.
- **Internet:**
- 1992: `telnet hermes.merit.edu` → "Which Host?" → `compuserve`.
- Later: direct telnet (exact hostname [GAP]).
- 1995: PPP via `<id>/GO:PPPCONNECT`.
- WinCIM could also use Winsock TCP on **port 4144**.
## 5. Clients
| Kind | Examples | Interface |
|---|---|---|
| Dumb terminal / emulator | Any terminal program, VT100, CompuServe's VIDTEX | ASCII + VIDTEX escapes, B for downloads |
| Offline readers (ASCII) | TAPCIS (≤6.0), AutoSIG/ATO, OzCIS | Scripted ASCII. Depend on exact prompts and `GO DEFAULT` settings |
| GUI (HMI) | DOSCIM, WinCIM, MacCIM, OS/2 CIM, CSNAV, MacNAV, OzWIN, TAPCIS 6.1 | HMI over the B+ Transport Layer |
See [02](02-terminal-ux.md) for the ASCII experience, [03](03-link-protocols.md) for B/B+, and [04](04-cim-hmi.md) for HMI.
## 6. Graphics
- **CompuServe RLE** [C]:
- Starts with `ESC G H` (256×192) or `ESC G M` (128×96).
- Each byte is a run length + 0x20 (0–94 pixels). Runs alternate background/foreground, starting with background, and wrap across lines.
- Ends with `ESC G N` (optionally preceded by BEL).
- Used for weather maps (`GO AWX`) and the CB "picture" pages.
- Send it only to clients that report `GH`/`GM` in `ESC I`.
- Refs: <https://github.com/RevCurtisP/csrle>, PRONOM fmt/1538.
- **GIF:** CompuServe's own format, from 1987. Delivered by B+ download (`ESC [ > 1 g` announces one to capable clients; doc 03 §5.4).
- **NAPLPS:** no evidence that CIS used it.
## 7. Other reimplementations
| Project | What it is |
|---|---|
| `24high/CompuServe-Emulator` (C#, 2026) | WinCIM 3.x HMI server. **Key reference** (doc 04). |
| `paulsullivan33-dev/compuserve-simulator` (Python) | Text-mode CIS-flavoured simulation, 1988 setting. Not protocol-faithful. |
| `CompuServeReloaded/csr-server` (C#, 2023) | Stub only. |
| `RevCurtisP/csrle` | RLE tools and the original RLE.TXT. |
+733
View File
@@ -0,0 +1,733 @@
# 02 — The Terminal (ASCII) Experience
This doc records what a caller with a plain terminal saw, as close to byte-exact as surviving session captures allow.
Offline readers (TAPCIS, AutoSIG, OzCIS, Navigator) **pattern-match these strings**, so treat the verbatim text as an interface contract.
Tags: **[V]** verbatim from a capture or period document (blank-line runs and ANSI clear codes stripped) · **[P]** paraphrased from a period source · **[I]** inferred.
## Sources
| ID | Source |
|---|---|
| S1 | 1989 logon→logoff via Telepac. <https://discmaster.textfiles.com/view/12465/floppyshareware.zip/floppyshareware/GLEN/TMC.ZIP/89-08-09.L0G> |
| S2 | 1987 CIS Navigator (Mac) session log. <https://discmaster.textfiles.com/view/11599/www.compmuseum.org.tar/www.compmuseum.org/upload/mac/diskimages/Utils%2012.image.hqx/Utils%2012.image/Navig/CIS> |
| S3–S5 | 1988 menu-mode forum, BROWSE and EasyPlex captures. <https://discmaster.textfiles.com/view/18187/Wonky_Flux_Batch_2019-02.zip/Wonky%20Flux%20Batch%202019-02/091%20-%20Compuserve%20EBU%202.dsk/JFORUM15TH.txt> (and `BROwse.DL11.txt`, `EASYPLEX.JAN.txt` in the same folder) |
| S6–S8 | 1993–94 Mac captures (logon, Mail, forum JOIN, RATES, BILLING, command summary). Discmaster item 19202 (`King.img`, `Alexander.img`). |
| S9 | 1995 Navigator session. Discmaster item 20868. |
| S10 | TAPCIS 5.3 (1990): manual TAPDOC.1–10, PARAMS.SCR, CIS.SCR, TYMNET.SCR, SPRINT24.SCR, strings in TAPCIS.EXE. <https://discmaster.textfiles.com/browse/14533/Megaware%20Volume%201.iso/communic/tapcis> |
| S11 | *Forum Software Version 4D Complete Command Listing*, May 1989. <https://discmaster.textfiles.com/view/17620/archives.tar/archives/compuserve-file-archive/02%20Help%20%26%20Utilities/CMDLST.TXT> |
| S12 | IBM PC SIG help text, Nov 1983. <https://discmaster.textfiles.com/view/10621/The%20PC-SIG%20Library%20on%20CD%20ROM%20-%20Ninth%20Edition.iso/001_100/DISK0099/DISK0099.ZIP/CS-IBM.SIG> |
| S13 | Conference/CB help, 1982–84. <https://discmaster.textfiles.com/view/6428/C.A.R.R.S.%20CD-ROM%20(1990).ISO/020a/symp_6.zip/CONFER.HLP> |
| S14 | 1989 forum conference log. <https://discmaster.textfiles.com/view/1969/RBBSIABOX31.cdr/zzap/zipcis.zip/ZIP.LOG> |
| S15 | 1996 forum conference log. <https://discmaster.textfiles.com/view/32223/CD_shareware_12-96.iso/WIN/Juegos/CIV2CON.ZIP/CIV2.TXT> |
| S16 | 1992 forum thread with exact headers. <http://www.textfiles.com/messages/zachman1.msg> |
| S17 | 1980s text files on IDs, CB, logon. <http://www.textfiles.com/hacking/cisinfo4.txt>, `compusrv`, `cis.phk`, `compusin.txt` |
| S18 | Early-80s GO page index. <http://www.textfiles.com/hacking/compuser.txt> |
Local copies of the captures are in the session scratchpad and are not committed. Re-fetch them from the URLs above for golden-transcript tests.
---
## 1. Connecting and logging in
### 1.1 Getting to the host
1. The modem connects: `CONNECT 2400`.
2. On CompuServe's own network the caller sends **Ctrl-C**, or a CR on "picky PADs" [V, S10 CIS.SCR].
3. The node prints its ID (` 02FMA`, ` 0003PAZ`) [V, S6, S9] and then `Host Name:`.
4. The caller types `CIS`.
Some 1987-era nodes went straight from ^C to `User ID:` [V, S2].
Third-party networks:
- Tymnet: wait for ` in:`, send `CPS`, wait for `ERVE` [V, S10].
- Sprintnet: `@`, `D`, `C 614227` [V, S10].
- Both are documented in doc 04 §2.2 too.
### 1.2 1989 full session [V, S1]
```
Host Name: cis
User ID: 73237,341
Password:
CompuServe Information Service
16:11 EDT Wednesday 09-Aug-89 P
Last access: 08:01 07-Aug-89
Copyright (c) 1989
CompuServe Incorporated
All Rights Reserved
GO RATES for information on new
connect time FREE services and
the Membership Support Fee
What's New This Week
1 New Databases Added to Reference Menu
...
9 Uploads: New Forum Files
10 Online Today Product Reviews
Enter choice!off
Thank you for using CompuServe!
Off at 16:12 EDT 9-Aug-89
Connect time = 0:01
^D
```
### 1.3 1993 banner [V, S6]
```
CompuServe Information Service
11:44 EDT Monday 10-May-93 P
(Executive Option)
Last access: 08:27 28-Apr-93
Copyright (c) 1993
CompuServe Incorporated
All Rights Reserved
You have Electronic Mail waiting.
GO RATES for current information
What's New This Week
1 X.400 Link With MCI Mail Added
...
Enter choice !
```
1995 variant [V, S9]:
```
Last access: ...
Connected to port CIS T03PAZ @19200
There is a What's New menu
No electronic mail is waiting.
```
### 1.4 Formatting rules
- **Banner date:** `HH:MM TZ Weekday DD-Mon-YY` followed by `P`. The `P` probably marks prime time [I]; print it during 08:00–19:00 on weekdays.
- **Logoff date:** `Off at HH:MM TZ D-Mon-YY` has **no leading zero on the day**, and `Connect time = h:mm`.
- **Plan line:** `(Executive Option)` appears when the account has it.
- **User ID suffixes:**
- `*NAVIG` (1987) tags the client [V, S2].
- `;TTY` forces default terminal settings [V, S10].
- `/INT`, `/INT:60`, `/GO:x` and `/HOST` are 90s options (doc 04 §2.2).
- `/INT` (with `+`/`/secure`) switches to HMI [I, S9].
- **Bad login:** `?? LOGINE - Invalid entry - try again` [V-quoted, S10]. The 1996 scripts expect the `?LOG INE` family (doc 04). Emit the first form for terminals; the code is the same.
- **Sign-up IDs:** IntroPak IDs looked like `177000,1147` and went through Agreement and Serial number prompts [P].
### 1.5 Logging off
- `OFF` or `BYE` hangs up.
- `LOG` logs off and returns to `User ID:`; TAPCIS uses it [V, S11].
- Logoff text (constant across 1987–94) [V]:
```
Thank you for using CompuServe!
Off at 18:49 EDT 15-Sep-90
Connect time = 0:01
```
After that the network sends `^D` and a new `Host Name:`. Our server prints the text and closes the connection.
---
## 2. User IDs
- The ID is "a project number and a programmer number. An example would be 70007,1460" [V, S17]. The format is `7xxxx,xx`, later `1xxxxx,xxxx`.
- Every ID in the captures uses only digits 0–7: `73237,341`, `76174,2404`, `100073,1227`, `104616,2705`. A 1980s file says "the second number is from '0-7'". **Treat as octal**: allocate only digits 0–7.
- Internet form: `76174.2404@compuserve.com` [V, S7].
- Folklore project ranges [P, S17]: 70000 security, 70003/70004 staff, 70006 customer service, 70007 complimentary, **76701–76704 sysops**, 177000 IntroPak. Sysops in the captures are in 7670x, so follow this.
---
## 3. Navigation
### 3.1 Menu pages
1987 [V, S2]:
```
CompuServe TOP
1 Subscriber Assistance
2 Find a Topic
3 Communications/Bulletin Bds.
4 News/Weather/Sports
5 Travel
6 The Electronic MALL/Shopping
7 Money Matters/Markets
8 Entertainment/Games
9 Home/Health/Family
10 Reference/Education
11 Computers/Technology
12 Business/Other Interests
Enter choice number !
```
1994 [V, S8]. The title is left-aligned and the page ID right-aligned to column 80; free pages add `(FREE)`:
```
CompuServe TOP
1 Access Basic Services
2 Member Assistance (FREE)
3 Communications/Bulletin Bds.
...
12 Business/Other Interests
Enter choice !
```
**Page IDs:**
- Older pages used `PREFIX-n` (`Page PCS-50` [V, S12]; `CIS-177`, `HOM-24`, `GAM-11` [S18]).
- Later pages mix named IDs (`TOP`, `RATES`, `BILLING`) with numbered ones (`CIS-162`, `BIL-512`, `LGN-1`, `CMS-138`).
- **The page tree is keyed by these IDs, and GO words are aliases for them.** HMI uses the same IDs (`CIS:FORUMS`, `HOM:…`; doc 04).
### 3.2 Command summary, page CIS-162 [V, S8]
```
T - TOP menu page
M - previous MENU
H or ? - HELP
GO word or GO page - GO directly to a service
FIND topic - FIND all references to topic
OFF or BYE - sign off
S n - SCROLL from n
R - RESEND a page
F - FORWARD a page
B - BACK a page
N - display NEXT menu item
P - display PREVIOUS menu item
SET option - SET terminal option
PER - exit to Personal File Area
```
- Commands chain with `;` (`OP;LL 32;T;RR 9900`) [V, S12].
- `SET` options include `SET BRI ON`, `SET PAG OFF`, `SET WID 80` [V, S2].
### 3.3 Prompts and messages [V]
| String | Where |
|---|---|
| `Enter choice !` | Standard (1993–94) |
| `Enter choice!` | 1989 variant (no space) |
| `Enter choice number !` | 1987 |
| `Press <CR> for more !` | Pager |
| `Enter choice or <CR> for more !` | Long menus |
| `Last page !` / `Last page, enter choice !` | End of an article or menu |
| `One moment please...` | Before slow services |
| `BILLS is unrecognized !` | Unknown GO word |
| `!` | **Brief mode** (expert) prompt, also `More!` |
| `OK` | Command-mode prompt when "TOP goes to COMMAND" |
From the DEFAULT screen [V, S10]: "1 YES - expert mode (You will receive abbreviated prompts such as ! or More!.) 2 NO - novice/intermediate mode (You will receive full prompts such as Enter choice! or Enter <CR> for more!.)"
PARAMS.SCR calls `!` "CompuServe's almost-universal prompt that it's awaiting user input". **Every prompt must end with `!`** (or the forum's chosen prompt character).
### 3.4 Control keys [V, S12, S13, S10]
| Key | Behaviour |
|---|---|
| Ctrl-C | Abort output; instant exit. In a conference, back to the forum `Function:` prompt. |
| Ctrl-P | Abort output, return to command level |
| Ctrl-S / Ctrl-Q | Freeze / resume output |
| Ctrl-O | Skip the rest of a message's text while retrieving |
| Ctrl-U | Delete the line being typed. **TAPCIS sends ^U before every command; the host echoes ^U only if the buffer had garbage** [V, S10]. |
| Ctrl-V | Retype the line typed so far |
### 3.5 Terminal settings: GO DEFAULT / GO TERMINAL [V, S10 PARAMS.SCR, 1990]
Time spent here is free of charges [V].
```
TERMINAL SETTINGS/SERVICE OPTIONS
1 Instructions
2 Change permanent settings
3 Explanation of session vs. permanent
4 Show session vs. permanent
5 Change current session settings
PERMANENT SETTINGS
1 Explanation
2 Logon/Service options
3 Display options
4 Terminal type/parameters
5 Transfer protocol/graphic support
6 Make session settings permanent
```
| Group | Settings (defaults in [ ]) |
|---|---|
| Display | PAGED display [NO], BRIEF prompts [YES], CLEAR screen between pages, BLANK lines sent, Line feeds sent |
| Terminal | TERMINAL type [OTHER]: VIDTEX, ANSI, VT100, VT52, Heath, ADM, CRT, Other. Screen WIDTH [79], LINES per page [0], Form FEEDS [SIMULATED], Horizontal TABS, CASE [U/L], Chars sent in CAPS, PARITY [ZERO], Output DELAYS [0], ERASE when backspacing [YES], Micro inquiry sequence at logon [NO] |
| Logon/Service | First service at logon, Mail Waiting [NOTIFY ONLY], Personal menu, TOP goes to [COMMAND] (COMMAND/MAIN), Online editor [EDIT] (EDIT/LINEDIT), Forum presentation mode [COMMAND] |
| Protocol | B, Quick B, XMODEM, KERMIT, A, SHOW MENU |
Each change ends with a confirm screen: `CHANGE PERMANENT SETTINGS 1 Confirm 2 Cancel`.
Other notes:
- "Micro inquiry sequence at logon" is the setting that sends `ESC I` at login (doc 03 §5).
- **Compatibility minimum** [V, S10]: TAPCIS requires PAGED=NO and COMMAND mode in forums and Mail ("COMMAND mode is essential. TAPCIS will not work in any other"). Navigator for the Mac needs "TOP goes to MAIN".
---
## 4. Forums
### 4.1 Entering a forum (1988, forum software V.4C) [V, S3]
```
Online CAMPUS JFORUM
One moment please...
Welcome to Journalism Forum, V. 4C(232)
Hello, JOHN EDWARDS
Last visit: 30-Dec-87 14:04:33
Forum messages: 33295 to 34948
Last message you've read: 0
Subtopic(s) Selected:
All Accessible
No members are in conference.
Short bulletin:
...
Press <CR> :
Journalism Forum
FUNCTIONS
1 (L) Leave a Message
2 (R) Read Messages
3 (CO) Conference Mode
4 (DL) Data Libraries
5 (B) Bulletins
6 (MD) Member Directory
7 (OP) User Options
8 (IN) Instructions
Enter choice !
```
### 4.2 1994 forum menu and JOIN (software V.3B) [V, S7]
```
Welcome to Amiga Tech Forum, V. 3B(64)
Forum messages: 39470 to 40332
Amiga Tech Forum Forum Menu
1 INSTRUCTIONS
2 MESSAGES
3 LIBRARIES (Files)
4 CONFERENCING (0 participating)
5 ANNOUNCEMENTS from sysop
6 MEMBER directory
7 OPTIONS for this forum
8 JOIN this forum
Enter choice !2
Non-members cannot access this feature.
Do you wish to join (Y or N)? y
Please enter your name: don hicks
don hicks
Is this correct (Y or N)? y
Inserting name and ID...
Thank You For Joining Amiga Tech Forum !
Press <CR> !
```
Sub-menus [V, S7]:
- **Messages Menu:** `Message age selection = [All]`, `1 SELECT (Read by section and subject)`, `2 READ or search messages`, `3 CHANGE age selection`, `4 COMPOSE a message`, `5 UPLOAD a message`.
- **Read Menu:** `1 [ALL] messages`, `2 Message NUMBER`, `3 WAITING messages for you (0)`, then `Search [all] messages` with `4 FROM (Sender)`, `5 SUBJECT`, `6 TO (Recipient)`.
- **After each message:** `Press <CR> for next or type CHOICES !`, which leads to the **Read Action Menu**: `1 REPLY with same subject`, `2 COMPOSE with new subject`, `3 REREAD this message`, `4 SKIP reply`, `5 SKIP ALL`, `6 READ reply`.
- **Other strings:** `Message #:`, `Can't find message #40300`, `There is 1 Reply.`, `Press <CR> for more:`.
### 4.3 Leaving a message (1988) [V, S3]
```
Enter choice !L
To: ALL
Subject: SUBJECTS
Enter /EX to exit EDIT
[ New message ready ]
...text...
/ex
LEAVE ACTIONS
1 (S) Store the Message
2 (SU) Store Unformatted
3 (MA) Mail via Easyplex
4 (MU) Mail Unformatted
5 (C) Continue Entering Text
6 (A) Abort the Leave Function
Enter choice !s
SUBTOPIC # REQUIRED
0 General Information
...
17 DeskTop Publishing
Enter choice : 5
Message # 34949 Stored
```
Sections run 0–17, which fixes the **section limit at 18 per forum**.
### 4.4 Message header [V, S16 1992; S7 1994]
```
#: 210094 S10/Views:Zachmann [E]
04-Jul-92 12:33:25
Sb: #210070-#Independence Declaration
Fm: Bruce Biermann [ZiffNet] 72241,261
To: William F. Zachmann 72241,43 (X)
...body...
* Reply: 210146
```
| Line | Rule |
|---|---|
| 1 | `#: <num> S<sec>/<section name>`, optionally followed by ` [E]`. TAPCIS shows `#: 55848` (two spaces). |
| 2 | Four spaces, then `DD-Mon-YY HH:MM:SS` (two spaces between date and time). |
| Sb | `#Subj` = thread root that has replies. `#<parent>-#Subj` = a reply that itself has replies. `#<parent>-Subj` = a leaf. |
| Fm / To | `Name ID`. `(X)` after To means the addressee has read it. Sysops look like `Steve Pietrowicz/SYSOP 76701,250`. |
| Footer | `* Reply: n` or `* Replies: n, n, …` wrapped with a 12-space indent (V.4); V.3B prints `There is 1 Reply.` |
### 4.5 Command mode (forum software 4D, 1989) [V, S11]
**Prompts:**
`Forum !`, `Messages !`, `LIB !`, `Member Directory !`, `Read action !`, `Enter <CR> for more or type CHOICES !`, `Post action !`, `Edit !`.
**Commands available everywhere:**
`CON FIND G/GO HELP LIB LOG M MES OFF OPT PER PRO QUO R S SET T UST WEA WHO ?`
**At `Forum !`:**
`A`nnouncements, `COM`pose, `CO#`, `DE`scriptions, `EX`it, `I`nstructions, `LIB#`, `MEM`bership, `NA`mes, `NE`w, `OP`tions, `REA`d, `WH`o, `U`log.
**At `Messages !`:**
`BR`owse, `CH`ange, `HI`gh (sets the high-message pointer), `SE`lect, `SCA`n, `U`pload.
**Read, browse and scan:**
```
READ|BROWSE [FORWARD|THREAD|REVERSE|WAITING|MARKED] [NEW|DAYS:##|ALL|STA:##]
[FROM:x|TO:x|SUB:x] [SEC:#,#]
```
Examples: `REA WAI`, `REA MAR`, `REA ALL SEC:2,9,10`, `REA NEW FRO:76703,4363`, `REA REV LAST`. `SCA` takes the same arguments plus `PRO`.
**After a message:**
`CH`oices, `D`elete, `MA`rk, `NEX`, `NEX SUB`, `P`arent, `REA` (replies), `RE`ply, `RER`ead, `RO`ot, `SC`roll.
**Posting:**
`POST [UNF] [PRI] [SEC:##] [TO:x] [SUB:x]`.
**Editor (EDIT):**
`/A /B /C/old/new /D# /EXIT /HELP /L/text /N# /P# /POS# /POST /T /TYPE /UPLOAD /W`. The alternative editor is LINEDIT, which numbers lines.
**OPTIONS:**
`CH`aracter (prompt character), `E`ditor, `HI`gh, `I`nitial, `MO`de, `N`ame, `P`ermanent, `PA`use, `RE`plies, `S`ession, `SEC`tions, `SK`ip, `TY`pe.
**Commands TAPCIS sends** (from TAPCIS.EXE strings) [V, S10]. **These are the acceptance tests.**
```
OPT;TYP N;SKI N;MOD COM;INI;1;CHA;P
MESS;SCA QUI NEW;M
REA NEW REA WAI MESS;SCA WAI REA THR NUM:U RS
SCA /DES/LONG BRO/LONG DOW /PROTO:B
```
TAPCIS waits for these prompt tails: `Forum !`, `um !`, `es !`, `ce !`, `lex!`.
Abbreviations: commands match on unique prefixes (`REA`, `SCA`, `MESS`). Accept any prefix of at least 2–3 characters [I].
Earlier styles:
- The 1983 SIGs used a `Function:` prompt.
- The 1987 Navigator sent `OP;SM N;RE L;ED SED;UM OFF;S`, then `SSA`, `RM` (→ `No marked messages present`) and `DL1` [V, S2].
Not confirmed by any primary source: `RS`/`RT`/`RN`/`RI`/`RTH` as standalone shortcuts (only TAPCIS's `RS` is attested) [I].
### 4.6 Leaving a forum [V, S3]
```
Exiting at 15-Jan-88 03:54:57
Last message in forum: 34949
Last message you've read: 0
Thank you for visiting Journalism Forum
```
### 4.7 Libraries [V, S2 1987; S4 1988; S10]
```
DL 1 !S [74065,16]OASIS /DES
[74065,16]
OASIS/binary 03-Oct-87 73856 160
Keywords: OASIS FINDER SHAREWARE
Here it is, the latest version of Oasis...
DL 1 !DOW [74065,16]OASIS /proto:xmodem
Starting XMODEM transfer
Please initiate XMODEM transfer
and press <CR> when the transfer
is complete.
```
BROWSE (1988):
```
[76703,242]
TAKJOB.HOM 05-Dec-87 1972 Accesses: 42
Keywords: JOB WORK HOME
...
Enter command, N for next file
or <CR> for disposition menu !
```
**File entries:**
- Name: 6.3 format, owned by the uploader's PPN: `[ppn]FILENM.EXT`, with a `/binary` tag for binary files.
- Fields: date, size, accesses, keywords, description (at most **465 chars** [V, S10]).
- The prompt shows the library: `DL 1 !` (1987) or `LIB !` (1989).
**Uploading:**
1. `UPL name/PRO:B/TYP:ASC`.
2. Prompts end in `ter:`, `hed:`, `rds:` (Keywords:) and `tle:` (Title).
3. Then `Is this okay (Y or N)?` [V, S10 UPL.SCR].
**Download protocol menus:**
- 1986 menu: doc 03 §7.1.
- 1993 Mail menu: `1 XMODEM (MODEM7) protocol 2 CompuServe 'B' protocol 5 Kermit 6 CompuServe Quick 'B' protocol` [V, S6]. The gaps in the numbering are original.
**Library announcement layout (1994)** [V, S7]:
```
GUILIB.LHA/Bin Bytes: 175965
Title : ...
Keywords: ...
```
### 4.8 Conference (CO) [V]
- Line format, 1989 [S14]: `(2,Irv) Hi Phil, nice to see you on CIS...`, meaning `(room,name)`.
- Line format, 1996 [S15]: `(19-11,Paladin) ...`, meaning `(room-job,name)`.
- `/users 2` [S14]:
```
User User ID Nod Rm Name / Forum Area
---- ------------ --- --- -----------------
12 70003,4205 CSD 2 Steve L.
```
---
## 5. CompuServe Mail (EasyPlex)
### 5.1 EasyPlex 1988 [V, S5]
```
EasyPlex
Date: 13-Jan-88 20:18 PST
From: Tom Sponheim [73557,3105]
Subj: Hello
```
Address book entries look like `1 JOHN EDWARDS 71251,2457`.
### 5.2 CompuServe Mail 1993, menu mode [V, S6]
```
CompuServe Mail Main Menu
1 READ mail, 23 messages pending
2 COMPOSE a new message
3 UPLOAD a message
4 USE a file from PER area
5 ADDRESS Book
6 SET options
9 Send a CONGRESSgram ($)
Enter choice !1
CompuServe Mail Read Menu
1 INTERNET:paulg@tplrd.tpl.oz.au/comp.sys.amiga.misc #24609 - to be or not to be
* Expire:(+78) *
4 John Steiner/Bug Bytes #66
...
0 READ ALL 23 messages
Enter choice or <CR> for more !
```
**Reading a message:**
- Header: `Date: 18-Apr-93 22:19 EDT` / `From: Deron Kazmaier [76317,3633]` / `Subj: …`.
- Internet senders appear as `From: INTERNET:user@host`.
- At the end: `Last page. Enter command or <CR> to continue !`.
**Action Menu:**
`1 DELETE this message`, `2 FILE in PER area`, `3 FORWARD`, `4 REREAD message`, `5 REPLY`, `6 SAVE in mailbox`, `7 DOWNLOAD message`.
**Downloading mail:**
`1 messages and 227840 characters ready for download`, then the protocol menu, then `*** File Transfer Completed! ***`.
**Binary items** are tagged `* Binary * Expire:(+5) *`.
**End of the read list:**
`Last page. Enter choice or M for CompuServe Mail main menu !`.
### 5.3 Command mode [V, S10]
- Prompt: `Mail!`. Entry text: `CompuServe Mail` / `No messages pending`.
- Error: `% Invalid command`.
- Mode menu: `Mail Mode Menu 1 MENU 2 PROMPT 3 COMMAND`, followed by `Make changes permanent for future Mail sessions ? (Y or N)`.
- Settings: `set edit noline`, `set page off`.
- Return receipts cost a $0.25 surcharge [P].
**Address forms:**
| Form | Meaning |
|---|---|
| `70000,123` | Member |
| `INTERNET:user@host` | Internet (inbound mail also arrives as `user.id@compuserve.com`) |
| `FAX:301-3877322` | Fax gateway |
| `POSTAL` | Laser-printed postal letter |
| `MCIMAIL:` / X.400 (`ems`) | Other mail networks [P] |
| `MHS:` | Real, but the syntax is unverified [I] |
The name and address are written `Name >ADDRESS` [V, S10].
---
## 6. CB Simulator
### 6.1 Commands, from `/HEL` (1982) [V, S13]
```
/TUN # - Tunes channel # (1-36)
/MON 1,4 - Listen to extra chnls
/UNM 7,3 - Unmonitor channels
/STA - Type channel status
/TIM - Type time, day, and date
/UST - User STatus typeout
/EXI - Exit CB Simulator
/WHO - Type PPN of last talker
/HAN - Change handle
/SCR xyz - Scramble on key "xyz"
/SMC xyz - Scr & Monitor Clear
/XCL xyz - Xmt CLear; unscr rcvr
/UNS - Unscramble (both clear)
/SQU abc - Squelch handle "abc"
/JOB - your job #
/HELP - Type this message
```
Also mentioned: `/TALK` (private chat), `/ROLL` (dice, prints `5,1`), `/GAG` (staff only), and `exceeding job limit` when the same ID enters twice [P, S17].
### 6.2 Output samples [V, S13, S17]
```
/TIM
11:09:43 PM EDT Friday, October 22, 1982
/UST
Job User ID Nod Ch Tlk Handle
--- ------- --- -- --- ------
88 70015,727 NYC 30 SYSOP/Ron
```
The later `/UST` format (1986):
```
Job User Id Ch. Node Handle
--- ---------- --- ---- ------
1) 12 70003,1295 17 CSG Red Leather
2) 133 70006,1293 1s BAF Surf's Up!
3) 69 76703,1211 Tlk BOO JOE CUFFS
```
In that format, `s` means scrambled and `Tlk` means in a `/TALK`.
### 6.3 Model
- **Bands and channels:** channels 1–36 per band. There was a General band plus later bands (an Adult band; a modern recreation uses bands A/B).
- **Users:** each has a **handle** and a **job number**, which is the session's job number on the host.
- **Scrambling:** a per-key "encryption". Users with the same key see clear text; everyone else sees garbage [I: implement as a deterministic scramble].
- **Line format:**
- forum conferences use `(room,name) text` [V];
- a 1985 magazine quotes CB as `(Old Man) Does anyone know what time it is?`;
- **the CB format is unresolved** — choose `(ch,Handle)` for consistency with forums [I].
---
## 7. Billing (for display only)
| Year | Rates |
|---|---|
| 1981 | 300 baud: $5.00/hr non-prime, $22.50/hr prime |
| 1986 | Non-prime $6 (300) / $12.50 (1200); prime $12.50 / $15 |
| 1987 | $6 (300) / $12.50 (1200/2400); prime surcharge dropped |
| ~1990 | $6.50 / $12.75 |
| Feb 1994 | Standard plan: $8.95/month for basic services, connect $4.80/hr (≤2400) and $9.60/hr (9600/14400). Alternative plan: $2.50/month plus $6.30 / $12.80 / $22.80 per hour. Non-prime is 1900–0800 weekdays and all weekend. |
Sources: trs-80.org, Compute! #78, START v2n3, S8.
**Menu markers:**
- `+` marks extended (hourly) services and `$` marks premium surcharges.
- `(FREE)` marks free pages.
- The Executive Option added a $10/month minimum, 6-month file storage and exclusive databases.
**GO BILLING (1988)** [V, S3]:
```
CompuServe BILLING
BILLING INFORMATION
1 Current Rates
2 Reviewing Your Charges
...
6 Order Executive Option
Enter choice !2
CompuServe CHARGES
1 Explanation
2 Account Balance
3 Billing History
USAGE DETAILS
4 Current activity
5 Previous activity
6 Mail Hardcopy ($)
Enter Choice !2
CompuServe CHARGES
Searching Billing Files ...
ACCOUNT BALANCE
Balance as of 12/26/87 $.00
Activity since 12/26/87:
Payments -.00
Charges $1.11
...
Balance as of 1/12/88 $1.11
========
Last page !
```
The 1994 `NEWBIL` "Enhanced Billing Display" menu: `1 Account Balance`, `2 Pricing Plans & Clubs`, `3 Mail and Other Allowances`, `4 Account History`, `5 Detailed Session Activity`, `6 Hardcopy Requests`.
**For the revival:** bill in fake period dollars from recorded connect time. This adds charm and costs nothing.
---
## 8. GO words seen in sources
| Category | GO words |
|---|---|
| Navigation and help | `CIS` `TOP` `NEW` `FIND` `HELP` `MEMBER` `FREE` `BASIC` |
| Account | `RATES` `BILLING` `CHARGES` `NEWBIL` `EXECUTIVE` `PHONES` `DEFAULT` `TERMINAL` `PROFILE` `PASSWORD` |
| Mail | `MAIL` `EASY` `MAILRATES` |
| Chat and forums | `CB` `CB-1` `FORUMS` `PRACTICE` `HELPFORUM` `CHALLENGE` |
| News and markets | `WEA` `QUO` `BASICQUOTE` `ENS` (Executive News Service, $) `OLT-90` (Online Today) `APN`/`APV` (AP) |
| Travel | `EAASY` (EAASY SABRE) `OAG` (Official Airline Guide) `PDG` `AWX` (aviation weather RLE maps) |
| Shopping | `MALL` |
| Reference | `PHONEFILE` `DIRECTORY` |
| Personal | `PER` (Personal File Area) |
| Forums | `MACUS` (MAUG) `JFORUM` `TAPCIS` `AMIGATECH` `AMIGAUSER` `CIMSUP` `WCIMSUP` `MCIMSUP` `NAVSUP` `ATARI8` `ATARIPRO` `IBMCOM` `PCMAGNET` |
| Games | `GAM-11` (Adventure), MegaWars |
---
## 9. Gaps
- No verbatim capture of CB band selection or of CB line format with channel numbers.
- The `MHS:` address syntax.
- The exact text for a bad password (two candidates in §1.4).
- `RS`/`RT`/`RN` shortcuts and QUICKSCAN output format (TAPCIS uses `SCA QUI`).
- **Next sources to mine:**
- Computer History Museum scans of CompuServe manuals (<https://archive.computerhistory.org/resources/access/text/2024/06/102751645-05-01-acc.pdf>, also 102751668, 102805861; OCR needed);
- *The Complete Handbook of CompuServe*;
- the 32 GB host disk images (doc 01 §2);
- <https://compuserveweb.com/>, a live recreation, to compare against.
+353
View File
@@ -0,0 +1,353 @@
# 03 — Link Protocols: A, B, B Plus, ESC I, VIDTEX
These protocols run *inside* the character stream of a terminal session. The host switches into them for file transfers, terminal identification and graphics. They also carry the GUI clients' HMI traffic (see [04](04-cim-hmi.md)). A reimplementation must have a correct B+ engine. Without it, nothing downloads, and CIM does not work at all.
Confidence tags: **[C]** confirmed from a spec or reference code · **[I]** inferred.
## Sources
| Key | Source |
|---|---|
| R | Russ Ranshaw, *The CompuServe B Plus Protocol*, 18 Nov 1993. CompuServe's own spec. <https://discmaster.textfiles.com/view/16904/SOS-DFUE.ISO/programm/texte/bplus.doc> |
| W | Steve Wilhite, `bp.c` / `dte.c` (1985), Classic B reference code. comp.sources.unix, Mar 1986. <https://www.tuhs.org/Usenet/comp.sources.unix/1986-March/002804.html> |
| O | Steve Sneed, OOBPLUS 1.0 (1991), Pascal B+ used by OzCIS. <https://discmaster.textfiles.com/view/16184/MAX_PROGRAMMERS.iso/PASCAL/OOBPLS10.ZIP> |
| A | *Protocol Notes: CIS A Protocol* (1982/83). <https://discmaster.textfiles.com/view/19793/2015.02.ftp.barnyard.co.uk.tar/ftp.barnyard.co.uk/cpm/walnut-creek-CDROM/CPM/CIS/PROTCISA.TXT> |
| T | Tandy, *TRS-80 Videotex Software Specifications (26-5000)*. <https://colorcomputerarchive.com/repo/Documents/Manuals/Hardware/TRS-80%20Videotex%20Software%20Specifications%20(Tandy).pdf> |
| M | *Antic*, Aug 1986, "Going Online" (verbatim download transcript). <https://www.atarimagazines.com/v5n4/GoingOnline.html> |
| P | HP Palmtop Paper CIS forum guide. <https://www.palmtoppaper.com/ptphtml/1/ptp10025.htm> |
| Wk | Wikipedia, "B protocol". <https://en.wikipedia.org/wiki/B_protocol> |
The two spec check values were recomputed and match R. Sample packet `10 42 37 54 44 41 53 2E 43 03` gives standard checksum **0x2A** and XMODEM-CRC (init 0xFFFF) **0x57FF**. Use them as unit-test vectors.
Byte names used below: `SOH`=01, `ETX`=03, `EOT`=04, `ENQ`=05, `SI`=0F, `SO`=0E, `DLE`=10, `DC1`=11, `DC3`=13, `NAK`=15, `ESC`=1B, `RS`=1E.
---
## 1. Lineage
| Protocol | Era | Notes |
|---|---|---|
| A | 1980–82 | Original. Tied to the AgVision/VideoTex projects [Wk]. B replaced it in 1982 [R]. |
| Classic B | 1982– | Stop-and-wait, 512-byte buffer, 8-bit additive checksum. |
| Interim B / "Quick B" | mid-80s | Adds `+` parameter negotiation and send-ahead. [O] calls a session "Quick B" once a `+` packet is seen. [I] |
| B Plus (B+) | late 80s–90s | Full negotiation: windows, 2 KB blocks, CRC-16/32, configurable quoting, download resume, file info, transport layer. **WinCIM and OzCIS use this.** |
---
## 2. A protocol [C, A]
- 8N1. The host enters protocol mode with **SI** and leaves it with **SO**. The terminal strips parity when looking for SI.
- Host commands inside protocol mode:
- `ESC I`: identify (§5)
- `ESC A`: start a transfer
- `ESC L`: CP/M memory load
- ACK = `.` (2E), NAK = `/` (2F). If nothing comes back, the host re-sends ETX up to 4 times, then aborts. Ctrl-U from the terminal aborts.
- Header record: `SOH <rec#> <U|D> <A|B> <filespec> CR [LF] ETX <ck>`. Data records: `SOH <rec#> <data> ETX <ck>`. The last data record carries `EOT` just before ETX. SO ends the session.
- Record numbers are ASCII `1`…`9`,`0`,`1`… [I]
- Masking: a data byte < 0x20 is sent as `DLE, b+0x40`. Framing characters are sent raw.
- Checksum: same rotate-add-carry as B (§3.3). It covers the bytes after SOH, excluding ETX, and is computed on unmasked values. A checksum < 0x20 is masked.
Priority for us: **low**. Implement only for completeness (period 8-bit clients).
---
## 3. Classic B
### 3.1 Initiation [C, R §D/§L, W]
The host is always the initiator. While the terminal is in plain terminal mode, the host sends **ENQ**. The terminal's reply tells the host which B version it speaks:
| Client | Reply to ENQ | Bytes |
|---|---|---|
| Classic B | `DLE '0'` | `10 30` |
| Interim B | `DLE '+' DLE '0'` | `10 2B 10 30` |
| B Plus | `DLE '+' '+' DLE '0'` | `10 2B 2B 10 30` |
| B Plus, relaxed timing | `DLE '+' '+' 'R' DLE '0'` | `10 2B 2B 52 10 30` (host doubles its timeouts) |
On ENQ the terminal resets to seq `'0'`, a 512-byte buffer, the standard checksum and the default quote set, and **stays in terminal mode**. It only enters protocol mode when it sees `DLE 'B'`.
Host loop: send ENQ, at most 5 tries. Parse the reply:
- each `+` before the `DLE digit` raises `PlusSeen`, then `PlusPlus`;
- `R` sets relaxed timing;
- the digit seeds the sequence numbers.
Then send a `+` packet (§4) if any `+` was seen, otherwise go straight to the `T` packet.
### 3.2 Packet framing [C, R §C1, W]
```
DLE 'B' <seq> <type> <body…quoted> ETX <check…quoted> [RS]
10 42 30–39
```
- **seq**: one ASCII digit, `'9'` wraps to `'0'`. The host's first packet after the ENQ reply `DLE '0'` is `'1'`. The counter is shared by both directions: the receiver adopts the received seq, and its next sent packet uses seq+1 [I from W/O]. The Transport Layer (§4.6) keeps separate counters.
- **check**: covers seq + type + body + ETX, computed on the **unquoted** bytes (the quoting DLEs are not included). The check bytes are quoted themselves if they fall in the quote set.
- **size**: Classic B has a 512-byte buffer *including* the type byte, so at most 511 data bytes per `N`. B+ allows 0–2048 data bytes.
- **RS** follows the check value only when CM is 2 or 3 (§4.3).
### 3.3 Standard checksum [C, R §M, W]
```go
func bChecksum(p []byte) byte {
ck := 0
for _, b := range p {
ck <<= 1
if ck > 0xFF { ck = (ck & 0xFF) + 1 } // 8-bit rotate
ck += int(b)
if ck > 0xFF { ck = (ck & 0xFF) + 1 } // end-around carry
}
return byte(ck)
}
```
### 3.4 Quoting [C, R §C2, W]
- Encode 0x00–0x1F as `DLE, c+0x40` (ETX becomes `10 43`).
- Encode 0x80–0x9F as `DLE, (c&0x1F)+0x60` (0x93 becomes `10 73`).
- Decode: after a DLE, if the next byte < 0x60 the value is `c & 0x1F`, otherwise `(c & 0x1F) | 0x80`. **Decoders must accept a quoted byte even if it is not in the negotiated set.**
Default sets:
- Wilhite's Classic sender quotes `03 05 10 11 13 15`.
- R §L lists all of 0x00–0x1F as the Classic default.
- The CIS host's B+ set is `03 05 10 11 13 15 1E 91 93`.
**Host policy [I]:** quote all of 0x00–0x1F for Classic clients. That is always safe.
### 3.5 Packet types [C, R §C4, W, O]
| Type | Body | Meaning |
|---|---|---|
| `T` | `<dir><dtype><filename>` | Transfer control. dir: `D` download (host→term), `U` upload, `C` close/EOF. dtype: `A` 7-bit ASCII (EOL conversion allowed), `B` binary, `I` image. Examples: `TDBFOO.ZIP`, `TUAREADME.TXT`, `TC`. |
| `N` | data | File data. A zero-length `N` is legal and is **not** EOF. |
| `F` | `<code>[text]` | Failure. The seq is ignored. Codes: `A` user abort, `C` capacity, `E` processing error, `I` I/O, `M` upload file missing, `N` unimplemented packet type, `S` sequence, `r` resume failure. The receiver ACKs it, then both sides leave protocol mode. |
| `+` | parameters | B+/Interim negotiation (§4.1). |
| `M` / `L` | data | Transport Layer: `M` more data follows, `L` last packet of a block. |
| `Tr` `Tf` `TI` | — | B+ resume and file info (§4.5). |
### 3.6 Control sequences [C, R §D, W]
| Sequence | Bytes | Meaning |
|---|---|---|
| ACK | `DLE <digit>` | Last good seq received |
| NAK | `15` | Bad check or unexpected seq |
| WACK | `DLE ';'` (`10 3B`) | Wait. The sender pauses (W sleeps 5 s). |
| ENQ in session | `05` | Peer replies `DLE <last seq>` |
| Duplicate packet | — | Re-ACK it, discard it |
| Panic abort | `10 10 10 10` | Four DLEs from the terminal |
| Fallback detect | `DLE '+'` while waiting for an ACK | Terminal fell back to terminal mode: abort |
- Response to a NAK: Classic retransmits the last packet. Interim and B+ send `ENQ ENQ`, wait for two identical ACKs, then resend everything unacked.
- Timeouts: 10 s per character, at most 10 errors. On a slow link the receiver should not NAK on timeout.
### 3.7 Flows [I from W/O, consistent with R]
Download:
```
H→T 05
T→H 10 30 (or 10 2B 2B 10 30 → §4.2 negotiation first)
H→T DLE B '1' "TDB" name ETX ck
T→H 10 31 client opened the file (or sends F)
H→T DLE B '2' 'N' data… ETX ck
T→H 10 32 … repeat …
H→T DLE B 'n' "TC" ETX ck
T→H DLE 'n' done; client is back in terminal mode
```
Upload: the host sends `TU<A|B><name>`. The **client does not ACK `TU`**: its first `N` packet (seq+1) is the implicit acknowledgement. The host ACKs each `N`, and the client ends with `TC`, which the host ACKs.
---
## 4. B Plus extensions [C, R unless noted]
### 4.1 Transport Parameters packet (`+`)
- Always sent with the standard checksum.
- While it is in flight, B+ quotes 0x00–0x1F **and** 0x80–0x9F (Interim quotes 0x00–0x1F only).
- Body = binary bytes in this order. Missing trailing fields default to 0, and extra fields are ignored.
| # | Field | Values |
|---|---|---|
| 1 | WS | Window Send: 0 = one outstanding, 1 = two … |
| 2 | WR | Window Receive, same encoding |
| 3 | BS | Block size ÷ 128: 0 or 4 = 512, 8 = 1024, 16 = 2048. R's text says "0x16" for 2048; that is a typo. |
| 4 | CM | Check method: 0 standard, 1 XMODEM CRC-16, 2 CCITT CRC-16, 3 CRC-32 |
| 5 | DQ | Obsolete quote level, ignored if Q1–Q8 are present. 0 = {00 03 05 10 11 13 15}; 1 = {03 05 10 11 13 15}; 2 = level 1 + {91 93}; 3 = all of 0x00–0x1F and 0x80–0x9F |
| 6 | TL | 1 = Transport Layer supported |
| 7–10 | Q1–Q4 | Bitmask for 0x00–0x1F. Q1 bit7 = 0x00 … bit0 = 0x07; Q2 = 08–0F; Q3 = 10–17; Q4 = 18–1F |
| 11–14 | Q5–Q8 | Same bitmask for 0x80–0x9F |
| 15 | DR | Download resume: 0 none, 1 `Tr`, 2 `Tr` + `Tf` |
| 16 | UR | Upload resume. Not described; [O] says "not supported by CIS". |
| 17 | FI | 1 = `TI` file-info packet supported |
- **CIS host values:** Q1–Q4 = `14 00 D4 02`, Q5–Q8 = `00 00 50 00`. That decodes to {03 05 10 11 13 15 1E 91 93}.
- **OzCIS client values [O]:** WS=1 WR=2 BS=4 CM=1 DQ=1 TL=0 Q=`14 00 D4 00 00 00 00 00` UR=0 FI=1.
### 4.2 Negotiation
```
H→T ENQ
T→H 10 2B 2B 10 30
H→T DLE B '1' '+' <host params> ETX ck
T→H DLE B '2' '+' <client params> ETX ck (implicit ACK of '1') [I]
H→T 10 32
```
Both sides then compute the same result:
- `sendWin = min(ownWS, peerWR)` and `recvWin = min(ownWR, peerWS)` (note the cross).
- `min()` of BS, CM, TL, DR, UR and FI.
- **Bitwise OR** of the quote masks.
The very next packet already uses the negotiated values.
### 4.3 Check methods [C, R §C3/§M]
| CM | Algorithm | Wire |
|---|---|---|
| 0 | §3.3 checksum | 1 byte |
| 1 | CRC-16 poly 0x1021, MSB-first, **init 0xFFFF**. `crc = tab[((crc>>8)^b)&0xFF] ^ (crc<<8)`. CRC over data + received CRC = 0. | 2 bytes, high byte first |
| 2 | CCITT CRC-16, reflected poly 0x8408, preset 0xFFFF. `crc = tab[(crc^b)&0xFF] ^ (crc>>8)`. Send the complement, low byte first. Receiver residue 0xF0B8. | 2 bytes + RS |
| 3 | CRC-32 (zlib/PKZIP, 0xEDB88320), preset −1, complemented, LSB first. Residue 0xDEBB20E3. | 4 bytes + RS |
In Go: CM=3 is `hash/crc32.ChecksumIEEE`. CM=1 is CRC-16/CCITT-FALSE. CM=2 is CRC-16/X-25.
### 4.4 Sliding window [C, R §H/§I]
- The sender keeps one buffer per unacked packet. If the window is full, it waits for an ACK.
- An ACK for an older packet means ACKs were lost: release everything up to and including that packet.
- On a NAK: `ENQ ENQ` resync, then resend everything unacked.
- Back-off: +3 per retransmit, −1 per ACK. At ≥ 12, drop to stop-and-wait.
- Suggested block size by speed: 300 bps → 128, 1200 → 512, 2400 → 1024, 9600 → 2048 with a window of 4–5. Over telnet, use 2048 with the window the client offers.
### 4.5 Resume and file info
- **`Tr<len> <crc> `**: sent by the client in reply to `TD` when it has a partial file. The fields are ASCII decimal, each followed by a space. The CRC uses the session algorithm, or XMODEM CRC-16 init −1 if the session uses the plain checksum.
- If the host's CRC over its first `len` bytes matches, it continues with `N` packets from that offset, or sends `TC` if the file is already complete.
- On mismatch: `Fr` if DR=1, or `Tf` if DR=2 (the client ACKs, then the full file follows).
- **`TI`**: sent by the file sender when FI=1. Body: `TI <dtype> <compression=0x00> <length> <tz> <cdate yyyymmdd> <ctime secs> <mdate> <mtime> <namelen as a binary byte> <truename>`, space-separated ASCII decimal. Spec example: `A\x0055387 300 19880422 52480 0 0 \x09BPLUS.DOC`.
### 4.6 Transport Layer (TL=1)
- An application escape sequence starts it. **That escape sequence is undocumented in R.**
- It uses separate send and receive sequence counters, carries data in `M`/`L` packets, and ends with `F`.
- This is the carrier for CIM/HMI. A reverse-engineered WinCIM 3 server reports host params `04 04 02 00 00 01` (TL=1), and HMI messages in `L` packets, entered via `ESC [ > … p`. See [04](04-cim-hmi.md) §2.4–§4.
### 4.7 Line requirements
- An 8-bit clean path is required. The client must honour XON/XOFF from the host, which is why 11, 13, 91 and 93 are always quoted.
- **Over telnet [I]:**
- Negotiate `WILL/DO BINARY` in both directions.
- Double any 0xFF data byte (0xFF is not in any quote set).
- Strip the NUL from CR-NUL on input.
- Otherwise B+ streams get corrupted.
---
## 5. Terminal identification: ESC I
### 5.1 Original VIDTEX [C, T]
The host sends `ESC I`. A Tandy VIDTEX terminal answers `RS4` + CR.
### 5.2 CIS 8-bit era [C, A]
Example reply: `#CPM MYSYSTEM,CC,HC,PA,PL,` + CR.
- `CC` = cursor control, `HC` = hard copy, `PA` = A protocol, `PL` = L protocol.
- The older MNEXEC form was `<lo page>,<hi page>,<system>,<&CPM>,<D>`.
### 5.3 B Plus era [C, R §N]
Order: the host normally runs the **ENQ test first**, then sends `ESC I` if the client speaks B.
```
'#' <PID>:<Ver>:<OS> ',' {Fcode ','}* '+' <checksum decimal> CR
e.g. #WINCIM:1.0.b7:W31,… (PID ≤6, Ver ≤12, OS ≤3 chars)
```
| Group | Codes |
|---|---|
| Screen | `AC` ANSI colour · `CA` ANSI/VT100 cursor · `CC` VIDTEX/VT52 cursor · `CW` wide characters (`ESC m` on / `ESC l` off) · `SSyx` screen size (y = lines+31, x = cols+31, e.g. `SS7o` = 24×80; unused by CIS) |
| Graphics | `GF` GIF · `GH` hi-res RLE · `GM` med-res RLE · `GJ` JPEG · `NF` NAPLPS · `GIvcpwwwhhh` GIF capabilities |
| Protocols | `AP` Application Protocol (**the HMI flag** [I]) · `CB` capture buffer · `PB` B protocol · `PX` XMODEM |
| International | `CHd` charset · `COddd` country · `LAd` language |
| Misc | `HC` hard copy · `XX` ignored · `DT` seen in real replies, meaning undocumented |
**Checksum:** the 16-bit sum of every character from `#` through `+`, sent as ASCII decimal. On a mismatch the host re-sends `ESC I` and compares consecutive replies, up to 10 tries. The spec's own example (`#PC3:3.2a:D,CC,GH,GM,GF,PB,+1035`) does **not** add up; the plain sum is 1680. OzCIS uses the plain sum.
**Host policy [I]:**
- Accept the reply if the sum matches, or if two consecutive replies are identical.
- Treat the ENQ reply as the authoritative B test; `PB` is advisory.
- Parse leniently: `#`, then comma-separated tokens, with product id first.
Real replies:
- Wilhite (pre-B+): `#IB1,PB,DT\r`
- OzCIS: `#OZ3,OzCIS1,AC,CA,SSxx,GF,PB,DT,+<sum>\r`
### 5.4 GIF interrogation [C as client behaviour, O]
- The host sends `ESC [ > 0 g`. The client replies with a capability string such as `#89a;1;0,320,200,4,0;0,640,200,2,2;…\r`.
- `ESC [ > 1 g` announces a GIF, which then arrives as a B+ download (`+`, then `T…`) straight into the viewer. The host waits for a CR once the image has been shown.
---
## 6. VIDTEX host escape sequences [C, T]
| Bytes | Function |
|---|---|
| `ESC A` / `ESC B` / `ESC C` / `ESC D` | Cursor up / down / right / left |
| `ESC H` | Home |
| `ESC J` | Clear to end of page |
| `ESC K` | Clear to end of line |
| `ESC Y <row+0x20> <col+0x20>` | Position cursor (`1B 59 24 26` = row 4, col 6) |
| `ESC j` | Clear page, cursor stays |
| `` ESC ` <c> `` | Change cursor symbol |
| `ESC G 4` | Semigraphics-4 mode |
| `ESC G M` | Medium-res RLE graphics |
| `ESC G H` | High-res RLE (256×192) (secondary source) |
| `ESC G N` | Back to alphanumeric mode |
| `0C` / `0D` / `0A` / `09` / `08` | Clear screen / CR / LF / tab / backspace |
**RLE graphics:**
- After `ESC G M` or `ESC G H` the data is byte pairs `(count_off+0x20, count_on+0x20)`, run-length encoding a monochrome image.
- Only `ESC G N` is recognised while in graphics mode.
The VIDTEX set is essentially VT52-compatible, so the host can use the same cursor codes for clients that report `CC`.
---
## 7. How the host triggers a transfer (terminal UI)
### 7.1 Verbatim 1986 forum download [C, M]
```
1 XMODEM (MODEM7) protocol
2 CompuServe 'B' protocol
3 CompuServe 'A' protocol
4 DC2/DC4 CAPTURE protocol
0 Abort transfer request
Enter choice: 1
Starting XMODEM transfer
Enter a carriage return when
transfer is complete
```
### 7.2 Later additions [C, P]
By about 1991, command mode offered Xmodem, Kermit and CIS-B (`LIB n`, `BRO`, `DIR`, `DOW <file>`). YMODEM likely came later. [I]
### 7.3 Host mechanics
| Choice | Host action |
|---|---|
| CIS B | Immediately ENQ → (`+` negotiation) → `TD…`. No user action needed: clients auto-start on `DLE B`. |
| XMODEM / Kermit | Print the start message, run the standard protocol, then wait for CR. |
| DC2/DC4 capture | `DC2` (12), raw text, `DC4` (14). Conventional capture on/off. [I] |
| A | `SI ESC A …` per §2 |
---
## 8. Gaps
- No public modern B+ implementation was found. A FreeBSD port `bpl+` (1989) exists but could not be fetched. **[O] and [W] are the best references to port into Go.**
- The Application Protocol / Transport Layer start escape is undocumented in R. A 2026 reverse-engineering project reports `ESC [ > 0 q` / `ESC [ > 3;3 p` then ACK (doc 04 §2.4). Confirm on the wire.
- The meaning of `DT` is unknown, as is the full VIDTEX 4.x escape set.
- Not retrieved: the Dr. Dobb's article on B, Jul 1986 (Levi Thomas & Nick Turner, vol. 11 no. 7, pp. 54–59).
+204
View File
@@ -0,0 +1,204 @@
# 04 — The GUI Service: CIM clients and HMI
The graphical clients (DOSCIM, WinCIM, MacCIM, OS/2 CIM, CSNAV/MacNAV, OzWIN, TAPCIS 6.1) did not scrape text. They spoke **HMI (Host-Micro Interface)**, a binary request/response protocol that runs **inside B Plus Transport Layer packets** (see [03](03-link-protocols.md) §4.6).
CompuServe never published the HMI spec. Everything below the B+ layer comes from reverse engineering.
Tags: **[C]** confirmed (period or primary document) · **[S]** secondary (Wikipedia, recollections) · **[RE]** from one reverse-engineering source only, not yet checked by us · **[GAP]** unknown.
## Sources
| Key | Source |
|---|---|
| E | `24high/CompuServe-Emulator`, a C# server (Sep 2026) that claims to bring WinCIM 3.x online. It was recovered by disassembling WinCIM 3.0.2 (`CCTN240C.DLL`, `CS3COR.DLL`, `CS3.EXE`). Notes in German: `HMI-PROTOKOLL.md`, `SECURE-LOGIN.md`, `NAECHSTER-SCHRITT.md`, `POST.md`, `SUCHE.md`. <https://github.com/24high/CompuServe-Emulator> |
| F | CompuServe HMI developer FAQ, Nov 1994. <https://discmaster.textfiles.com/view/21536/03-Comm.zip/hmidev.txt> |
| N | Rick Wilkes, CIS HMI/NISA migration FAQ, Dec 1995. <https://discmaster.textfiles.com/view/6764/CDA1_96.ISO/novell/cishmi.faq> |
| R | Ranshaw, B Plus spec (1993). See doc 03. |
| P | US Patent 5,737,538 (HMI "protocol data units"). <https://patents.justia.com/patent/5737538> |
| Wc | Wikipedia, "CompuServe Information Manager". <https://en.wikipedia.org/wiki/CompuServe_Information_Manager> |
> **About source E.** It is new (0 stars when found) and is the only detailed source for the HMI layer. Treat it as a strong lead, not ground truth: check each claim against a real WinCIM under Wine or in a VM. The repo also redistributes CompuServe's 1996 connection scripts and decompiler output. **Cite it; do not copy its files into this project.**
---
## 1. What is publicly confirmed
From the developer FAQ [F]:
- HMI is "a set of protocols" with "an application-level error-correcting transport layer".
- It avoids "pattern-matching" and allows asynchronous host data.
- The toolbox was available free, under NDA and licence. CompuServe "will not release the spec or source to the public".
- Developers were pointed to the IBM Communications Forum Lib 10 for the B Protocol, and the Graphics Support Forum Lib 16 for GIF.
From the B Plus spec [R]:
- The `+` packet's 6th field, **TL**, is 1 when an application runs under the Transport Layer.
- Transport data travels in **`M`** (more follows) and **`L`** (last of block) packets. An `F` packet ends the transport session.
- The Transport Layer is entered with a "CompuServe Application Protocol escape sequence" from the host and an escape reply from the terminal. **The bytes are not given.**
- A client advertises support with the `AP` F-code in its `ESC I` reply.
From the 1995 migration FAQ [N]:
- In 1995–96 forums moved from the 36-bit hosts to new **"NISA" hosts (Windows NT on Intel)**. These were **HMI-only**: no ASCII, and telnet terminal sessions were blocked.
- HMI clients listed: WinCIM, CSNAV, DOSCIM, OS2CIM, MacCIM, MacNAV, OzWIN, CISCOMM, TAPCIS 6.1.
- A few forums (Palmtop, Apple II, Amiga, Atari, C64) stayed on the 36-bit hosts.
- Mail got an optional, one-way HMI conversion.
So historically there were two backends: the PDP-10 hosts (ASCII + HMI) and the NISA hosts (HMI). **Our design merges them**: one core, two front ends (doc 05).
Client timeline [S, Wc]: CIM 1989 → WinCIM 1.x (1993) → 2.0.1 (1994, bundled Mosaic) → CompuServe for Windows / CS 3.0 (late 1996, the "CSi" rebrand, partly HTML) → AOL-based CompuServe 2000 / 7.0 (out of scope). **Target WinCIM 2.x and 3.0.x first.**
---
## 2. Connection and login
### 2.1 Transport [RE, E]
- WinCIM can connect over **TCP port 4144**. CIS.INI settings:
```
[Connector (CIS Connection)]
CommType=WINSOCK
WinsockCommType=Local
HostIPAddress=…
```
SANS lists port 4144 as "wincim" (<https://isc.sans.edu/port/4144>).
- **Our server should listen on 4144 for CIM and on 23 (or 2323) for terminals.** Both run the same login state machine; see doc 05.
- Host banner: `\r\nCONNECT 9600\r\n\r\nHost Name: `.
- The client's connection scripts drive the dial-up login, so the host prompts must match exactly.
### 2.2 The script dialogue [C: CompuServe's own CSERVE.SCR v3.9.1, 1996, hosted in E]
| Host prints | Script sends |
|---|---|
| `Host Name:` | **`CPS`** by default. **`CISAGREE`** when Network = Internet. Manuals say **`CIS`**. **Accept all three.** |
| `User ID:` | `+<id><params>/INT:60 /secure:1` for secure login. The leading `+` requests SLP. Plain login: `<id>/INT:60`. Options: `/HOST` (stop at host), `/GO:PPPCONNECT` (PPP). |
| `Password:` | the password (plain login only) |
| `UIC:` | `^C` |
| `XPAD:` / `ITI:` | an X.121 address (network-specific) |
The script treats login as **successful** on any of: `CompuServe`, `ESC [ >`, `^F` (ACK), `ESC I` (answered with its ID string). `PPP:` sends it down the PPP path.
**Host error grammar.** The host prints `? LOG` or `??LOG` followed by a code. The script recognises these, so emit them verbatim:
| Code | Meaning |
|---|---|
| `INE` | Bad ID or password |
| `ISX`, `INS` | ID syntax error |
| `CAI` | Cannot auto-IRUN HMI server |
| `SIL`, `SIU`, `SNA` | System unavailable |
| `STU` | Check user ID |
| `UTL` | Too many simultaneous users |
Other messages: `? IPX` = InfoPlex unavailable, `? ICD` = PPP/gateway failure, ` NTW` = remote busy.
Network scripts: Tymnet answers its `log in:` prompt with `CPS` (`CNS` for AlaskaNet, `CNSG` for PacNet). That is not needed for TCP, but useful if we ever emulate a network node.
### 2.3 Secure Login Protocol (SLP) [RE, E: SECURE-LOGIN.md, which has test vectors]
```
H→C "RA:" HostChallenge
C→H "RB:" MicroChallenge
C→H "UR:" UserResponse
H→C "HR:" HostResponse (or "No." on failure)
```
- `K = MD5( UTF-16BE( lowercase(password) ) )`
- `UserResponse = MD5( K ‖ 48×0x00 ‖ H ‖ M ‖ K )`
- `HostResponse = MD5( K ‖ Z ‖ M ‖ H ‖ K )`. The meaning of `Z` must be checked in E.
- Values are Base64 plus a trailing 1-byte folded ones'-complement checksum, wrapped at 76 columns with CR.
- `DisableSecureLogin=ON` in CIS.INI falls back to plain `Password:`.
**Storage consequence:** the server needs K, not the plaintext password. Store K (an MD5 of the password) for SLP alongside a modern hash (bcrypt/argon2) for terminal logins. Both are derived at signup or password change. K is password-equivalent, so protect it like a secret.
### 2.4 Terminal negotiation, then HMI [RE, E; checksum rule cross-checked against R]
```
H→C ESC I
C→H #WinCIM:3.0.1:WN6,PB,DT,CA,GF,GJ,GP,GJP,GI…,+,MS,AP,PB,LA1,CH1,CO0,+4657 CR
H→C ESC [ > 0 q
C→H #1,2,3,6,8,10 (supported application modes)
H→C ESC [ > 3;3 p (select mode 3)
C→H #3,2,1,4,2,0;614
H→C ACK (0x06) → client switches to HMI over B+
```
`ESC [ >` is very probably the "Application Protocol escape sequence" that [R] leaves unspecified. The `AP` code in the ID string is the client's capability flag.
Server rule:
- **After login, a client whose ID string includes `AP` gets the HMI handshake.**
- A client without `AP` gets the ASCII top menu.
- The ID string's checksum follows the same rule as doc 03 §5.3.
---
## 3. B Plus as WinCIM uses it [RE, E]
- The host's `+` packet body is `04 04 02 00 00 01` (after the `+` type byte), read in Ranshaw's field order:
| WS | WR | BS | CM | DQ | TL |
|---|---|---|---|---|---|
| 4 | 4 | 2 (256-byte blocks) | 0 (checksum) | 0 | **1** |
This is consistent with [R]: windows can exceed 1, and **TL=1 must be set for HMI**. E's own field labels differ; trust Ranshaw's order and check on the wire.
- E recommends BS = 8 (1024-byte blocks).
- Sequence counters are separate per direction. That matches [R]'s rule for the Transport Layer, as opposed to Classic B's single shared counter.
- **Quirk:** WinCIM drops the first host message after B+ setup, so E sends the first ack twice.
- `HMIMaxTime` in CIS.INI defaults to 120 s. Send a keepalive or ack before then.
---
## 4. HMI message layer [RE, E: HMI-PROTOKOLL.md]
Each HMI message rides in B+ `L` (or `M`…`L`) packets:
```
'L' <stream:byte> <type:byte> <fields…>
```
Field encodings:
| Kind | Encoding |
|---|---|
| byte | 1 byte |
| u16 | little-endian, 2 bytes |
| u24 | little-endian, 3 bytes |
| varint | 7 bits per byte, 2 bytes |
| text | NUL-terminated |
| date/time | DOS packed date and time |
Known request/response pairs:
| Client → host | Meaning | Host → client |
|---|---|---|
| `0x0B` | session request | `0x01` ack |
| `0x0F` | keepalive | `0x01` ack |
| `0x20` | open session | `0x21` |
| `0x24` | get page | `0x27` page, or `0x09` error |
| `0x25` | select menu item | `0x27` |
| `0x34` | continue list | `0x35` |
| `0x29` / `0x2A` | article text chunks | `0x04`… then `0x2B` at end |
| `0x0D` | directory lookup | `0x0E` |
| `0x22` | service search ("Find") | ? |
| `0x07` | logoff | — |
**Page names** use the old service page IDs: `CIS:NEWPAGE`, `CIS:CONTENTS`, `CIS:CHAT`, `CIS:FORUMS`, `HOM:MAILHMI`. A GO word the user types is prefixed with `HOM:`.
This matters for the design: **HMI and ASCII share one page/menu tree.** HMI just asks for the same pages by ID and gets structured data back instead of text.
**State of E:**
- Working: login, SLP, ESC I, B+, pages and menus, article text, mail *reading*, forums, partial Find.
- **Not done:** mail send, CB/chat, file libraries (streams 2/3/6/8), the forms layer (`FORMCB.DLL`), news (`NEWS.DLL`), and message types `0x2D`/`0x2E`.
- E counts about 190 `StartMessage` call sites in the client, so the catalogue is far from complete.
---
## 5. Reverse-engineering plan for the gaps
1. **Rig.** Run WinCIM 2.x and 3.0.x under Wine or in a Win9x VM, set `CommType=WINSOCK` and point it at our server. Log every byte in both directions, with B+ decoded (doc 05 §7 calls for a wire tap in the server).
2. **Cross-check E** on the wire, message by message, before relying on it. Each confirmed item goes from [RE] to [C-wire] in this doc.
3. **Disassemble** (Ghidra) `CCTN240C.DLL` (transport) and `CS3COR.DLL` (HMI messages) to find the stream/type table: the `StartMessage` call sites.
4. **Next features, in order:** mail send → file libraries (B+ downloads inside HMI) → forum message post/reply → CB chat → forms.
5. **Older clients** (DOSCIM, WinCIM 1.x, MacCIM) may predate SLP and use other mode numbers. Test them separately.
## 6. Out of scope (for now)
- CS 3.0's HTML/web content panes, which used ordinary HTTP. Add later with a small web server.
- CompuServe 2000 / 7.0, which are AOL protocols.
- PPP dial-up (`/GO:PPPCONNECT`), which is irrelevant over TCP.
+215
View File
@@ -0,0 +1,215 @@
# 05 — Server Design: CompuServe on a D-Modem/bbs Fork
**Decision:** build the CompuServe backend as a **fork of [D-Modem/bbs](https://github.com/D-Modem/bbs)**, a Go BBS (AGPL-3.0) for telnet, SSH, TN3270 and modem callers.
The fork adds two CompuServe front ends:
- **ASCII**: the classic terminal service.
- **HMI**: the WinCIM/CIM GUI service.
Both run on top of the BBS's existing users, message base, mail, file areas, chat hub, transfers and listeners.
Protocol and UX details are in docs [02](02-terminal-ux.md), [03](03-link-protocols.md) and [04](04-cim-hmi.md).
## 1. Why D-Modem/bbs fits
Reviewed at commit `b9a9acc` (7 Nov 2026): about 87k lines of Go, Go 1.24, created 10 Oct 2026.
| CompuServe needs | D-Modem/bbs already has |
|---|---|
| Telnet and modem callers, 8-bit clean | `internal/telnet` (BINARY, ECHO, SGA, NAWS, TTYPE, IAC doubling). Modem callers come via the D-Modem softmodem, so **real dial-up into CompuServe** is possible. |
| Listeners, limits, TLS, bans, panic isolation | `internal/server` (`Listener{Kind: telnet\|raw\|rlogin\|ssh}`, per-IP limits, `handle()`), `internal/guard` |
| One core with several front ends | `internal/app` defines a `Frontend` interface. `textui` and `ui3270` are two front ends over the same screens. **This is the shape we want.** |
| Users, sessions, who's online, "jobs" | `store.User`, `bbs.Node` (node number ≈ CIS job number), calls log |
| Forum messages with threads | `store.Message{AreaID, ReplyTo, Thread, …}`, areas with groups and read/post access |
| CompuServe Mail | Private mail in `store` (`AreaID = 0`, inbox per user) |
| Forum libraries | `store.FileArea` / `store.File` (downloads count, uploader, descriptions), file store, archive readers |
| XMODEM / YMODEM / Kermit | `internal/xfer`, a protocol registry (`xfer.Protocols`) with `Send(Port, files)` / `Receive(Port, sink)` |
| CB Simulator and forum conferences | Chat hub with rooms, permanent rooms, paging (`bbs/chat*.go`) |
| DB, migrations, backups | SQLite, PostgreSQL or MySQL. Additive `ALTER TABLE` migrations (`store/schema.go migrate`). Backups. |
| Bonus | HTTP API, web terminal (xterm.js), web forum, NNTP: the CIS forums for free in a browser or newsreader |
Building all of this from scratch would take months. The CompuServe-specific work (login, page tree, the ASCII command language, B+, HMI) is about the same either way.
## 2. Constraints and risks
1. **We must fork; a library import won't work.** Everything useful is under `internal/`, and Go forbids importing `internal` packages from another module. Keep the fork mergeable (§4).
2. **The licence is AGPL-3.0-only**, with a commercial licence as the alternative. Our fork must stay AGPL. Anyone using the service over the network must be offered the source (a `GO SOURCE` page linking the repo covers this). Sending changes upstream requires their CLA (CONTRIBUTING.md).
3. **The project is young:** about 4 weeks old, about 62 commits, one org. Expect API churn. Mitigate by keeping our code in new packages and touching few upstream files.
4. **Probe collisions.** For ANSI callers the BBS sends `ENQ` (answerback) and `CSI > 0 q` (XTVERSION) at connect. Both mean something to CompuServe clients:
- `ENQ` starts the B-protocol handshake (doc 03 §3.1).
- `ESC [ > 0 q` is CIM's application-mode query (doc 04 §2.4).
**CIS listeners must skip the BBS's terminal probing** and run their own identification (`ESC I`).
5. **The app screens are BBS-shaped.** `internal/app` defines BBS menus (message areas, profile…). CompuServe's page tree, `!` prompts and forum command language are different. **We reuse the services under `app`, not its screens.** Our front ends are new packages.
## 3. Architecture
```
D-Modem/bbs fork (cmd/bbs) ← new in the fork: ★
┌──────────────────────────────────────────────────────────────────────────────────────────┐
│ internal/server listeners: telnet :23 (BBS) │ ★cis :2323 (telnet) │ ★cim :4144 (raw) │
│ │ │ │ │
│ textui / ui3270 ★cis/login (Host Name, User ID, SLP, │
│ (the normal BBS, ?LOG codes) → ★cis/termid (ESC I, ENQ) │
│ kept or disabled) │ │
│ ┌────────┴─────────┐ │
│ ★cis/ascii ★cis/hmi │
│ (pages, ! prompts, (HMI messages over the │
│ forum/mail/CB cmds) B+ Transport Layer) │
│ └────────┬─────────┘ │
│ ★cis/core │
│ (pages+GO words, forums=sections+libraries, mail addressing, │
│ CB bands/channels, billing meter, PPN user IDs) │
│ │ │
│ internal/bbs (nodes, chat hub, access) internal/store (+★ migrations) internal/xfer │
│ (+★ cisb.go: B / B+ / TL) │
└──────────────────────────────────────────────────────────────────────────────────────────┘
```
### 3.1 New packages
| Package | Purpose |
|---|---|
| `internal/cis/login` | Network dialogue: `CONNECT` banner, `Host Name:` (CIS/CPS/CISAGREE), `User ID:` parsing (`+`, `/INT:60`, `/secure:1`, `/GO:x`, `;TTY`, `*NAVIG`), password or SLP (doc 04 §2.3), `?LOG xxx` codes, banner and logoff text |
| `internal/cis/termid` | `ESC I` reply parser and checksum, the `ENQ` B-version test, `Caps` struct, GIF caps (`ESC [ > 0 g`) |
| `internal/xfer/cisb.go` | CIS B / Interim / B+ engine: quoting, checksum and CRCs, packets, window, `Tr`/`TI`, and **Transport Layer** `M`/`L` for HMI. Registered in `xfer.Protocols` as `B` and `Q` (Quick B). Upstream-friendly, since it is just another protocol. |
| `internal/cis/aproto` | A protocol (low priority) |
| `internal/cis/core` | CompuServe's domain on top of `store`/`bbs`: page tree and GO resolver, forums, libraries, mail address forms (`INTERNET:` etc.), CB model, billing meter, PPN allocation. **It knows nothing about bytes or screens.** |
| `internal/cis/ascii` | Terminal front end: line input with ^U/^V/^O/^C/^P semantics, pager, `!` prompts, BRIEF/PAGED/COMMAND/MENU modes, DEFAULT settings, forum command language (doc 02 §4.5), EDIT/LINEDIT, Mail, CB slash-commands, download protocol menu |
| `internal/cis/hmi` | GUI front end: `ESC [ >` handshake, HMI message codec (u16/u24/varint/text/DOS date), streams, dispatcher onto `cis/core` |
| `internal/cis/wiretap` | Per-session byte log of both directions, with B+/HMI decode. Viewable through the existing HTTP API. **This is the reverse-engineering tool.** |
| `content/` | The page tree (YAML): page IDs, GO aliases, menus, articles, help text, the forum list |
### 3.2 Changes to upstream files (keep this list short)
| Upstream file | Change |
|---|---|
| `internal/server/server.go` | In `handle()`, dispatch `Listener.Kind == "cis"` and `"cim"` to `cis/login.Run(...)`. Add the two kinds to the config parser (`config.go`). |
| `internal/xfer/xfer.go` | Append `B` and `Q` to `Protocols` (or register them from `cisb.go`'s `init`). |
| `internal/store/schema.go` | New tables, plus additive columns via the existing `migrate` list (§5). |
| `cmd/bbs/main.go` | Load `content/`, and add a `cis` subcommand (seed forums, allocate IDs). |
| `bbs.conf.sample` | `[listen cis]` and `[listen cim]` examples, plus a `[cis]` section. |
## 4. Fork workflow
- Fork `D-Modem/bbs` to our GitHub and clone it into this project. Add `upstream` as a remote.
- Our work lives in `internal/cis/**`, `internal/xfer/cisb*.go`, `content/` and `docs/cis/`. Upstream files carry only the hooks in §3.2.
- Rebase or merge `upstream/main` weekly, with CI running `go vet` and `go test ./...` (upstream already has `.github/workflows/ci.yml`).
- Candidates for upstream PRs, if we sign their CLA: `xfer/cisb.go` (B+ is useful to any BBS) and a generic listener-kind hook.
## 5. Data mapping onto `store`
| CompuServe | Stored as |
|---|---|
| User ID `70000,123` | `users.name = "70000,123"`, so the whole BBS login, access and who's-online machinery works unchanged on the ID. The display name goes in a new `users.real_name`. New `users.slp_key` (doc 04 §2.3). Allocate octal-only IDs from 70000,100; sysops from 76701,x. |
| Forum | New `cis_forums(id, go_word, name, welcome, version_tag, sysop_ids)`. |
| Forum section 0–17 | One `store.Area` per section: `Group = forum`, plus new `areas.cis_forum`, `areas.cis_section`. |
| Forum message number | CIS numbers messages per forum (`#: 210094`), while `store.Message.ID` is global. Add `messages.cis_num` (unique per forum, monotonic) and map `ReplyTo`/`Thread` directly. |
| Membership | New `cis_members(forum, user, name, joined, high_msg, options)`. The per-forum name comes from JOIN, and options from OPT (mode, prompt char, sections). |
| Library n | `store.FileArea` plus new `file_areas.cis_forum` / `cis_lib`. |
| File entry | `store.File` plus new `title`, `keywords`, `dtype` (A/B). `Downloads` is "Accesses". The uploader PPN is the user's name. |
| Mail | Existing private mail. Add `from_addr`/`to_addrs` (address forms), `expire`, `binary`. |
| CB | Chat hub rooms named `cb:<band>:<ch>`, forum conferences as `co:<forum>:<room>`. Handles live in `cis_handles`, and the job number is `bbs.Node.Num`. |
| DEFAULT settings | `users.prefs` (it already holds `key=value` preferences): `brief=yes paged=no top=command editor=edit width=79 …` |
| Billing | Session times are in the calls log already; a new `cis_charges` view prices them with the period rate tables (doc 02 §7). |
## 6. Connection lifecycle (on `cis` and `cim` listeners)
```
accept (server.handle) → Kind cis: telnet.New + StartNVT(binary) WITHOUT the VT/ENQ probes
Kind cim: raw TCP
▼
login.Run "\r\nCONNECT 9600\r\n\r\nHost Name: " → CIS|CPS|CISAGREE
"User ID: " → parse → SLP (if + or /secure) or "Password: " (echo off)
fail → "?LOG INE" / "?? LOGINE - Invalid entry - try again", 3 tries
▼
termid ESC I → "#…" reply (≤10 tries; none in ~2 s = dumb terminal)
▼
dispatch Caps.AppProto (AP) → hmi.Run (ESC [ > 0 q / 3;3 p, ACK, ENQ, B+ with TL=1)
otherwise → ascii.Run (banner, "Last access", mail notice, first page)
▼
session a bbs.Node is registered for its life: who's online, chat delivery, /UST job #
▼
logoff "Thank you for using CompuServe!" / "Off at …" / "Connect time = h:mm"; calls log
```
The B-protocol `ENQ` test runs when a download or graphic is about to be sent, not at login. The result is cached in `Caps`.
## 7. Interaction walkthroughs
### 7.1 Terminal user: forum read and B+ download
```
H: CONNECT 9600 / Host Name: U: CIS
H: User ID: U: 70000,123
H: Password: U: ********
H: ESC I T: (none → dumb terminal)
H: banner … "Enter choice !"
U: GO IBMCOM → core.Pages.Resolve → forum page → ascii forum UI
H: "Welcome to IBM Communications Forum, V. 4D(…)" … "Forum !"
U: LIB 10 H: "LIB !" U: BRO/LONG
H: "[76701,250]" / "BPLUS.ZIP/binary 12-Mar-93 41234 Accesses: 990" / "Keywords: …"
U: DOW BPLUS.ZIP /PROTO:B
H: ENQ T: DLE + + DLE 0 → xfer B+ ('+' exchange, TDB, N…, TC)
H: "Forum !" U: OFF → "Thank you for using CompuServe!" …
```
### 7.2 WinCIM: the Forums page
```
TCP :4144 H: CONNECT 9600 / Host Name: C: CPS
H: User ID: C: +70000,123/INT:60 /secure:1
H: RA:… C: RB:… UR:… H: HR:…
H: ESC I C: #WinCIM:3.0.1:WN6,…,AP,…,+4657
H: ESC [ > 0 q C: #1,2,3,6,8,10
H: ESC [ > 3;3 p C: #3,2,1,4,2,0;614
H: ACK, ENQ C: DLE + + DLE 0
H: '+' 04 04 02 00 00 01 C: '+' …
── HMI in L packets ──
C: 0x0B H: 0x01 ×2 (client drops the first one)
C: 0x20 H: 0x21
C: 0x24 "CIS:FORUMS" → core.Pages.Resolve("FORUMS") → hmi.EncodePage → 0x27
C: 0x0F keepalive H: 0x01 … C: 0x07 logoff
```
### 7.3 One world
- A WinCIM user posts in IBMCOM section 4. `core.Forums.Post` stores it in the section's `store.Area`, and a terminal user's `REA NEW` sees it.
- The upstream **NNTP server and web forum** expose the same messages, without extra work.
- CB:
- A terminal user on `/TUN 12` and a WinCIM chat user share the hub room `cb:A:12`.
- ASCII renders `(12,Handle) text`; HMI renders its chat message (to be reverse-engineered).
- IRC users can join the same room through upstream's ircd, if enabled.
## 8. Concurrency
The upstream model is one goroutine per caller with node registration in `bbs`, and we keep it. Additions:
- `link` reads with per-byte deadlines (`xfer.Port` already has `SetReadDeadline`) for B+ timeouts.
- During a transfer, the ASCII front end hands the port to `xfer` and takes it back afterwards.
- The HMI session runs a reader goroutine (B+ Transport Layer → messages) and a writer that merges replies with async events (chat, mail-waiting).
- Chat and CB fan-out uses the upstream hub, so slow clients never block a room.
## 9. Testing
| Layer | How |
|---|---|
| `xfer/cisb` | Spec vectors (checksum `0x2A`, CRC `0x57FF`, doc 03). Fuzz the decoder. Loopback host↔client over `net.Pipe` with noise, drops and duplicates. Test against OzCIS's B+ in DOSBox-X. |
| `termid` | Real ID strings: WinCIM, OzCIS, Wilhite. |
| `cis/ascii` | Golden transcripts from the captures in doc 02, as exact bytes. TAPCIS's command strings (doc 02 §4.5) as acceptance tests. |
| `login/SLP` | Test vectors from the 24high emulator, checked independently. |
| `hmi` | Replay recorded WinCIM sessions from the wire tap. |
| End to end | `telnet localhost 2323`. DOSBox-X `serial1=modem` (dial `ATDT host:2323`) with TAPCIS, OzCIS and AutoSIG. WinCIM 2.x/3.x under Wine (`CommType=WINSOCK`, port 4144). **Real modems via D-Modem.** |
## 10. Milestones
0. **Fork and setup:** fork, build, run the stock BBS, add a CI job, add `[listen cis]` and dispatch to a stub `login.Run`.
1. **Login and top menu:** Host Name, User ID, password, banner, page tree from `content/`, `GO`/`T`/`M`/`B`/`F`/`R`/`H`, pager, `OFF`/`BYE`/`LOG`.
2. **DEFAULT settings:** BRIEF/PAGED/COMMAND/MENU in `users.prefs`; `SET`; `;TTY`.
3. **Forums, ASCII:** JOIN, sections, `REA`/`SCA`/`BRO` command language, headers, post/reply, EDIT, OPTIONS, exit stats.
4. **Libraries and transfers:** BRO/DIR/DOW/UPL, protocol menu (XMODEM and Kermit from upstream), then **CIS B/B+** in `xfer`.
5. **Mail:** menu and `Mail!` command modes, address forms, `INTERNET:` gateway (upstream's SMTP work in TODO.md may help).
6. **CB Simulator** and forum conferences on the chat hub.
7. **CIM:** `cim` listener, SLP, `ESC I`/AP handshake, B+ Transport Layer, HMI session, pages, menus, articles. Get WinCIM to the main menu.
8. **HMI features:** forums, mail read → send → libraries → chat (reverse-engineering at each step; doc 04 §5).
9. **Offline-reader pass:** TAPCIS, AutoSIG and OzCIS run their scripts cleanly.
10. **Polish:** billing display, RLE/GIF pages, sysop tools in the upstream config UI, content import.
+38
View File
@@ -0,0 +1,38 @@
# CompuServe Revival — Research and Design
These docs are the groundwork for reimplementing the CompuServe Information Service backend. The backend will be written in Go as a fork of [D-Modem/bbs](https://github.com/D-Modem/bbs). It will serve both the classic terminal interface and the WinCIM/CIM GUI clients.
> **Update:** rather than a fork, the service is being built in this repository, as `internal/cis` (a `frontend = compuserve` listener) and `internal/xfer/cisb.go`. Where doc 05 talks about "the fork" and "upstream files", read "this repo" and "the BBS's existing files". The goal is compatibility with the real clients (TAPCIS, OzCIS, AutoSIG, WinCIM and the other CIMs), not a look-alike.
| Doc | Contents |
|---|---|
| [01 — History and architecture](01-history-and-architecture.md) | Timeline, PDP-10/SC-40 hosts, NISA NT servers, user IDs, networks, clients, graphics, other revival projects |
| [02 — Terminal (ASCII) experience](02-terminal-ux.md) | Verbatim login, menus, prompts, forum command language, message headers, libraries, Mail, CB, billing, GO words |
| [03 — Link protocols](03-link-protocols.md) | A, B and B+ at the byte level, ESC I identification, VIDTEX escapes, how transfers start |
| [04 — GUI service (CIM/HMI)](04-cim-hmi.md) | Connection scripts, `?LOG` codes, Secure Login, the AP handshake, B+ Transport Layer, HMI message catalogue, reverse-engineering plan |
| [05 — Server design](05-server-design.md) | How the fork is laid out, the data mapping, connection lifecycle, walkthroughs, testing, milestones |
## Confidence tags used throughout
- **[C] / [V]** Confirmed: a primary spec, period document or verbatim capture says so.
- **[P]** Paraphrased from a period source.
- **[S]** Secondary: Wikipedia or recollections.
- **[RE]** Comes from a single reverse-engineering source (mainly the 2026 `24high/CompuServe-Emulator`). It needs checking on the wire.
- **[I]** Inference or design choice.
- **[GAP]** Not publicly known.
## Most important sources
- Russ Ranshaw, *The CompuServe B Plus Protocol* (1993): CompuServe's own spec.
- Steve Wilhite's `bp.c` (1985) and Steve Sneed's OOBPLUS (1991): reference code for B and B+.
- TAPCIS 5.3 manual and scripts, and the Forum 4D command listing (1989): the ASCII command contract.
- Session captures from 1987–1995 on discmaster.textfiles.com.
- `24high/CompuServe-Emulator` (C#, 2026): the only detailed HMI and Secure Login notes found. **Cite it, but don't copy from it:** it contains CompuServe's scripts and decompiler output.
- CompuServe's 1994 HMI developer FAQ and the 1995 NISA migration FAQ.
## Biggest open questions
1. The HMI message catalogue beyond pages, articles and mail-read (doc 04 §4).
2. The CB line format and band selection text (doc 02 §6).
3. Whether pre-1996 CIM clients used Secure Login and which mode numbers they used.
4. Exact host help texts. Candidates: the archive.org disk images and the Computer History Museum manual scans.
+79
View File
@@ -0,0 +1,79 @@
# CompuServe
A listener with `frontend = compuserve` serves a recreation of the
CompuServe Information Service instead of the BBS's menus. It runs on the
BBS's own users, and it aims to work with the real CompuServe software:
terminal programs, offline readers (TAPCIS, AutoSIG, OzCIS) and, later,
the CompuServe Information Manager (WinCIM, DOSCIM, MacCIM). Their
scripts look for the period's exact prompts, so the service keeps them.
```ini
[listen cis]
type = telnet
address = :2324
frontend = compuserve
```
A `raw` listener works too: modem callers through app_dmodem dial
straight into CompuServe. `connect = 9600` sets the `CONNECT` line shown
before `Host Name:`. It is on by default for telnet, which is what CIM's
scripts expect over TCP, and off for raw listeners, where the modem has
already said it.
## Logging on
```
Host Name: CIS
User ID: 72000,1
Password:
```
- **Host Name:** `CIS`, `CPS` or `CISAGREE`, the names CompuServe's own
scripts send.
- **User ID:** the account's number written as a CompuServe ID: account 1
is `72000,1`, using octal digits only, like CompuServe's own. A caller
can also type their BBS name; in that case the ID is shown at logon.
The ID may carry the usual options, such as `/INT:60`, `;TTY` and
`/GO:word`.
- **Password:** the BBS password.
- **Bad logon:** a wrong ID or password gets
`?? LOGINE - Invalid entry - try again`. Locked accounts and throttled
addresses get CompuServe's `?LOG` codes.
After the logon the host sends `ESC I`. Terminals that know it answer
with their identification, which shows in who's online. CIM clients
(`AP` in their reply) are told `?LOG CAI` for now, because the graphical
(HMI) service is not built yet.
## Commands
| Command | Does |
|---|---|
| a number | that menu choice |
| `T` | the TOP menu |
| `M` | the previous menu |
| `B` | back a page |
| `F` | forward a page |
| `R` | resend the page |
| `N` / `P` | next or previous item of the menu |
| `H` or `?` | help |
| `GO word` | go to a page by GO word or page ID |
| `FIND topic` | list the pages that mention a topic |
| `SET BRIEF ON` | brief `!` prompts |
| `SET PAGED ON` | stop at each screen |
| `SET WIDTH n` / `SET LINES n` | screen size |
| `OFF` or `BYE` | sign off |
| `LOG` | sign off and go back to `User ID:` |
Commands chain with `;`, as in `SET BRI ON;GO RATES`.
## What is there and what is coming
| Done | Coming, in order |
|---|---|
| The logon, `ESC I`, the menus and articles (`internal/cis/pages.txt`), GO, FIND, SET | Forums on the message areas, with the forum command language |
| The CompuServe B, Quick B and B Plus protocols (`internal/xfer/cisb.go`) | Libraries on the file areas, with B+ downloads |
| | CompuServe Mail, the CB Simulator, then CIM's HMI service |
The research behind all this, with sources, is in
[docs/cis](https://github.com/D-Modem/bbs/tree/main/docs/cis).
+3 -1
View File
@@ -94,7 +94,7 @@ There may be any number of these, each with its own NAME.
| key | default | live | what it does |
|---|---|---|---|
| `type` | `telnet` | | a telnet server; with tn3270 = yes (the default), a client that says it is a 3270 (IBM-3278-2-E, IBM-DYNAMIC) gets the 3270 screens raw the caller's bytes as they come, no protocol: app_dmodem's mode = tcp, modemmenu tcp/unix items rlogin RFC 1282, as modemmenu's rlogin items speak it ssh SSH: passwords or users' keys (host_keys, legacy) Examples: `telnet`, `raw`, `ssh`, `rlogin`. |
| `address` | `host:port` | | or a unix socket's path (/run/bbs/bbs.sock) Examples: `:2300`, `:992`, `127.0.0.1:2323`, `:2222`, `127.0.0.1:2513`, `/run/bbs/menu.sock`. |
| `address` | `host:port` | | or a unix socket's path (/run/bbs/bbs.sock) Examples: `:2300`, `:992`, `127.0.0.1:2323`, `:2324`, `:2222`, `127.0.0.1:2513`, `/run/bbs/menu.sock`. |
| `via` | `...` | | how its callers came, in who's online (telnet, modem, rlogin by type) |
| `ansi` | `auto` | | the terminal's ANSI color: auto asks the terminal (or believes its terminal type), yes, no. |
| `utf8` | `auto` | | UTF-8 both ways: auto by the terminal type (xterm and friends yes; "ansi" BBS terminals no), yes, no. |
@@ -109,6 +109,8 @@ There may be any number of these, each with its own NAME.
| `create_users` | `no` | | yes, with trust_user: a user unknown here gets an account (with no password of its own) Examples: `yes`. |
| `socket_mode` | `0660` | | a unix socket's permissions. |
| `socket_group` | `...` | | and its group. Examples: `asterisk`. |
| `frontend` | `bbs` | | what callers get: the BBS, or compuserve: the CompuServe Information Service (telnet and raw listeners; no 3270). See the wiki's CompuServe. Examples: `compuserve`. |
| `connect` | `9600` | | compuserve: the CONNECT line before Host Name: (telnet: 9600; raw: none, the modem says its own) |
| `tn3270` | | | See the section above. Examples: `yes`. |
| `tls_cert` | | | See the section above. Examples: `/etc/bbs/cert.pem`. |
| `tls_key` | | | See the section above. Examples: `/etc/bbs/key.pem`. |
+1
View File
@@ -20,6 +20,7 @@
- [Sixel graphics](Sixel-Graphics)
- [PETSCII and RIP](PETSCII-and-RIP)
- [Terminal identification](Terminal-Identification)
- [CompuServe](CompuServe)
**Features**
- [Message areas](Message-Areas)
+347
View File
@@ -0,0 +1,347 @@
package cis
import (
"errors"
"strconv"
"strings"
)
// errRelog is LOG: off, and back to "User ID:".
var errRelog = errors.New("cis: LOG")
// ascii is the terminal service, from the banner to the logoff.
func (s *session) ascii() error {
s.banner()
first := s.pages.Get("TOP")
if s.firstGo != "" {
if p := s.pages.Get(s.firstGo); p != nil {
first = p
}
}
s.show(first)
for {
line, err := s.prompt(s.promptFor())
if errors.Is(err, errAbort) {
continue
}
if err != nil {
return err
}
if err := s.commands(line); err != nil {
return err
}
}
}
// promptFor is the prompt of the page shown.
func (s *session) promptFor() string {
switch {
case len(s.more) > 0:
return s.choicePrompt("Press <CR> for more !")
case s.page.Menu():
return s.choicePrompt("Enter choice !")
}
return s.choicePrompt("Last page !")
}
// commands does a line of commands, separated by ";".
func (s *session) commands(line string) error {
if strings.TrimSpace(line) == "" {
return s.command("")
}
for _, c := range strings.Split(line, ";") {
if err := s.command(strings.TrimSpace(c)); err != nil {
return err
}
}
return nil
}
// command does one command.
func (s *session) command(c string) error {
verb, arg, _ := strings.Cut(c, " ")
verb, arg = strings.ToUpper(verb), strings.TrimSpace(arg)
switch {
case verb == "":
switch {
case len(s.more) > 0:
s.pageOut(s.more)
case !s.page.Menu():
// the end of an article: back to its menu
s.backToMenu()
default:
s.show(s.page)
}
case isNumber(verb):
n, _ := strconv.Atoi(verb)
if !s.page.Menu() || n < 1 || n > len(s.page.Items) {
s.out(verb + " is not a choice !\n")
return nil
}
s.goTo(s.pages.Get(s.page.Items[n-1].Target))
case verb == "T" || verb == "TOP":
s.goTo(s.pages.Get("TOP"))
case verb == "M" || verb == "MENU":
s.backToMenu()
case verb == "B" || verb == "BACK":
if len(s.stack) > 1 {
s.stack = s.stack[:len(s.stack)-1]
p := s.stack[len(s.stack)-1]
s.stack = s.stack[:len(s.stack)-1]
s.goTo(p)
} else {
s.show(s.page)
}
case verb == "F" || verb == "FORWARD":
if len(s.more) > 0 {
s.pageOut(s.more)
} else {
s.out(s.choicePrompt("Last page") + "\n")
}
case verb == "R" || verb == "RESEND":
s.show(s.page)
case verb == "N" || verb == "NEXT", verb == "P" || verb == "PREVIOUS":
s.sibling(verb[0] == 'N')
case verb == "H" || verb == "HELP" || verb == "?":
s.goTo(s.pages.Get("HELP"))
case verb == "G" || verb == "GO":
if arg == "" {
s.out("GO where? Type GO and a GO word or page ID.\n")
return nil
}
p := s.pages.Get(arg)
if p == nil {
s.out(strings.ToUpper(arg) + " is unrecognized !\n")
return nil
}
s.goTo(p)
case verb == "FIND":
s.find(arg)
case verb == "SET":
s.set(arg)
case verb == "OFF" || verb == "BYE":
s.logoff()
return errHangup
case verb == "LOG" || verb == "LOGOFF":
s.logoff()
return errRelog
default:
// a GO word alone takes you there too
if p := s.pages.Get(c); p != nil {
s.goTo(p)
return nil
}
s.out(strings.ToUpper(c) + " is unrecognized !\n")
}
return nil
}
func isNumber(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}
// goTo shows a page and remembers it for B and M.
func (s *session) goTo(p *Page) {
if p == nil {
return
}
if p.Menu() {
s.menus = append(s.menus, p)
}
s.show(p)
}
// show shows a page.
func (s *session) show(p *Page) {
s.page = p
s.more = nil
if len(s.stack) == 0 || s.stack[len(s.stack)-1] != p {
s.stack = append(s.stack, p)
if len(s.stack) > 100 {
s.stack = s.stack[1:]
}
}
s.node.Doing("CompuServe: " + p.ID)
lines := []string{heading(p, s.width), ""}
lines = append(lines, p.Text...)
for i, it := range p.Items {
lines = append(lines, padNum(i+1, len(p.Items))+" "+it.Text)
}
s.out("\n")
s.pageOut(lines)
}
// padNum is a menu item's number, right-aligned to the widest.
func padNum(n, of int) string {
w := len(strconv.Itoa(of))
if w < 2 {
w = 2
}
k := strconv.Itoa(n)
return strings.Repeat(" ", w-len(k)) + k
}
// pageOut sends lines, a screen at a time when paged: what is left waits
// in s.more for a CR.
func (s *session) pageOut(lines []string) {
n := len(lines)
if s.paged && s.lines > 2 && n > s.lines-1 {
n = s.lines - 1
}
for _, l := range lines[:n] {
s.out(l + "\n")
}
s.more = lines[n:]
if len(s.more) == 0 {
s.more = nil
}
}
// backToMenu goes back to the menu before (or the page's own menu).
func (s *session) backToMenu() {
for len(s.menus) > 0 {
m := s.menus[len(s.menus)-1]
if m != s.page {
s.show(m)
return
}
s.menus = s.menus[:len(s.menus)-1]
}
if p := s.pages.Parent(s.page); p != nil {
s.goTo(p)
return
}
s.goTo(s.pages.Get("TOP"))
}
// sibling is N or P: the next or previous item of the menu the page is on.
func (s *session) sibling(forward bool) {
m := s.pages.Parent(s.page)
if len(s.menus) > 0 && s.menus[len(s.menus)-1] != s.page {
m = s.menus[len(s.menus)-1]
}
if m == nil {
s.out("There is no next item.\n")
return
}
for i, it := range m.Items {
if it.Target != s.page.ID {
continue
}
j := i + 1
if !forward {
j = i - 1
}
if j < 0 || j >= len(m.Items) {
break
}
s.show(s.pages.Get(m.Items[j].Target))
return
}
if forward {
s.out("There is no next item.\n")
} else {
s.out("There is no previous item.\n")
}
}
// find is FIND topic: the pages that mention it.
func (s *session) find(topic string) {
if topic == "" {
s.goTo(s.pages.Get("FIND"))
return
}
ps := s.pages.Find(topic)
if len(ps) == 0 {
s.out("\nNo matches were found for " + strings.ToUpper(topic) + ".\n")
return
}
lines := []string{"", "Index of " + strings.ToUpper(topic), ""}
for _, p := range ps {
title := p.Title
if title == "CompuServe" && len(p.Text) > 0 {
title = strings.TrimSpace(p.Text[0])
}
if title == "CompuServe" {
if m := s.pages.Parent(p); m != nil {
for _, it := range m.Items {
if it.Target == p.ID {
title = it.Text
}
}
}
}
lines = append(lines, " "+pad(title, 50)+" [GO "+p.ID+"]")
}
s.pageOut(lines)
}
func pad(s string, n int) string {
if len(s) >= n {
return s
}
return s + strings.Repeat(" ", n-len(s))
}
// set is SET: BRIEF, PAGED, WIDTH, LINES.
func (s *session) set(arg string) {
f := strings.Fields(strings.ToUpper(arg))
if len(f) != 2 {
s.out("Type SET and an option: SET BRIEF ON, SET PAGED OFF, SET WIDTH 80, SET LINES 24\n")
return
}
onOff := func(v string) (bool, bool) {
switch v {
case "ON", "YES", "Y":
return true, true
case "OFF", "NO", "N":
return false, true
}
return false, false
}
switch opt, v := f[0], f[1]; {
case strings.HasPrefix("BRIEF", opt) && len(opt) >= 3:
b, ok := onOff(v)
if !ok {
s.out("BRIEF is ON or OFF\n")
return
}
s.brief = b
case strings.HasPrefix("PAGED", opt) && len(opt) >= 3:
b, ok := onOff(v)
if !ok {
s.out("PAGED is ON or OFF\n")
return
}
s.paged = b
if b && s.lines == 0 {
s.lines = 24
}
case strings.HasPrefix("WIDTH", opt) && len(opt) >= 3:
n, err := strconv.Atoi(v)
if err != nil || n < 40 || n > 132 {
s.out("WIDTH is from 40 to 132\n")
return
}
s.width = n
case strings.HasPrefix("LINES", opt) && len(opt) >= 3:
n, err := strconv.Atoi(v)
if err != nil || n < 0 || n > 200 {
s.out("LINES is from 0 to 200\n")
return
}
s.lines = n
default:
s.out(opt + " is not a terminal option\n")
return
}
s.out("OK\n")
}
+232
View File
@@ -0,0 +1,232 @@
// Package cis is a CompuServe Information Service front end on the BBS:
// the network's "Host Name:", CompuServe's "User ID:" and "Password:", the
// terminal's identification (ESC I), and the ASCII service: its menu and
// article pages, GO words and the "!" prompts, as a terminal caller of
// the 1980s and 90s saw them. Offline readers (TAPCIS, AutoSIG, OzCIS)
// match these strings, so they keep the period's wording.
//
// Users are the BBS's: a User ID is the account's number written as a
// CompuServe ID (PPN), or its name. The GUI service (CIM's HMI, over B
// Plus) is not here yet: a CIM client is told "?LOG CAI".
package cis
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/cis/termid"
"github.com/D-Modem/bbs/internal/store"
)
// Line is the caller's connection: telnet (in binary mode) or raw.
type Line interface {
io.Reader
io.Writer
SetReadDeadline(time.Time) error
}
// Options are a listener's: Connect, a "CONNECT <rate>" line before the
// Host Name prompt (what a dial-up node's caller saw first, and what
// CIM's scripts over TCP wait for); "" for none (a modem caller has had
// the modem's).
type Options struct {
Connect string
}
// session is a caller's time on the service.
type session struct {
b *bbs.BBS
node *bbs.Node
line Line
r *bufio.Reader
opt Options
user *store.User
caps *termid.Caps
start time.Time
now func() time.Time
// session settings (SET)
brief bool
paged bool
width int
lines int
pages *Pages
page *Page // the page shown
stack []*Page // pages gone through, for B
menus []*Page // menus gone through, for M
more []string
firstGo string // /GO:word at the User ID
byName bool // logged on with a BBS name, not a User ID
pushed []byte // input put back
cr bool // the last input byte was a CR (drop a LF or NUL after it)
}
// errHangup ends a call: OFF, BYE or the caller gone.
var errHangup = errors.New("cis: logged off")
// Run is a call on the service, from the Host Name prompt to the logoff.
func Run(b *bbs.BBS, node *bbs.Node, line Line, opt Options) error {
s := &session{b: b, node: node, line: line, r: bufio.NewReader(line), opt: opt,
start: time.Now(), now: time.Now, width: 80, pages: DefaultPages()}
err := s.run()
if errors.Is(err, errHangup) || errors.Is(err, io.EOF) {
return nil
}
return err
}
func (s *session) run() error {
s.node.Doing("CompuServe: logging in")
if s.opt.Connect != "" {
s.out("\nCONNECT " + s.opt.Connect + "\n")
}
if err := s.hostName(); err != nil {
return err
}
for {
u, err := s.login()
if err != nil {
return err
}
s.user = u
if err := s.identify(); err != nil {
return err
}
if s.caps.AP() {
// a CIM client: its HMI service is to come
s.b.Log.Printf("node %d: CompuServe: %s is a CIM client (%s); HMI not yet served", s.node.Num, u.Name, s.caps.Raw)
s.out("\n?LOG CAI\n")
return errHangup
}
err = s.ascii()
if !errors.Is(err, errRelog) {
return err
}
s.user = nil
}
}
// out writes text, its newlines as CR LF.
func (s *session) out(text string) error {
_, err := io.WriteString(s.line, strings.ReplaceAll(text, "\n", "\r\n"))
return err
}
func (s *session) outf(format string, a ...any) error { return s.out(fmt.Sprintf(format, a...)) }
// errors of input
var (
errAbort = errors.New("cis: ^C") // the line given up
errIdle = errors.New("cis: idle")
)
func (s *session) getc(d time.Duration) (byte, error) {
if len(s.pushed) > 0 {
c := s.pushed[0]
s.pushed = s.pushed[1:]
return c, nil
}
if d > 0 {
s.line.SetReadDeadline(time.Now().Add(d))
defer s.line.SetReadDeadline(time.Time{})
}
c, err := s.r.ReadByte()
if errors.Is(err, os.ErrDeadlineExceeded) {
return 0, errIdle
}
return c, err
}
// input reads a line, echoed (or, for a password, not), within d a key.
// ^U throws away what was typed, ^V types it again, ^C and ^P give the
// line up (errAbort).
func (s *session) input(echo bool, d time.Duration) (string, error) {
var b []byte
for {
c, err := s.getc(d)
if err != nil {
return "", err
}
if s.cr && (c == '\n' || c == 0) {
s.cr = false
continue
}
s.cr = false
switch c {
case '\r', '\n':
s.cr = c == '\r'
s.out("\n")
return string(b), nil
case 8, 0x7F:
if len(b) > 0 {
b = b[:len(b)-1]
if echo {
s.out("\b \b")
}
}
case 0x15: // ^U: echoed only if there was something to throw away
if len(b) > 0 && echo {
s.out("^U\n")
}
b = b[:0]
case 0x16: // ^V
if echo {
s.out("\n" + string(b))
}
case 3, 0x10: // ^C, ^P
s.out("^C\n")
return "", errAbort
default:
if c < 0x20 || len(b) >= 255 {
continue
}
b = append(b, c)
if echo {
s.line.Write([]byte{c})
}
}
}
}
// prompt asks and reads the answer, after the login: an idle caller is
// logged off.
func (s *session) prompt(p string) (string, error) {
s.out(p)
line, err := s.input(true, s.b.Conf().IdleTimeout)
if errors.Is(err, errIdle) {
s.out("\n\nYou have been idle too long.\n")
s.logoff()
return "", errHangup
}
return line, err
}
// choicePrompt is the prompt for a choice: "!" when brief.
func (s *session) choicePrompt(long string) string {
if s.brief {
return "!"
}
return long
}
// identify sends ESC I and reads the terminal's answer, if it gives one;
// what the caller typed meanwhile is kept.
func (s *session) identify() error {
caps, junk, err := termid.Probe(s.line, s.r, 10, 1500*time.Millisecond)
if err != nil {
return err
}
s.pushed = append(s.pushed, junk...)
if caps != nil {
s.caps = caps
s.node.SetIdent(caps.Raw)
}
return nil
}
+71
View File
@@ -0,0 +1,71 @@
package cis
import "testing"
func TestPPN(t *testing.T) {
for _, c := range []struct {
id int64
ppn string
}{{1, "72000,1"}, {8, "72000,10"}, {4095, "72000,7777"}, {4096, "72001,0"}, {100000, "72030,3240"}} {
if got := PPN(c.id); got != c.ppn {
t.Errorf("PPN(%d) = %s, want %s", c.id, got, c.ppn)
}
if id, ok := ParsePPN(c.ppn); !ok || id != c.id {
t.Errorf("ParsePPN(%s) = %d %v", c.ppn, id, ok)
}
}
for _, bad := range []string{"70000,123", "72000,8", "72000,0", "alice", "72000;1", "720001"} {
if id, ok := ParsePPN(bad); ok {
t.Errorf("ParsePPN(%s) = %d", bad, id)
}
}
if id, ok := ParsePPN("72000.1"); !ok || id != 1 {
t.Error("72000.1")
}
}
func TestParseUserID(t *testing.T) {
u := ParseUserID("+72000,1/INT:60 /secure:1")
if u.ID != "72000,1" || !u.Secure {
t.Errorf("%+v", u)
}
u = ParseUserID("73237,341;TTY")
if u.ID != "73237,341" || !u.TTY {
t.Errorf("%+v", u)
}
u = ParseUserID("70000,123*NAVIG")
if u.ID != "70000,123" || len(u.Opts) != 1 {
t.Errorf("%+v", u)
}
u = ParseUserID("alice/GO:RATES")
if u.ID != "alice" || u.Go != "RATES" {
t.Errorf("%+v", u)
}
}
func TestPages(t *testing.T) {
ps := DefaultPages()
if p := ps.Get("cis"); p == nil || p.ID != "TOP" || len(p.Items) != 12 {
t.Fatalf("TOP: %+v", p)
}
if p := ps.Get("help"); p == nil || p.ID != "CIS-162" || p.Menu() {
t.Errorf("HELP: %+v", p)
}
if ps.Parent(ps.Get("RATES")).ID != "MEMBER" {
t.Error("RATES's parent")
}
for _, bad := range []string{
":TOP\n 1 Nowhere > NOWHERE\n",
":TOP\n 2 Wrong number > TOP\n",
":X\n",
":TOP\n:TOP\n",
":TOP A\n:B A\n",
} {
if _, err := ParsePages(bad); err == nil {
t.Errorf("%q parsed", bad)
}
}
if h := heading(ps.Get("TOP"), 80); len(h) != 80 {
t.Errorf("heading %q", h)
}
}
+240
View File
@@ -0,0 +1,240 @@
package cis
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/store"
)
// PPN is a user's CompuServe User ID: their account number, in octal
// (CompuServe's IDs have only the digits 0-7), as a project number from
// 72000 and a programmer number. Account 1 is 72000,1.
func PPN(id int64) string {
return fmt.Sprintf("%o,%o", 0o72000+id>>12, id&0o7777)
}
var ppnPattern = regexp.MustCompile(`^([0-7]{5,6})[,.]([0-7]{1,5})$`)
// ParsePPN is the account number of a User ID, or false if it is not one
// PPN makes.
func ParsePPN(s string) (int64, bool) {
m := ppnPattern.FindStringSubmatch(s)
if m == nil {
return 0, false
}
proj, _ := strconv.ParseInt(m[1], 8, 64)
prog, _ := strconv.ParseInt(m[2], 8, 64)
if proj < 0o72000 || prog > 0o7777 {
return 0, false
}
id := (proj-0o72000)<<12 | prog
return id, id > 0
}
// UserID is what a caller typed at "User ID:": the ID, and what came with
// it.
type UserID struct {
ID string // the ID (or name) itself
Secure bool // a leading +: CIM asking for the Secure Login Protocol
Opts []string
TTY bool // ;TTY: default terminal settings
Go string // /GO:word: the first service
}
// ParseUserID reads "+70000,123/INT:60 /secure:1", "73237,341;TTY",
// "70000,123*NAVIG", "alice/GO:MAIL".
func ParseUserID(s string) UserID {
s = strings.TrimSpace(s)
var u UserID
if strings.HasPrefix(s, "+") {
u.Secure = true
s = s[1:]
}
if i := strings.IndexAny(s, "/*;"); i >= 0 {
u.ID = strings.TrimSpace(s[:i])
rest := s[i:]
for _, f := range strings.FieldsFunc(rest, func(r rune) bool { return r == '/' || r == ' ' }) {
switch {
case strings.EqualFold(f, ";TTY"):
u.TTY = true
case strings.HasPrefix(f, "*"), strings.HasPrefix(f, ";"):
u.Opts = append(u.Opts, f)
case len(f) > 3 && strings.EqualFold(f[:3], "GO:"):
u.Go = f[3:]
case strings.EqualFold(f, "secure:1"):
u.Secure = true
u.Opts = append(u.Opts, f)
default:
if j := strings.Index(f, ";"); j >= 0 && strings.EqualFold(f[j:], ";TTY") {
u.TTY = true
f = f[:j]
}
u.Opts = append(u.Opts, f)
}
}
} else {
u.ID = s
}
return u
}
// hosts are the names the network's "Host Name:" takes for the service:
// the manuals' CIS, the 1996 scripts' CPS, and CISAGREE over the internet.
var hosts = map[string]bool{"CIS": true, "CPS": true, "CISAGREE": true, "COMPUSERVE": true}
// hostName is the network node's dialogue: "Host Name:" until the caller
// names the service.
func (s *session) hostName() error {
for try := 0; ; try++ {
s.out("\nHost Name: ")
h, err := s.input(true, s.b.Conf().LoginTimeout)
if errors.Is(err, errAbort) {
continue
}
if err != nil {
return s.loginErr(err)
}
h = strings.ToUpper(strings.TrimSpace(h))
if h == "" {
try--
if try < -10 {
return errHangup
}
continue
}
if i := strings.IndexAny(h, "/;"); i >= 0 {
h = h[:i]
}
if hosts[h] {
return nil
}
s.out("Host is unavailable\n")
if try >= 2 {
return errHangup
}
}
}
func (s *session) loginErr(err error) error {
if errors.Is(err, errIdle) {
s.out("\n")
return errHangup
}
return err
}
// login is "User ID:" and "Password:", up to the BBS's attempts. A bad
// ID or password is "?? LOGINE - Invalid entry - try again".
func (s *session) login() (*store.User, error) {
attempts := s.b.Conf().Attempts
if attempts < 1 {
attempts = 3
}
for try := 0; try < attempts; try++ {
s.out("\nUser ID: ")
line, err := s.input(true, s.b.Conf().LoginTimeout)
if errors.Is(err, errAbort) {
try--
continue
}
if err != nil {
return nil, s.loginErr(err)
}
id := ParseUserID(line)
if id.ID == "" {
try--
continue
}
s.out("Password: ")
pw, err := s.input(false, s.b.Conf().LoginTimeout)
if errors.Is(err, errAbort) {
continue
}
if err != nil {
return nil, s.loginErr(err)
}
name := id.ID
s.byName = true
if n, ok := ParsePPN(id.ID); ok {
if u, err := s.b.Store.UserByID(n); err == nil {
name, s.byName = u.Name, false
}
}
u, err := s.node.Login(name, pw)
switch {
case err == nil:
if id.Go != "" {
s.firstGo = id.Go
}
return u, nil
case errors.Is(err, bbs.ErrBadLogin):
s.out("\n?? LOGINE - Invalid entry - try again\n")
case errors.Is(err, bbs.ErrLocked):
s.out("\n?LOG STU - Please check your User ID\n")
return nil, errHangup
case errors.Is(err, bbs.ErrThrottled):
s.out("\n?LOG SNA - System unavailable\n")
return nil, errHangup
default:
s.out("\n?LOG SIU - System unavailable\n")
return nil, err
}
}
return nil, errHangup
}
// date formats of the banner and the logoff
const (
bannerTime = "15:04 MST Monday 02-Jan-06"
accessTime = "15:04 02-Jan-06"
offTime = "15:04 MST 2-Jan-06"
)
// prime is CompuServe's prime time: 8 to 7 on weekdays.
func prime(t time.Time) bool {
return t.Weekday() != time.Saturday && t.Weekday() != time.Sunday && t.Hour() >= 8 && t.Hour() < 19
}
// banner is what the caller sees once in.
func (s *session) banner() {
now := s.now()
p := ""
if prime(now) {
p = " P"
}
s.out("\nCompuServe Information Service\n")
s.outf(" %s%s\n", now.Format(bannerTime), p)
if !s.user.LastLogin.IsZero() {
s.outf(" Last access: %s\n", s.user.LastLogin.Format(accessTime))
}
if name := s.b.Conf().Name; name != "" {
s.outf(" Copyright (c) %d\n %s\n", now.Year(), name)
}
if s.byName {
// not CompuServe's; only a caller who logged on by name sees it,
// and a script logs on by its User ID
s.outf(" Your User ID is %s\n", PPN(s.user.ID))
}
if n, err := s.b.Store.UnreadMail(s.user.ID); err == nil && n > 0 {
s.out("You have Electronic Mail waiting.\n")
}
}
// logoff is CompuServe's goodbye.
func (s *session) logoff() {
now := s.now()
d := now.Sub(s.start)
mins := int(d.Round(time.Minute) / time.Minute)
if mins < 1 {
mins = 1
}
s.out("\nThank you for using CompuServe!\n")
s.outf("Off at %s\n", now.Format(offTime))
s.outf("Connect time = %d:%02d\n", mins/60, mins%60)
}
+196
View File
@@ -0,0 +1,196 @@
package cis
import (
_ "embed"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
)
// Page is a page of the service: a menu (items leading to other pages) or
// an article (text), named by its page ID (TOP, CIS-162, RATES...) and
// reached by GO with that or one of its GO words.
type Page struct {
ID string
Title string // shown at the left of the page's first line
Go []string
Text []string // an article's text, or a menu's lines before its items
Items []Item
}
// Item is a menu's choice.
type Item struct {
Text string
Target string // a page ID
}
// Menu reports whether p is a menu.
func (p *Page) Menu() bool { return len(p.Items) > 0 }
// Pages are the service's pages, by ID, with the GO words that lead to
// each.
type Pages struct {
byID map[string]*Page
words map[string]*Page
order []*Page
}
//go:embed pages.txt
var pagesText string
// DefaultPages are the pages the service comes with.
func DefaultPages() *Pages {
p, err := ParsePages(pagesText)
if err != nil {
panic("cis: pages.txt: " + err.Error())
}
return p
}
var itemPattern = regexp.MustCompile(`^\s*(\d+)\s+(.*?)\s*>\s*(\S+)\s*$`)
// ParsePages reads pages from text:
//
// :ID GOWORD GOWORD... a page and the GO words for it
// =Title its title
// 1 Some service > ID a menu item leading to page ID
// anything else its text
//
// Lines starting with "#" are comments. Every item must lead to a page
// there is.
func ParsePages(text string) (*Pages, error) {
ps := &Pages{byID: map[string]*Page{}, words: map[string]*Page{}}
var cur *Page
for n, line := range strings.Split(text, "\n") {
line = strings.TrimRight(line, " \r")
switch {
case strings.HasPrefix(line, "#"):
continue
case strings.HasPrefix(line, ":"):
f := strings.Fields(line[1:])
if len(f) == 0 {
return nil, fmt.Errorf("line %d: a page needs an ID", n+1)
}
id := strings.ToUpper(f[0])
if ps.byID[id] != nil {
return nil, fmt.Errorf("line %d: page %s again", n+1, id)
}
cur = &Page{ID: id, Title: "CompuServe"}
ps.byID[id] = cur
ps.order = append(ps.order, cur)
for _, w := range append([]string{id}, f[1:]...) {
w = strings.ToUpper(w)
if ps.words[w] != nil && ps.words[w] != cur {
return nil, fmt.Errorf("line %d: GO %s is page %s's", n+1, w, ps.words[w].ID)
}
ps.words[w] = cur
if w != id {
cur.Go = append(cur.Go, w)
}
}
case cur == nil:
if strings.TrimSpace(line) != "" {
return nil, fmt.Errorf("line %d: text before the first page", n+1)
}
case strings.HasPrefix(line, "="):
cur.Title = strings.TrimSpace(line[1:])
default:
if m := itemPattern.FindStringSubmatch(line); m != nil {
if k, _ := strconv.Atoi(m[1]); k != len(cur.Items)+1 {
return nil, fmt.Errorf("line %d: item %s of %s is not number %d", n+1, m[1], cur.ID, len(cur.Items)+1)
}
cur.Items = append(cur.Items, Item{m[2], strings.ToUpper(m[3])})
continue
}
if len(cur.Items) > 0 && strings.TrimSpace(line) != "" {
return nil, fmt.Errorf("line %d: text after %s's items", n+1, cur.ID)
}
cur.Text = append(cur.Text, line)
}
}
for _, p := range ps.order {
// blank lines at the ends are the file's, not the page's
for len(p.Text) > 0 && strings.TrimSpace(p.Text[len(p.Text)-1]) == "" {
p.Text = p.Text[:len(p.Text)-1]
}
for len(p.Text) > 0 && strings.TrimSpace(p.Text[0]) == "" {
p.Text = p.Text[1:]
}
for _, it := range p.Items {
if ps.byID[it.Target] == nil {
return nil, fmt.Errorf("page %s: item %q leads to %s, which is not a page", p.ID, it.Text, it.Target)
}
}
}
if ps.byID["TOP"] == nil {
return nil, fmt.Errorf("there is no TOP page")
}
return ps, nil
}
// Get is a page by its ID or a GO word.
func (ps *Pages) Get(word string) *Page {
word = strings.ToUpper(strings.TrimSpace(word))
if p := ps.byID[word]; p != nil {
return p
}
return ps.words[word]
}
// Find is the pages whose title, text, items or GO words mention topic.
func (ps *Pages) Find(topic string) []*Page {
topic = strings.ToUpper(strings.TrimSpace(topic))
if topic == "" {
return nil
}
var out []*Page
for _, p := range ps.order {
hay := []string{p.ID, p.Title}
hay = append(hay, p.Go...)
hay = append(hay, p.Text...)
for _, it := range p.Items {
hay = append(hay, it.Text)
}
for _, h := range hay {
if strings.Contains(strings.ToUpper(h), topic) {
out = append(out, p)
break
}
}
}
return out
}
// Words are the GO words, sorted.
func (ps *Pages) Words() []string {
var out []string
for w := range ps.words {
out = append(out, w)
}
sort.Strings(out)
return out
}
// Parent is the first menu with an item leading to p, or nil.
func (ps *Pages) Parent(p *Page) *Page {
for _, m := range ps.order {
for _, it := range m.Items {
if it.Target == p.ID {
return m
}
}
}
return nil
}
// heading is a page's first line: its title, and its ID at the right
// margin.
func heading(p *Page, width int) string {
pad := width - len(p.Title) - len(p.ID)
if pad < 1 {
pad = 1
}
return p.Title + strings.Repeat(" ", pad) + p.ID
}
+192
View File
@@ -0,0 +1,192 @@
# The CompuServe service's pages. See ParsePages in pages.go for the form.
# Page IDs follow CompuServe's own (TOP, CIS-162, RATES...); GO words are
# aliases. Services not built yet lead to a page that says so.
:TOP CIS MAIN
1 Member Assistance (FREE) > MEMBER
2 Find a Topic (FREE) > FIND
3 Communications/Bulletin Bds. > COMMUNICATIONS
4 News/Weather/Sports > NEWS
5 Travel > TRAVEL
6 The Electronic MALL/Shopping > MALL
7 Money Matters/Markets > MONEY
8 Entertainment/Games > GAMES
9 Home/Health/Family > HOME
10 Reference/Education > REFERENCE
11 Computers/Technology > COMPUTERS
12 Business/Other Interests > BUSINESS
:MEMBER FREE BASIC MEMBERASSIST
1 Command Summary > CIS-162
2 What's New > NEW
3 Rates and Billing > RATES
4 Terminal Settings > DEFAULT
5 Sign-up and User IDs > LGN-1
6 About This Service > ABOUT
7 Source Code for This Service > SOURCE
:CIS-162 HELP COMMANDS ?
=CompuServe
T - TOP menu page
M - previous MENU
H or ? - HELP
GO word or GO page - GO directly to a service
FIND topic - FIND all references to topic
OFF or BYE - sign off
LOG - sign off and log on again
R - RESEND a page
F - FORWARD a page
B - BACK a page
N - display NEXT menu item
P - display PREVIOUS menu item
SET option - SET terminal option
SET BRIEF ON|OFF, SET PAGED ON|OFF, SET WIDTH n, SET LINES n
Commands may be chained with ";" (GO RATES;T).
^C abandons a line or a display, ^U erases a line, ^V retypes it.
:NEW WHATSNEW
=What's New
This CompuServe service runs on this BBS, sharing its users. You
log on with your BBS name or your User ID (shown at logon) and your
BBS password.
Here now: the menus and articles, GO words and FIND, and the
terminal settings of SET.
On their way, in this order: forums (the BBS's message areas, with
the forum command language), libraries and the CompuServe B and
B Plus protocols, CompuServe Mail, the CB Simulator, and the
CompuServe Information Manager (CIM) graphical service.
:RATES CHARGES BILLING NEWBIL
=CompuServe
RATES
Connect time on this service is free, at every baud rate, prime
time and non-prime alike. Prime time is 8:00 a.m. to 7:00 p.m.
on weekdays; a "P" after the time at logon says you are in it.
There is no membership support fee.
:DEFAULT TERMINAL PROFILE
=TERMINAL SETTINGS
Your settings for this session are set with the SET command:
SET BRIEF ON brief "!" prompts (expert mode)
SET BRIEF OFF full prompts ("Enter choice !")
SET PAGED ON stop at each screen ("Press <CR> for more !")
SET PAGED OFF no stops (for offline readers)
SET WIDTH n the screen's width (40 to 132)
SET LINES n lines per screen, when paged
Permanent settings are not kept yet: each logon starts with BRIEF
OFF, PAGED OFF and WIDTH 80.
:LGN-1 SIGNUP JOIN PASSWORD
=CompuServe
USER IDS
Your User ID is your BBS account number written the CompuServe way,
as two numbers with a comma between: account 1 is 72000,1. It is
shown at logon. You may also type your BBS name at "User ID:".
To sign up, call the BBS itself and make an account there; the same
name and password let you in here. Change your password on the
BBS.
:ABOUT
=CompuServe
ABOUT THIS SERVICE
This is a recreation of the CompuServe Information Service as a
terminal caller of the 1980s and 1990s saw it, running on this BBS.
It is not affiliated with CompuServe. The prompts and the shape of
the menus follow the period's, so that old terminal programs and
offline readers (TAPCIS, AutoSIG, OzCIS) can find their way.
:SOURCE AGPL
=CompuServe
SOURCE CODE
This service is free software under the GNU Affero General Public
License, version 3. Its source code, and the BBS's, is at
https://github.com/D-Modem/bbs
:FIND
=CompuServe
FIND
Type FIND and a topic (FIND MAIL, FIND FORUM) to list every page
that mentions it, with the page ID to GO to.
:COMMUNICATIONS COMMUNICATE
1 CompuServe Mail > MAIL
2 Forums (Special Interest Groups) > FORUMS
3 CB Simulator > CB
4 Member Directory > DIRECTORY
:MAIL EASY EASYPLEX
=CompuServe Mail
CompuServe Mail is on its way. Until then, read and send your mail
on the BBS itself.
:FORUMS SIGS
=CompuServe
Forums are on their way: each of the BBS's message areas is to be a
forum section, with the forum command language (REA, SCA, BRO,
LIB...). Until then, read and post on the BBS itself.
:CB CB-1 CHAT
=CB Simulator
The CB Simulator is on its way, on the BBS's chat rooms.
:DIRECTORY
=CompuServe
The member directory is on its way.
:NEWS WEA WEATHER SPORTS
1 Weather > WEATHER-SOON
2 News > NEWS-SOON
:WEATHER-SOON
=Weather
Weather reports are not offered yet.
:NEWS-SOON
=News
News services are not offered yet.
:TRAVEL
=Travel
Travel services are not offered yet.
:MALL
=The Electronic MALL
The Electronic MALL is closed. No shopping is offered here.
:MONEY QUO
=Money Matters
Market quotes are not offered yet.
:GAMES GAM-1
=Entertainment/Games
Games are not offered yet. The BBS's doors may have some.
:HOME
=Home/Health/Family
There is nothing here yet.
:REFERENCE
=Reference/Education
There is nothing here yet.
:COMPUTERS
=Computers/Technology
1 Computer Forums > FORUMS
2 Source Code for This Service > SOURCE
:BUSINESS
=Business/Other Interests
There is nothing here yet.
+187
View File
@@ -0,0 +1,187 @@
// Package termid is CompuServe's terminal identification: the host sends
// ESC I and a terminal that knows it answers with what it is and can do,
//
// #<product>[:<version>[:<os>]],<code>,<code>,...,+<checksum>CR
//
// (#WINCIM:3.0.1:WN6,PB,...,AP,+4657), the checksum the sum of the
// characters from '#' through '+' in decimal. Older terminals give no
// checksum (#IB1,PB,DT); a VIDTEX answers RS 4. Codes this host uses:
// PB (B protocol), AP (the application protocol: CIM's HMI), CA (ANSI
// cursor), AC (ANSI colour), CC (VIDTEX/VT52 cursor), GF (GIF), GH and GM
// (RLE graphics).
package termid
import (
"bufio"
"errors"
"os"
"strconv"
"strings"
"time"
)
// Caps is what a terminal said of itself.
type Caps struct {
Raw string // the reply as sent, without its CR
Product string // WINCIM, OZ3, IB1...
Version string
OS string
Codes []string // the capability codes, as sent
Checksum int // -1 if none was sent
Vidtex bool // an old VIDTEX's RS 4
}
// Has reports whether the terminal gave code (or one beginning with it:
// "SS" for "SS7o").
func (c *Caps) Has(code string) bool {
if c == nil {
return false
}
for _, k := range c.Codes {
if k == code || len(code) == 2 && strings.HasPrefix(k, code) {
return true
}
}
return false
}
// AP is a terminal speaking the application protocol: a CIM client.
func (c *Caps) AP() bool { return c.Has("AP") }
// B is a terminal claiming the B protocol (the ENQ test decides).
func (c *Caps) B() bool { return c.Has("PB") }
// Sum is the checksum of a reply: its characters through '+'.
func Sum(s string) int {
n := 0
for i := 0; i < len(s); i++ {
n += int(s[i])
if s[i] == '+' && (i+1 == len(s) || s[i+1] >= '0' && s[i+1] <= '9') {
break
}
}
return n
}
// ErrBadChecksum is a reply whose checksum does not add up.
var ErrBadChecksum = errors.New("termid: bad checksum")
// Parse reads a reply (CR removed). A reply with a checksum that does not
// add up is returned with ErrBadChecksum: the host asks again, and takes
// it if it comes twice the same.
func Parse(s string) (*Caps, error) {
s = strings.TrimRight(s, "\r\n")
c := &Caps{Raw: s, Checksum: -1}
if strings.HasPrefix(s, "\x1e4") || s == "\x1e" {
c.Vidtex = true
return c, nil
}
if !strings.HasPrefix(s, "#") {
return nil, errors.New("termid: not an identification")
}
body := s[1:]
if i := strings.LastIndex(body, ",+"); i >= 0 || strings.HasPrefix(body, "+") {
tail := body[i+2:]
if i < 0 {
tail = body[1:]
}
if n, err := strconv.Atoi(tail); err == nil {
c.Checksum = n
body = body[:max(i, 0)]
} else if tail == "" {
body = body[:max(i, 0)]
}
}
parts := strings.Split(body, ",")
id := strings.SplitN(parts[0], ":", 3)
c.Product = id[0]
if len(id) > 1 {
c.Version = id[1]
}
if len(id) > 2 {
c.OS = id[2]
}
for _, p := range parts[1:] {
if p = strings.TrimSpace(p); p != "" {
c.Codes = append(c.Codes, p)
}
}
if c.Checksum >= 0 && Sum(s) != c.Checksum {
return c, ErrBadChecksum
}
return c, nil
}
// Line is what Probe reads and writes: a caller's line with deadlines.
type Line interface {
Read([]byte) (int, error)
Write([]byte) (int, error)
SetReadDeadline(time.Time) error
}
// Probe sends ESC I and reads the answer, up to tries times, each waiting
// wait. nil, nil: no answer (a plain terminal). A reply whose checksum
// is wrong is asked for again and taken when it comes twice the same.
// What came that was not an answer is returned in junk (the caller's
// typing, to be put back).
func Probe(l Line, r *bufio.Reader, tries int, wait time.Duration) (caps *Caps, junk []byte, err error) {
prev := ""
for try := 0; try < tries; try++ {
if _, err := l.Write([]byte("\x1bI")); err != nil {
return nil, junk, err
}
reply, j, err := readReply(l, r, wait)
junk = append(junk, j...)
if err != nil {
return nil, junk, err
}
if reply == "" {
return nil, junk, nil
}
c, perr := Parse(reply)
if perr == nil {
return c, junk, nil
}
if errors.Is(perr, ErrBadChecksum) && reply == prev {
return c, junk, nil
}
prev = reply
}
return nil, junk, nil
}
// readReply reads a "#..." or RS reply to CR, within wait; "" if none.
func readReply(l Line, r *bufio.Reader, wait time.Duration) (string, []byte, error) {
deadline := time.Now().Add(wait)
l.SetReadDeadline(deadline)
defer l.SetReadDeadline(time.Time{})
var b []byte
var junk []byte
started := false
for len(b) < 512 {
c, err := r.ReadByte()
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
return "", append(junk, b...), nil
}
return "", junk, err
}
if !started {
if c == '#' || c == 0x1e {
started = true
} else {
junk = append(junk, c)
continue
}
}
if c == '\r' || c == '\n' {
return string(b), junk, nil
}
b = append(b, c)
if len(b) == 2 && b[0] == 0x1e {
// VIDTEX: RS 4 and a CR, which may not come
l.SetReadDeadline(time.Now().Add(200 * time.Millisecond))
}
}
return string(b), junk, nil
}
+74
View File
@@ -0,0 +1,74 @@
package termid
import (
"bufio"
"net"
"strconv"
"testing"
"time"
)
func TestParse(t *testing.T) {
oz := "#OZ3,OzCIS1,AC,CA,SSxx,GF,PB,DT,+"
oz += strconv.Itoa(Sum(oz))
cases := []struct {
in string
product string
ap, b bool
err error
}{
{"#IB1,PB,DT", "IB1", false, true, nil},
{oz, "OZ3", false, true, nil},
{"#WINCIM:3.0.1:WN6,PB,DT,CA,GF,AP,+1", "WINCIM", true, true, ErrBadChecksum},
{"#PC3:3.2a:D,CC,GH,GM,GF,PB,+1680", "PC3", false, true, nil},
}
for _, c := range cases {
caps, err := Parse(c.in)
if err != c.err {
t.Errorf("%q: %v", c.in, err)
}
if caps == nil || caps.Product != c.product || caps.AP() != c.ap || caps.B() != c.b {
t.Errorf("%q: %+v", c.in, caps)
}
}
c, _ := Parse("#PC3:3.2a:D,CC,GH,GM,GF,PB,+1680")
if c.Version != "3.2a" || c.OS != "D" || !c.Has("GH") || c.Checksum != 1680 {
t.Errorf("%+v", c)
}
if c, err := Parse("\x1e4"); err != nil || !c.Vidtex {
t.Errorf("vidtex: %+v %v", c, err)
}
}
func TestProbe(t *testing.T) {
a, b := net.Pipe()
defer a.Close()
go func() {
buf := make([]byte, 2)
b.Read(buf)
// a bad checksum, twice: taken
b.Write([]byte("x#WINCIM:3.0.1:WN6,PB,AP,+1\r"))
b.Read(buf)
b.Write([]byte("#WINCIM:3.0.1:WN6,PB,AP,+1\r"))
}()
c, junk, err := Probe(a, bufio.NewReader(a), 10, time.Second)
if err != nil || c == nil || !c.AP() || string(junk) != "x" {
t.Fatalf("%+v %q %v", c, junk, err)
}
// nobody there
x, y := net.Pipe()
defer x.Close()
go func() {
buf := make([]byte, 8)
for {
if _, err := y.Read(buf); err != nil {
return
}
}
}()
c, _, err = Probe(x, bufio.NewReader(x), 3, 50*time.Millisecond)
if c != nil || err != nil {
t.Errorf("silent: %+v %v", c, err)
}
y.Close()
}
+107
View File
@@ -0,0 +1,107 @@
package server
import (
"strconv"
"strings"
"testing"
"time"
"github.com/D-Modem/bbs/internal/bbs"
)
func cisListener() *Listener {
return &Listener{Name: "cis", Kind: "raw", Address: "cis.sock", Frontend: "compuserve", Connect: "9600"}
}
// TestCompuServe: a terminal caller logs on with a User ID, finds their
// way through the pages and signs off; then a bad password, and a name
// for the User ID.
func TestCompuServe(t *testing.T) {
e := start(t, func(s *bbs.Settings) { s.FailDelay = 0 }, cisListener())
d := e.dial("cis.sock")
d.expect("CONNECT 9600\r\n")
d.expect("Host Name: ")
d.send("CIS\r")
d.expect("User ID: ")
d.send("72000,1\r")
d.expect("Password: ")
d.send("wrong\r")
d.expect("?? LOGINE - Invalid entry - try again")
d.expect("User ID: ")
d.send("72000,1;TTY\r")
d.expect("Password: ")
d.send("alicepass1\r")
d.expect("\x1bI") // the terminal's identification, unanswered
d.expect("CompuServe Information Service\r\n")
d.expect("CompuServe" + strings.Repeat(" ", 80-len("CompuServe")-len("TOP")) + "TOP\r\n")
if strings.Contains(string(d.before), "Your User ID") {
t.Error("the User ID shown to a caller who gave it")
}
d.expect(" 1 Member Assistance (FREE)\r\n")
d.expect("12 Business/Other Interests\r\n")
d.expect("Enter choice !")
d.send("1\r")
d.expect("MEMBER\r\n")
d.expect("Enter choice !")
d.send("3\r")
d.expect("RATES\r\n")
d.expect("Connect time on this service is free")
d.expect("Last page !")
d.send("\r") // back to the menu
d.expect(" 3 Rates and Billing")
d.expect("Enter choice !")
d.send("GO BILLS\r")
d.expect("BILLS is unrecognized !")
d.send("SET BRI ON;GO SOURCE\r")
d.expect("OK\r\n")
d.expect("https://github.com/D-Modem/bbs")
d.expect("\r\n!")
d.send("FIND mail\r")
d.expect("Index of MAIL")
d.expect("[GO MAIL]")
d.send("T\r")
d.expect(" 2 Find a Topic")
d.send("off\r")
d.expect("Thank you for using CompuServe!\r\nOff at ")
d.expect("Connect time = 0:01\r\n")
d = e.dial("cis.sock")
d.expect("Host Name: ")
d.send("cps\r")
d.expect("User ID: ")
d.send("sysop/INT:60\r")
d.expect("Password: ")
d.send("sysoppass1\r")
d.expect("Your User ID is 72000,2")
d.send("LOG\r")
d.expect("Thank you for using CompuServe!")
d.expect("User ID: ")
}
// TestCompuServeCIM: a CIM client (AP in its identification) is turned
// away with ?LOG CAI until the HMI service is here.
func TestCompuServeCIM(t *testing.T) {
e := start(t, nil, cisListener())
d := e.dial("cis.sock")
d.expect("Host Name: ")
d.send("CPS\r")
d.expect("User ID: ")
d.send("alice\r")
d.expect("Password: ")
d.send("alicepass1\r")
d.expect("\x1bI")
reply := "#WINCIM:3.0.1:WN6,PB,DT,CA,GF,AP,+"
sum := 0
for i := 0; i < len(reply); i++ {
sum += int(reply[i])
}
d.send(reply + strconv.Itoa(sum) + "\r")
d.expect("?LOG CAI")
d.c.SetReadDeadline(time.Now().Add(5 * time.Second))
buf := make([]byte, 64)
for {
if _, err := d.c.Read(buf); err != nil {
break // hung up
}
}
}
+18
View File
@@ -532,6 +532,24 @@ func listener(sec *config.Section) (*Listener, error) {
if l.MaxPerIP, err = sec.Int("max_per_ip", 4, 0, 1000); err != nil {
return nil, err
}
switch l.Frontend = strings.ToLower(sec.String("frontend", "bbs")); l.Frontend {
case "bbs":
l.Frontend = ""
case "compuserve":
if l.Kind != "telnet" && l.Kind != "raw" {
return nil, errors.New("frontend: compuserve is for telnet and raw listeners")
}
if sec.Has("tn3270") && l.TN3270 {
return nil, errors.New("tn3270: not with frontend = compuserve")
}
l.TN3270 = false
default:
return nil, fmt.Errorf("frontend: %q is not bbs or compuserve", l.Frontend)
}
l.Connect = sec.String("connect", map[bool]string{true: "9600", false: ""}[l.Kind == "telnet"])
if sec.Has("connect") && l.Frontend == "" {
return nil, errors.New("connect: only for frontend = compuserve")
}
mode := sec.String("socket_mode", "0660")
m, err := strconv.ParseUint(mode, 8, 32)
if err != nil || m > 0777 {
+26 -3
View File
@@ -41,6 +41,7 @@ import (
"golang.org/x/crypto/ssh"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/cis"
"github.com/D-Modem/bbs/internal/sockets"
"github.com/D-Modem/bbs/internal/telnet"
"github.com/D-Modem/bbs/internal/textui"
@@ -69,6 +70,10 @@ type Listener struct {
SocketGroup string
HostKeys []string // ssh: the host keys' files
Legacy bool // ssh: offer old algorithms too (CBC ciphers, DH group 1)
// Frontend is what callers get: "" the BBS, "compuserve" the
// CompuServe Information Service (internal/cis)
Frontend string
Connect string // compuserve: the CONNECT line's rate ("": no line)
// TLS: telnet or raw over TLS (telnets, port 992), with this
// certificate and key
CertFile, KeyFile string
@@ -391,10 +396,12 @@ func (s *Server) handle(nc net.Conn, l *Listener) {
defer node.Leave()
s.B.Log.Printf("node %d: %s on [listen %s]%s", node.Num, remote, l.Name, callDetails(caller, node.Place()))
switch l.Kind {
case "telnet":
switch {
case l.Frontend == "compuserve":
err = s.compuserve(c, l, node)
case l.Kind == "telnet":
err = s.telnet(c, l, node)
case "rlogin":
case l.Kind == "rlogin":
err = s.rlogin(c, l, node)
default:
err = s.text(c, c, l, node, "")
@@ -463,6 +470,22 @@ func (s *Server) telnet(c net.Conn, l *Listener, node *bbs.Node) error {
return s.text(tc, c, l, node, tt)
}
// compuserve runs the CompuServe service on a call: over telnet, in
// binary both ways and without the BBS's terminal probes (CompuServe's
// terminals take ENQ and ESC [ > 0 q for their own protocols).
func (s *Server) compuserve(c net.Conn, l *Listener, node *bbs.Node) error {
opt := cis.Options{Connect: l.Connect}
if l.Kind != "telnet" {
return cis.Run(s.B, node, c, opt)
}
tc := telnet.New(c)
if err := tc.StartNVT(true, 2*time.Second); err != nil {
return err
}
node.SetTerminal(node.Caller.Via, tc.TermType())
return cis.Run(s.B, node, tc, opt)
}
// tn3270 hands a telnet connection to go3270 and runs the 3270 BBS on it;
// a client that stops answering during the negotiation is hung up after
// 30 seconds.
+945
View File
@@ -0,0 +1,945 @@
package xfer
// CompuServe B, Interim ("Quick") B and B Plus, the host's side and the
// terminal's.
//
// The host starts everything: it sends ENQ while the terminal is in plain
// terminal mode, the terminal's answer says which B it speaks (DLE '0';
// DLE '+' DLE '0'; DLE '+' '+' DLE '0'), and B Plus terminals then trade
// transport parameters ('+' packets) before the first transfer.
//
// A packet is DLE 'B' <seq> <type> <body> ETX <check>, the body and check
// quoted (a control byte c goes as DLE c+0x40, a byte 0x80-0x9F as DLE
// (c&0x1F)+0x60), the check over seq, type, body and ETX before quoting.
// ACK is DLE <seq>, NAK is NAK. Sources: Russ Ranshaw, "The CompuServe B
// Plus Protocol" (1993); Steve Wilhite's bp.c (1985); Steve Sneed's
// OOBPLUS (1991).
import (
"bytes"
"errors"
"fmt"
"hash/crc32"
"io"
"time"
)
const (
bETX = 0x03
bENQ = 0x05
bDLE = 0x10
bNAK = 0x15
bRS = 0x1E
)
// Check methods of B Plus.
const (
CheckSum = 0 // the 8-bit rotate-and-add checksum
CheckCRC16 = 1 // CRC-16/XMODEM with a preset of 0xFFFF, high byte first
CheckCCITT = 2 // CRC-16/X-25, low byte first
CheckCRC32 = 3 // CRC-32 (zlib), low byte first
)
// BParams are B Plus transport parameters, in the order a '+' packet
// carries them.
type BParams struct {
WS, WR byte // windows, send and receive: outstanding packets less one
BS byte // block size / 128 (0 means 4: 512)
CM byte // check method
DQ byte // obsolete quote level, unused when Q is given
TL byte // 1: the Transport Layer (for CIM's HMI)
Q [8]byte // quote masks: 0x00-0x1F, then 0x80-0x9F, bit 7 first
DR byte // download resume: 0 none, 1 Tr, 2 Tr and Tf
UR byte // upload resume (CIS: none)
FI byte // 1: the TI file information packet
}
// HostParams are the parameters this host offers: two packets outstanding
// each way, 1 KB blocks, CRC-16, CompuServe's own quote set, no transport
// layer, resume or file information.
var HostParams = BParams{WS: 1, WR: 1, BS: 8, CM: CheckCRC16, DQ: 1,
Q: [8]byte{0x14, 0x00, 0xD4, 0x02, 0x00, 0x00, 0x50, 0x00}}
func (p BParams) bytes() []byte {
b := []byte{p.WS, p.WR, p.BS, p.CM, p.DQ, p.TL}
b = append(b, p.Q[:]...)
return append(b, p.DR, p.UR, p.FI)
}
func parseBParams(b []byte) BParams {
f := make([]byte, 17)
copy(f, b)
p := BParams{WS: f[0], WR: f[1], BS: f[2], CM: f[3], DQ: f[4], TL: f[5], DR: f[14], UR: f[15], FI: f[16]}
copy(p.Q[:], f[6:14])
if len(b) < 7 {
// no quote masks: from the old quote level
p.Q = dqMasks(p.DQ)
}
return p
}
// dqMasks are the quote masks of an old quote level.
func dqMasks(dq byte) [8]byte {
switch dq {
case 0:
return [8]byte{0x94, 0x00, 0xD4, 0x00} // 00 03 05 10 11 13 15
case 1:
return [8]byte{0x14, 0x00, 0xD4, 0x00}
case 2:
return [8]byte{0x14, 0x00, 0xD4, 0x00, 0x00, 0x00, 0x50, 0x00}
}
return [8]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
}
// negotiate is what both sides use after trading parameters: windows
// crossed, the least of the rest, quote masks or'ed.
func negotiate(mine, theirs BParams) BParams {
m := func(a, b byte) byte { return min(a, b) }
r := BParams{WS: m(mine.WS, theirs.WR), WR: m(mine.WR, theirs.WS), BS: m(blockUnits(mine.BS), blockUnits(theirs.BS)),
CM: m(mine.CM, theirs.CM), TL: m(mine.TL, theirs.TL), DR: m(mine.DR, theirs.DR),
UR: m(mine.UR, theirs.UR), FI: m(mine.FI, theirs.FI)}
if r.CM > CheckCRC32 {
r.CM = CheckSum
}
for i := range r.Q {
r.Q[i] = mine.Q[i] | theirs.Q[i]
}
return r
}
func blockUnits(bs byte) byte {
switch {
case bs == 0:
return 4
case bs > 16:
return 16
}
return bs
}
// BChecksum is B's 8-bit checksum: rotate left, add, carry around.
func BChecksum(p []byte) byte {
ck := 0
for _, b := range p {
ck <<= 1
if ck > 0xFF {
ck = ck&0xFF + 1
}
ck += int(b)
if ck > 0xFF {
ck = ck&0xFF + 1
}
}
return byte(ck)
}
// crcX25 is CRC-16/X-25 before its complement: reflected 0x8408, preset
// 0xFFFF.
func crcX25(data []byte, crc uint16) uint16 {
for _, b := range data {
crc ^= uint16(b)
for i := 0; i < 8; i++ {
if crc&1 != 0 {
crc = crc>>1 ^ 0x8408
} else {
crc >>= 1
}
}
}
return crc
}
// bCheck is the check value of p by method cm, as sent.
func bCheck(cm byte, p []byte) []byte {
switch cm {
case CheckCRC16:
c := crc16(p, 0xFFFF)
return []byte{byte(c >> 8), byte(c)}
case CheckCCITT:
c := ^crcX25(p, 0xFFFF)
return []byte{byte(c), byte(c >> 8)}
case CheckCRC32:
c := crc32.ChecksumIEEE(p)
return []byte{byte(c), byte(c >> 8), byte(c >> 16), byte(c >> 24)}
}
return []byte{BChecksum(p)}
}
// BPacket is a B packet: its sequence digit ('0'-'9'), type and body.
type BPacket struct {
Seq byte
Type byte
Body []byte
}
// B errors.
var (
ErrBAborted = errors.New("B: aborted by the other side")
ErrBFallback = errors.New("B: the terminal fell back to terminal mode")
)
// BFailure is an F packet: the other side gave up.
type BFailure struct {
Code byte
Text string
}
func (f *BFailure) Error() string {
if f.Text != "" {
return fmt.Sprintf("B: failure %c: %s", f.Code, f.Text)
}
return fmt.Sprintf("B: failure %c", f.Code)
}
// BLink is one side of a B link. Its zero timeouts are the protocol's:
// 10 seconds a character, 10 errors.
type BLink struct {
l *line
Timeout time.Duration // the most to wait for a byte
Errors int // the most errors in a row
Plus bool // the terminal spoke Interim B or B Plus ('+' seen)
PlusPlus bool // ...B Plus
Relaxed bool // the terminal asked for relaxed timing
Params BParams // negotiated: the zero value for Classic B
quote [256]bool
seq byte // the sequence digit of the last packet sent or taken
last []byte
// ahead is a packet read while waiting for an ACK: the other side's
// next, which ACKs ours by implication
ahead *BPacket
}
// NewBLink is a B link on p, as Classic B with every control byte quoted.
func NewBLink(p Port) *BLink {
k := &BLink{l: newLine(p), seq: '0'}
k.setQuote([]byte{0xFF, 0xFF, 0xFF, 0xFF}, [4]byte{})
return k
}
func (k *BLink) timeout() time.Duration {
d := k.Timeout
if d == 0 {
d = 10 * time.Second
}
if k.Relaxed {
d *= 2
}
return d
}
func (k *BLink) maxErrors() int {
if k.Errors == 0 {
return 10
}
return k.Errors
}
// setQuote sets the quote set from the masks of 0x00-0x1F (lo) and
// 0x80-0x9F (hi). DLE is always quoted.
func (k *BLink) setQuote(lo []byte, hi [4]byte) {
for i := 0; i < 32; i++ {
k.quote[i] = lo[i/8]&(0x80>>(i%8)) != 0
k.quote[0x80+i] = hi[i/8]&(0x80>>(i%8)) != 0
}
k.quote[bDLE] = true
k.quote[bETX] = true
}
func (k *BLink) quoteAll() {
for i := 0; i < 32; i++ {
k.quote[i], k.quote[0x80+i] = true, true
}
}
func (k *BLink) applyParams() {
var hi [4]byte
copy(hi[:], k.Params.Q[4:])
k.setQuote(k.Params.Q[:4], hi)
}
// BlockSize is how much data a packet may carry.
func (k *BLink) BlockSize() int {
if !k.PlusPlus {
return 511
}
return int(blockUnits(k.Params.BS)) * 128
}
func next(s byte) byte {
if s >= '9' {
return '0'
}
return s + 1
}
// encode makes the bytes of a packet.
func (k *BLink) encode(p BPacket, cm byte) []byte {
raw := append([]byte{p.Seq, p.Type}, p.Body...)
raw = append(raw, bETX)
var b bytes.Buffer
b.Write([]byte{bDLE, 'B', p.Seq, p.Type})
q := func(c byte) {
if k.quote[c] {
if c < 0x80 {
b.Write([]byte{bDLE, c + 0x40})
} else {
b.Write([]byte{bDLE, c&0x1F + 0x60})
}
} else {
b.WriteByte(c)
}
}
for _, c := range p.Body {
q(c)
}
b.WriteByte(bETX)
for _, c := range bCheck(cm, raw) {
q(c)
}
if cm >= CheckCCITT {
b.WriteByte(bRS)
}
return b.Bytes()
}
// send sends packet p with check method cm.
func (k *BLink) send(p BPacket, cm byte) error {
b := k.encode(p, cm)
k.last = b
return k.l.write(b)
}
// what the link read
const (
evPacket = iota
evACK
evNAK
evENQ
evWACK
evBad // a packet whose check failed
)
type bEvent struct {
kind int
seq byte
pkt BPacket
}
// read waits for the next thing from the other side.
func (k *BLink) read(cm byte) (bEvent, error) {
dles := 0
for {
c, err := k.l.getc(k.timeout())
if err != nil {
return bEvent{}, err
}
switch c {
case bNAK:
return bEvent{kind: evNAK}, nil
case bENQ:
return bEvent{kind: evENQ}, nil
case bDLE:
dles++
if dles >= 4 {
return bEvent{}, ErrBAborted
}
continue
}
if dles == 0 {
continue // noise between packets
}
dles = 0
switch {
case c >= '0' && c <= '9':
return bEvent{kind: evACK, seq: c}, nil
case c == ';':
return bEvent{kind: evWACK}, nil
case c == '+':
return bEvent{}, ErrBFallback
case c == 'B':
p, ok, err := k.readPacket(cm)
if err != nil {
return bEvent{}, err
}
if !ok {
return bEvent{kind: evBad}, nil
}
return bEvent{kind: evPacket, seq: p.Seq, pkt: p}, nil
}
}
}
// readPacket reads a packet after its DLE 'B': ok false if its check is
// wrong.
func (k *BLink) readPacket(cm byte) (BPacket, bool, error) {
d := k.timeout()
getq := func() (byte, bool, error) { // a byte, unquoted; raw ETX
c, err := k.l.getc(d)
if err != nil {
return 0, false, err
}
if c == bETX {
return c, true, nil
}
if c != bDLE {
return c, false, nil
}
c, err = k.l.getc(d)
if err != nil {
return 0, false, err
}
if c < 0x60 {
return c & 0x1F, false, nil
}
return c&0x1F | 0x80, false, nil
}
var raw []byte
limit := 2048 + 3
for {
c, etx, err := getq()
if err != nil {
return BPacket{}, false, err
}
raw = append(raw, c)
if etx {
break
}
if len(raw) > limit {
return BPacket{}, false, nil
}
}
n := len(bCheck(cm, nil))
got := make([]byte, n)
for i := range got {
c, _, err := getq()
if err != nil {
return BPacket{}, false, err
}
got[i] = c
}
if len(raw) < 3 || !bytes.Equal(got, bCheck(cm, raw)) {
return BPacket{}, false, nil
}
return BPacket{Seq: raw[0], Type: raw[1], Body: raw[2 : len(raw)-1]}, true, nil
}
func (k *BLink) ack(s byte) error { return k.l.write([]byte{bDLE, s}) }
// SendPacket sends a packet of typ and waits for its ACK (stop and wait).
// A packet from the other side while waiting, with the next sequence, ACKs
// it too: it is kept for ReadPacket.
func (k *BLink) SendPacket(typ byte, body []byte) error {
return k.sendWait(typ, body, k.Params.CM)
}
func (k *BLink) sendWait(typ byte, body []byte, cm byte) error {
s := next(k.seq)
p := BPacket{Seq: s, Type: typ, Body: body}
if err := k.send(p, cm); err != nil {
return err
}
k.seq = s
errs := 0
for {
ev, err := k.read(cm)
if errors.Is(err, ErrTimeout) {
ev, err = bEvent{kind: evNAK}, nil
}
if err != nil {
return err
}
switch ev.kind {
case evACK:
if ev.seq == s {
return nil
}
continue // an old ACK
case evWACK:
continue
case evPacket:
if ev.seq == next(s) {
k.ahead = &ev.pkt
return nil
}
if ev.pkt.Type == 'F' {
k.ack(ev.seq)
return failure(ev.pkt)
}
case evENQ:
k.ack(k.seq)
continue
}
if errs++; errs >= k.maxErrors() {
return ErrRetries
}
if err := k.l.write(k.last); err != nil {
return err
}
}
}
func failure(p BPacket) error {
f := &BFailure{Code: 'E'}
if len(p.Body) > 0 {
f.Code, f.Text = p.Body[0], string(p.Body[1:])
}
return f
}
// ReadPacket waits for the other side's next packet and ACKs it. A
// repeat of the last is ACKed again and dropped; a bad one is NAKed.
func (k *BLink) ReadPacket() (BPacket, error) {
return k.readCM(k.Params.CM)
}
func (k *BLink) readCM(cm byte) (BPacket, error) {
if p := k.ahead; p != nil {
k.ahead = nil
k.seq = p.Seq
return *p, k.ack(p.Seq)
}
errs := 0
for {
ev, err := k.read(cm)
if err != nil && !errors.Is(err, ErrTimeout) {
return BPacket{}, err
}
if err == nil {
switch ev.kind {
case evPacket:
switch ev.seq {
case next(k.seq):
k.seq = ev.seq
return ev.pkt, k.ack(ev.seq)
case k.seq:
k.ack(ev.seq)
continue
}
if ev.pkt.Type == 'F' {
k.ack(ev.seq)
return BPacket{}, failure(ev.pkt)
}
// out of order: one before it was lost. The sender
// resends from there when it hears nothing.
if errs++; errs >= 4*k.maxErrors() {
return BPacket{}, ErrRetries
}
continue
case evENQ:
k.ack(k.seq)
continue
case evACK, evWACK:
continue
}
}
if errs++; errs >= 4*k.maxErrors() {
return BPacket{}, ErrRetries
}
if err := k.l.write([]byte{bNAK}); err != nil {
return BPacket{}, err
}
}
}
// Fail sends an F packet (code: A abort, E error, I I/O, M missing...),
// which ends the link.
func (k *BLink) Fail(code byte, text string) error {
return k.SendPacket('F', append([]byte{code}, text...))
}
// Start is the host's ENQ: up to 5 of them, until the terminal answers.
// Then B Plus terminals are sent the host's parameters, and theirs read.
func (k *BLink) Start(host BParams) error {
var err error
for try := 0; try < 5; try++ {
if err = k.l.write([]byte{bENQ}); err != nil {
return err
}
if err = k.enqReply(); err == nil {
break
}
if !errors.Is(err, ErrTimeout) && !errors.Is(err, ErrProtocol) {
return err
}
}
if err != nil {
return err
}
if !k.Plus {
return nil
}
return k.hostPlus(host)
}
// enqReply reads [DLE '+' ['+'] ['R']] DLE digit.
func (k *BLink) enqReply() error {
d := k.timeout()
if d > 5*time.Second {
d = 5 * time.Second
}
for {
c, err := k.l.getc(d)
if err != nil {
return err
}
if c != bDLE {
continue
}
c, err = k.l.getc(d)
if err != nil {
return err
}
if c >= '0' && c <= '9' {
k.seq = c
return nil
}
if c != '+' {
return ErrProtocol
}
k.Plus = true
for {
c, err = k.l.getc(d)
if err != nil {
return err
}
switch c {
case '+':
k.PlusPlus = true
continue
case 'R':
k.Relaxed = true
continue
}
break
}
if c != bDLE {
return ErrProtocol
}
if c, err = k.l.getc(d); err != nil {
return err
}
if c < '0' || c > '9' {
return ErrProtocol
}
k.seq = c
return nil
}
}
// hostPlus trades '+' packets: the host's, with the standard check and
// everything quoted; then the terminal's.
func (k *BLink) hostPlus(host BParams) error {
if k.PlusPlus {
k.quoteAll()
}
err := k.sendWait('+', host.bytes(), CheckSum)
if err != nil {
return err
}
p, err := k.readCM(CheckSum)
if err != nil {
return err
}
if p.Type != '+' {
return ErrProtocol
}
k.Params = negotiate(host, parseBParams(p.Body))
k.applyParams()
return nil
}
// AnswerENQ is the terminal's side of the host's ENQ: it says it speaks
// B Plus when params is non-nil, else Classic B; then trades parameters.
func (k *BLink) AnswerENQ(params *BParams) error {
for {
c, err := k.l.getc(k.timeout())
if err != nil {
return err
}
if c == bENQ {
break
}
}
k.seq = '0'
if params == nil {
return k.l.write([]byte{bDLE, '0'})
}
k.Plus, k.PlusPlus = true, true
if err := k.l.write([]byte{bDLE, '+', '+', bDLE, '0'}); err != nil {
return err
}
k.quoteAll()
p, err := k.readNoAck(CheckSum)
if err != nil {
return err
}
if p.Type != '+' {
return ErrProtocol
}
host := parseBParams(p.Body)
// our parameters ACK theirs
if err := k.sendWait('+', params.bytes(), CheckSum); err != nil {
return err
}
k.Params = negotiate(*params, host)
k.applyParams()
return nil
}
// readNoAck reads the next packet without ACKing it: the reply does.
func (k *BLink) readNoAck(cm byte) (BPacket, error) {
errs := 0
for {
ev, err := k.read(cm)
if err != nil && !errors.Is(err, ErrTimeout) {
return BPacket{}, err
}
if err == nil && ev.kind == evPacket && ev.seq == next(k.seq) {
k.seq = ev.seq
return ev.pkt, nil
}
if err == nil && ev.kind == evPacket && ev.pkt.Type == 'F' {
k.ack(ev.seq)
return BPacket{}, failure(ev.pkt)
}
if errs++; errs >= k.maxErrors() {
return BPacket{}, ErrRetries
}
k.l.write([]byte{bNAK})
}
}
// sendWindow sends data packets of typ, as many outstanding as the
// window lets; a NAK or a timeout resends all not yet ACKed.
func (k *BLink) sendWindow(typ byte, r io.Reader) (int64, error) {
win := int(k.Params.WS) + 1
if !k.PlusPlus || win < 1 {
win = 1
}
if win > 9 {
win = 9
}
type sent struct {
seq byte
raw []byte
}
var out []sent
var total int64
eof := false
buf := make([]byte, k.BlockSize())
errs := 0
resync := false
for !eof || len(out) > 0 {
for !resync && !eof && len(out) < win {
n, err := io.ReadFull(r, buf)
if err == io.EOF || err == io.ErrUnexpectedEOF {
eof = true
if n == 0 {
break
}
} else if err != nil {
k.Fail('I', "read error")
return total, err
}
s := next(k.seq)
b := k.encode(BPacket{Seq: s, Type: typ, Body: buf[:n]}, k.Params.CM)
if err := k.l.write(b); err != nil {
return total, err
}
k.seq = s
out = append(out, sent{s, b})
total += int64(n)
}
if len(out) == 0 {
break
}
ev, err := k.read(k.Params.CM)
if errors.Is(err, ErrTimeout) {
ev, err = bEvent{kind: evNAK, seq: 'T'}, nil
}
if err != nil {
return total, err
}
switch ev.kind {
case evACK:
for i, o := range out {
if o.seq == ev.seq {
out = out[i+1:]
errs = 0
break
}
}
if resync {
// the receiver's last good packet: resend those after it
resync = false
for _, o := range out {
if err := k.l.write(o.raw); err != nil {
return total, err
}
}
}
continue
case evWACK:
continue
case evPacket:
if ev.pkt.Type == 'F' {
k.ack(ev.seq)
return total, failure(ev.pkt)
}
case evENQ:
k.ack(k.seq)
continue
case evNAK:
if resync && !timedOut(ev) {
continue // more NAKs of the same loss
}
}
if errs++; errs >= k.maxErrors() {
return total, ErrRetries
}
// resynchronize: ENQ asks for the receiver's last good packet
resync = true
if err := k.l.write([]byte{bENQ}); err != nil {
return total, err
}
}
return total, nil
}
// timedOut: the NAK stands for a timeout.
func timedOut(ev bEvent) bool { return ev.seq == 'T' }
// SendFile is a host's download: TD (binary, or ASCII), the data, TC.
func (k *BLink) SendFile(name string, binary bool, r io.Reader) (int64, error) {
dt := byte('A')
if binary {
dt = 'B'
}
if err := k.SendPacket('T', append([]byte{'D', dt}, name...)); err != nil {
return 0, err
}
if k.ahead != nil {
// the terminal answered TD with a packet: Tr (resume, which we do
// not offer) or F
p := *k.ahead
k.ahead = nil
k.seq = p.Seq
k.ack(p.Seq)
if p.Type == 'F' {
return 0, failure(p)
}
}
n, err := k.sendWindow('N', r)
if err != nil {
return n, err
}
return n, k.SendPacket('T', []byte{'C'})
}
// ReceiveFile is a host's upload: TU (binary or ASCII) names the file to
// the terminal, which sends N packets and TC. The terminal does not ACK
// TU: its first packet does.
func (k *BLink) ReceiveFile(name string, binary bool, w io.Writer, max int64) (int64, error) {
dt := byte('A')
if binary {
dt = 'B'
}
s := next(k.seq)
if err := k.send(BPacket{Seq: s, Type: 'T', Body: append([]byte{'U', dt}, name...)}, k.Params.CM); err != nil {
return 0, err
}
k.seq = s
var total int64
for {
p, err := k.ReadPacket()
if err != nil {
return total, err
}
switch {
case p.Type == 'N':
if max > 0 && total+int64(len(p.Body)) > max {
k.Fail('C', "file too large")
return total, errors.New("B: upload too large")
}
if _, err := w.Write(p.Body); err != nil {
k.Fail('I', "write error")
return total, err
}
total += int64(len(p.Body))
case p.Type == 'T' && len(p.Body) > 0 && p.Body[0] == 'C':
return total, nil
case p.Type == 'F':
return total, failure(p)
default:
k.Fail('N', "unexpected packet")
return total, ErrProtocol
}
}
}
// Terminal is the terminal's side of transfers the host starts: it reads
// T packets and does them. open gives a writer for a download (an error
// refuses it); upload gives the data of a file the host asks for. It
// returns after a transfer completes.
func (k *BLink) Terminal(open func(name string, binary bool) (io.Writer, error),
upload func(name string) (io.Reader, error)) error {
p, err := k.readNoAck(k.Params.CM)
if err != nil {
return err
}
if p.Type != 'T' || len(p.Body) < 1 {
k.ack(p.Seq)
return ErrProtocol
}
switch p.Body[0] {
case 'D':
name := ""
bin := false
if len(p.Body) > 1 {
bin = p.Body[1] != 'A'
name = string(p.Body[2:])
}
w, err := open(name, bin)
if err != nil {
k.ack(p.Seq)
k.Fail('E', err.Error())
return err
}
k.ack(p.Seq)
for {
q, err := k.ReadPacket()
if err != nil {
return err
}
switch q.Type {
case 'N':
if _, err := w.Write(q.Body); err != nil {
return err
}
case 'T':
return nil
default:
return ErrProtocol
}
}
case 'U':
name := ""
if len(p.Body) > 1 {
name = string(p.Body[2:])
}
r, err := upload(name)
if err != nil {
k.Fail('M', err.Error())
return err
}
// our first N packet ACKs the TU
if _, err := k.sendWindow('N', r); err != nil {
return err
}
return k.SendPacket('T', []byte{'C'})
}
k.ack(p.Seq)
return ErrProtocol
}
+201
View File
@@ -0,0 +1,201 @@
package xfer
import (
"bytes"
"crypto/rand"
"io"
"net"
"sync"
"testing"
"time"
)
// TestBChecks: the spec's packet DLE B '7' "TDAS.C" ETX has checksum 0x2A
// and CRC-16 (preset 0xFFFF) 0x57FF.
func TestBChecks(t *testing.T) {
p := []byte{0x37, 0x54, 0x44, 0x41, 0x53, 0x2E, 0x43, 0x03}
if c := BChecksum(p); c != 0x2A {
t.Errorf("checksum %#x, want 0x2a", c)
}
if c := bCheck(CheckCRC16, p); !bytes.Equal(c, []byte{0x57, 0xFF}) {
t.Errorf("CRC-16 % x, want 57 ff", c)
}
// the receiver's residues
c := bCheck(CheckCCITT, p)
if r := crcX25(append(append([]byte{}, p...), c...), 0xFFFF); r != 0xF0B8 {
t.Errorf("CCITT residue %#x", r)
}
}
// TestBParams: CompuServe's host quote masks are its set, and a '+' body
// reads back as it was.
func TestBParams(t *testing.T) {
k := &BLink{}
k.Params = HostParams
k.applyParams()
var set []byte
for i, q := range k.quote {
if q {
set = append(set, byte(i))
}
}
if want := []byte{3, 5, 0x10, 0x11, 0x13, 0x15, 0x1E, 0x91, 0x93}; !bytes.Equal(set, want) {
t.Errorf("quote set % x, want % x", set, want)
}
if p := parseBParams(HostParams.bytes()); p != HostParams {
t.Errorf("parsed %+v", p)
}
// short: OzCIS's
oz := parseBParams([]byte{1, 2, 4, 1, 1, 0, 0x14, 0, 0xD4, 0, 0, 0, 0, 0, 0, 0, 1})
n := negotiate(HostParams, oz)
if n.WS != 1 || n.WR != 1 || n.BS != 4 || n.CM != 1 || n.FI != 0 {
t.Errorf("negotiated %+v", n)
}
}
// tcpPair is two ends of a loopback TCP connection (buffered, unlike
// net.Pipe, so both sides may write at once).
func tcpPair(t *testing.T) (net.Conn, net.Conn) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
ch := make(chan net.Conn)
go func() {
c, _ := ln.Accept()
ch <- c
}()
a, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatal(err)
}
b := <-ch
t.Cleanup(func() { a.Close(); b.Close() })
return a, b
}
// bNoisy corrupts every nth byte written.
type bNoisy struct {
net.Conn
mu sync.Mutex
n int
i int
}
func (c *bNoisy) Write(p []byte) (int, error) {
c.mu.Lock()
q := append([]byte{}, p...)
for j := range q {
if c.i++; c.n > 0 && c.i%c.n == 0 {
q[j] ^= 0x5A
}
}
c.mu.Unlock()
_, err := c.Conn.Write(q)
return len(p), err
}
func TestBTransfers(t *testing.T) {
data := make([]byte, 10000)
rand.Read(data)
cases := []struct {
name string
params *BParams
noise int
}{
{"classic", nil, 0},
{"plus", &BParams{WS: 2, WR: 2, BS: 8, CM: CheckCRC16, DQ: 1}, 0},
{"checksum", &BParams{WS: 0, WR: 0, BS: 4, CM: CheckSum}, 0},
{"ccitt", &BParams{WS: 1, WR: 1, BS: 16, CM: CheckCCITT}, 0},
{"crc32", &BParams{WS: 3, WR: 3, BS: 16, CM: CheckCRC32}, 0},
{"classic bNoisy", nil, 997},
{"plus bNoisy", &BParams{WS: 2, WR: 2, BS: 8, CM: CheckCRC16}, 1499},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
a, b := tcpPair(t)
var hp, tp Port = a, b
if c.noise > 0 {
hp = &bNoisy{Conn: a, n: c.noise}
tp = &bNoisy{Conn: b, n: c.noise + 2}
}
host, term := NewBLink(hp), NewBLink(tp)
host.Timeout, term.Timeout = 300*time.Millisecond, 300*time.Millisecond
host.Errors, term.Errors = 30, 30
var got bytes.Buffer
var gotName string
var gotBin bool
done := make(chan error, 1)
go func() {
if err := term.AnswerENQ(c.params); err != nil {
done <- err
return
}
err := term.Terminal(func(name string, bin bool) (io.Writer, error) {
gotName, gotBin = name, bin
return &got, nil
}, nil)
if err == nil {
// then an upload
err = term.Terminal(nil, func(name string) (io.Reader, error) {
return bytes.NewReader(data[:3333]), nil
})
}
done <- err
}()
if err := host.Start(HostParams); err != nil {
t.Fatal("start:", err)
}
if host.PlusPlus != (c.params != nil) {
t.Errorf("B Plus seen %v", host.PlusPlus)
}
n, err := host.SendFile("TEST.BIN", true, bytes.NewReader(data))
if err != nil || n != int64(len(data)) {
t.Fatalf("send: %d, %v", n, err)
}
var up bytes.Buffer
un, err := host.ReceiveFile("UP.TXT", false, &up, 1<<20)
if err != nil {
t.Fatalf("receive: %d, %v", un, err)
}
if err := <-done; err != nil {
t.Fatal("terminal:", err)
}
if gotName != "TEST.BIN" || !gotBin || !bytes.Equal(got.Bytes(), data) {
t.Errorf("download: %q %v %d bytes, equal %v", gotName, gotBin, got.Len(), bytes.Equal(got.Bytes(), data))
}
if !bytes.Equal(up.Bytes(), data[:3333]) {
t.Errorf("upload: %d bytes", up.Len())
}
})
}
}
// TestBRefused: a terminal's F packet in answer to TD ends the download.
func TestBRefused(t *testing.T) {
a, b := tcpPair(t)
host, term := NewBLink(a), NewBLink(b)
host.Timeout, term.Timeout = 300*time.Millisecond, 300*time.Millisecond
go func() {
term.AnswerENQ(nil)
term.Terminal(func(string, bool) (io.Writer, error) { return nil, io.ErrClosedPipe }, nil)
}()
if err := host.Start(HostParams); err != nil {
t.Fatal(err)
}
_, err := host.SendFile("X", true, bytes.NewReader([]byte("hello")))
if f, ok := err.(*BFailure); !ok || f.Code != 'E' {
t.Errorf("got %v", err)
}
}
// TestBNoTerminal: a terminal that never answers ENQ times out.
func TestBNoTerminal(t *testing.T) {
a, _ := tcpPair(t)
host := NewBLink(a)
host.Timeout = 50 * time.Millisecond
if err := host.Start(HostParams); err != ErrTimeout {
t.Errorf("got %v", err)
}
}