usim

Check-in [9e48bb8745]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:uch11: Split backend code to seperate files.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | ams/sdl
Files: files | file ages | folders
SHA3-256: 9e48bb874519eec74ec20b94ab1f780a4dac0ff0e8d5093d915b50a38479a120
User & Date: ams 2024-06-25 11:20:20
Context
2024-06-25
11:30
uch11: Make sure each backend now is a seperate compilation unit. check-in: 200674745d user: ams tags: ams/sdl
11:20
uch11: Split backend code to seperate files. check-in: 9e48bb8745 user: ams tags: ams/sdl
09:54
ucfg.c: Handle setting modifiers in config file. check-in: 7bf9883f4f user: ams tags: ams/sdl
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to Makefile.

50
51
52
53
54
55
56


57
58
59
60
61
62
63
64
# LDFLAGS +=
# USIM_TV_BACKEND =

ucfg.o: ucfg.h ucfg.defs lmch.defs knight.defs

$(USIM_TV_BACKEND) iob.o cadet.o knight.o usim.o: lmch.defs knight.defs



USIM_UCH11 = uch11.o chutil.o challoc.o chdopen.o chopen.o MINI.o FILE.o glob.o

USIM_OBJS = usim.o ucode.o uexec.o umem.o iob.o mouse.o kbd.o knight.o cadet.o tv.o $(USIM_TV_BACKEND) $(USIM_UCH11) disk.o ini.o ucfg.o trace.o udiss.o usym.o misc.o m32.o idle.o \
	$(CHAOS)/libhosts/libhosts.a
usim: $(USIM_OBJS)
	$(CC) $(CFLAGS) -o $@ $(USIM_OBJS) -lpthread $(LDFLAGS)

READMCR_OBJS = readmcr.o udiss.o misc.o usym.o







>
>
|







50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# LDFLAGS +=
# USIM_TV_BACKEND =

ucfg.o: ucfg.h ucfg.defs lmch.defs knight.defs

$(USIM_TV_BACKEND) iob.o cadet.o knight.o usim.o: lmch.defs knight.defs

# Add uch11-local.o uch11-chaosd.o when they can compile.
USIM_UCH11 = uch11.o uch11-udp.o \
	chutil.o challoc.o chdopen.o chopen.o MINI.o FILE.o glob.o

USIM_OBJS = usim.o ucode.o uexec.o umem.o iob.o mouse.o kbd.o knight.o cadet.o tv.o $(USIM_TV_BACKEND) $(USIM_UCH11) disk.o ini.o ucfg.o trace.o udiss.o usym.o misc.o m32.o idle.o \
	$(CHAOS)/libhosts/libhosts.a
usim: $(USIM_OBJS)
	$(CC) $(CFLAGS) -o $@ $(USIM_OBJS) -lpthread $(LDFLAGS)

READMCR_OBJS = readmcr.o udiss.o misc.o usym.o

Added uch11-chaosd.c.















































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/* Connect to a chaos daemon via a Unix socket.
 */

// #include <sys/poll.h>
// #include <sys/socket.h>
// #include <sys/stat.h>
// #include <sys/time.h>
// #include <sys/types.h>
// #include <sys/uio.h>
// #include <sys/un.h>
// 
// #include <netinet/in.h>
// 
// #include <sys/types.h>
// #include <sys/socket.h>
// #include <netdb.h>
// #include <arpa/inet.h>
// 
// #include <err.h>
// #include <pthread.h>
// #include <stddef.h>
// #include <stdint.h>
// #include <stdio.h>
// #include <stdlib.h>
// #include <string.h>
// #include <time.h>
// #include <unistd.h>
// 
// #include "uch11.h"
// #include "chaosd.h"
// #include "hosttab.h"
// #include "misc.h"
// #include "ucfg.h"
// #include "ucode.h"
// #include "usim.h"
// #include "utrace.h"

#define UNIX_SOCKET_PATH	"/var/tmp/"
#define UNIX_SOCKET_CLIENT_NAME	"chaosd_"
#define UNIX_SOCKET_SERVER_NAME	"chaosd_server"
#define UNIX_SOCKET_PERM	S_IRWXU

static int
chaos_send_to_chaosd(char *buffer, int size)
{
	int wcount, dest_addr;

	/*
	 * Local loopback.
	 */
	if (uch11_csr & CHAOS_CSR_LOOP_BACK) {
		DEBUG(TRACE_CHAOS, "chaos: loopback %d bytes\n", size);
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
		return 0;
	}
	wcount = (size + 1) / 2;
	dest_addr = ((unsigned short *) buffer)[wcount - 3];
	DEBUG(TRACE_CHAOS, "chaos: sending packet to chaosd (dest_addr=%o, uch11_myaddr=%o, size %d, wcount %d)\n", dest_addr, uch11_myaddr, size, wcount);
	/*
	 * Recieve packets addressed to us, but don't receive broadcasts we send
	 */
	if (dest_addr == uch11_myaddr) {
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
	}
	if (chaosd_fd == -1)
		return 0;
	{
		struct iovec iov[2];
		unsigned char lenbytes[4];
		int ret;

		lenbytes[0] = size >> 8;
		lenbytes[1] = size;
		lenbytes[2] = 1;
		lenbytes[3] = 0;
		iov[0].iov_base = lenbytes;
		iov[0].iov_len = 4;
		iov[1].iov_base = buffer;
		iov[1].iov_len = size;
		ret = writev(chaosd_fd, iov, 2);
		if (ret < 0) {
			perror("chaos write");
			return -1;
		}
	}
	return 0;
}

static int
chaos_poll_chaosd(void)
{
	ssize_t ret;
	struct pollfd pfd[1];
	int nfds, timeout;
	unsigned char lenbytes[4];
	ssize_t len;
	int dest_addr;

	if (reconnect_chaos == true) {
		uch11_reconnect();
	}
	if (chaosd_fd == -1) {
		return 0;
	}
	timeout = 0;
	nfds = 1;
	pfd[0].fd = chaosd_fd;
	pfd[0].events = POLLIN;
	pfd[0].revents = 0;
	ret = poll(pfd, nfds, timeout);
	if (ret == -1) {
		ERR(TRACE_CHAOS, "chaos: polling chaosd: nothing there (RDN=%o)\n", uch11_csr & CHAOS_CSR_RECEIVE_DONE);
		reconnect_chaos = true;
		return -1;
	} else if (ret == 0) {
		ERR(TRACE_CHAOS, "chaos: timeout\n");
		return -1;
	}
	/*
	 * Is RX buffer full?
	 */
	if (!uch11_rcv_buffer_empty && (uch11_csr & CHAOS_CSR_RECEIVE_DONE)) {
		/*
		 * Toss packets arriving when buffer is already in
		 * use, they will be resent.
		 */
		ERR(TRACE_CHAOS, "chaos: polling chaosd: unread data, drop (RDN=%o, lost %d)\n", uch11_csr & CHAOS_CSR_RECEIVE_DONE, uch11_lost_count);
		uch11_lost_count++;
		ret = read(chaosd_fd, lenbytes, 4);
		if (ret != 4)
			perror("read");
		len = (lenbytes[0] << 8) | lenbytes[1];
		DEBUG(TRACE_CHAOS, "chaos: tossing packet of %d bytes\n", len);
		if (len > (ssize_t) sizeof(uch11_rcv_buffer_toss)) {
			ERR(TRACE_CHAOS, "chaos: packet won't fit (len=%d)", len);
			uch11_force_reconect();
			return -1;
		}
		/*
		 * Toss it...
		 */
		ret = read(chaosd_fd, (char *) uch11_rcv_buffer_toss, len);
		if (ret != len)
			perror("read");
		return -1;
	}
	/*
	 * Read header from chaosd.
	 */
	ret = read(chaosd_fd, lenbytes, 4);
	if (ret <= 0) {
		perror("chaos: header read error");
		uch11_force_reconect();
		return -1;
	}
	len = (lenbytes[0] << 8) | lenbytes[1];
	if (len > (ssize_t) sizeof(uch11_rcv_buffer)) {
		ERR(TRACE_CHAOS, "chaos: packet too big: pkt size %d, buffer size %lu\n", len, sizeof(uch11_rcv_buffer));
		/*
		 * When we get out of synch break socket conn.
		 */
		uch11_force_reconect();
		return -1;
	}
	ret = read(chaosd_fd, (char *) uch11_rcv_buffer, len);
	if (ret == -1) {
		perror("chaos: read");
		uch11_force_reconect();
		return -1;
	} else if (ret == 0) {
		ERR(TRACE_CHAOS, "chaos: read zero bytes\n");
		return -1;
	}
	DEBUG(TRACE_CHAOS, "chaos: polling; got chaosd packet %d\n", ret);
	uch11_rcv_buffer_size = (ret + 1) / 2;
	uch11_rcv_buffer_empty = false;
	dest_addr = uch11_rcv_buffer[uch11_rcv_buffer_size - 3];
	/*
	 * If not to us, ignore.
	 */
	if (dest_addr != uch11_myaddr) {
		DEBUG(TRACE_CHAOS, "chaos: ignoring packet not to us (%o): %o\n", uch11_myaddr, dest_addr);
		uch11_rcv_buffer_size = 0;
		uch11_rcv_buffer_empty = true;
		/*
		 * Should uch11_rx_pkt be called here?
		 */
		return 0;
	}
	DEBUG(TRACE_CHAOS, "chaos: recieving packet: from %o, my %o\n", dest_addr, uch11_myaddr);
	uch11_rx_pkt();
	return 0;
}

Added uch11-local.c.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/* Local Chaos -- this should go into chlib.c
 */

// #include <sys/poll.h>
// #include <sys/socket.h>
// #include <sys/stat.h>
// #include <sys/time.h>
// #include <sys/types.h>
// #include <sys/uio.h>
// #include <sys/un.h>
// 
// #include <netinet/in.h>
// 
// #include <sys/types.h>
// #include <sys/socket.h>
// #include <netdb.h>
// #include <arpa/inet.h>
// 
// #include <err.h>
// #include <pthread.h>
// #include <stddef.h>
// #include <stdint.h>
// #include <stdio.h>
// #include <stdlib.h>
// #include <string.h>
// #include <time.h>
// #include <unistd.h>
// 
// #include "uch11.h"
// #include "chaosd.h"
// #include "hosttab.h"
// #include "misc.h"
// #include "ucfg.h"
// #include "ucode.h"
// #include "usim.h"
// #include "utrace.h"

static void
chaos_queue(struct packet *packet)
{
	struct packet_queue *node;

	node = malloc(sizeof(struct packet_queue));
	node->packet = packet;
	pthread_mutex_lock(&recvqueue);
	TAILQ_INSERT_TAIL(&queuehead, node, next);
	pthread_mutex_unlock(&recvqueue);
}

int
chaos_connection_queue(struct connection *conn, struct packet *packet)
{
	struct packet_queue *node;
	unsigned short nextpacket;

	INFO(TRACE_CHAOS, "chaos: sending packet (0%o) to 0%o from 0%o (length: %d)\n", packet->pk_op, CH_ADDR_SHORT(packet->pk_daddr), CH_ADDR_SHORT(packet->pk_saddr), PH_LEN(packet->pk_phead));
	if (trace_level == LOG_DEBUG && (trace_facilities & TRACE_CHAOS)) {
		dumpmem(packet->pk_cdata, PH_LEN(packet->pk_phead));
	}
	/*
	 * Any packet for remote gets queued.
	 */
	if (CH_ADDR_SHORT(packet->pk_daddr) == CH_ADDR_SHORT(conn->cn_faddr)) {
		for (;;) {
			if (chtfull(conn) && packet->pk_op != STSOP) {
				struct timespec ts;

				DEBUG(TRACE_CHAOS, "chaos: waiting for remote ack packet=%d (cn_tlast = %d cn_tacked = %d twsize = %d)\n", packet->pk_pkn, conn->cn_tlast, conn->cn_tacked, conn->cn_twsize);
				pthread_mutex_lock(&conn->twsem);
				clock_gettime(CLOCK_REALTIME, &ts);
				ts.tv_sec += 5;
				if (pthread_cond_timedwait(&conn->twcond, &conn->twsem, &ts)) {
					if (conn->lastpacket) {
						struct packet *retransmit;

						DEBUG(TRACE_CHAOS, "chaos: re-transmit last packet\n");
						retransmit = conn->lastpacket;
						conn->lastpacket = 0;
						chaos_queue(retransmit);
					}
				}
				pthread_mutex_unlock(&conn->twsem);
			} else
				break;
		}
		if (packet->pk_op != STSOP && CH_INDEX_SHORT(packet->pk_didx) == CH_INDEX_SHORT(conn->cn_fidx) && cmp_gt(packet->pk_pkn, conn->cn_tlast))
			conn->cn_tlast = packet->pk_pkn;
		conn->lastpacket = packet;
		chaos_queue(packet);
		return 0;
	}
	node = malloc(sizeof(struct packet_queue));
	node->packet = packet;
	nextpacket = conn->cn_rlast + 1;
	if (cmp_gt(packet->pk_pkn, nextpacket)) {
		DEBUG(TRACE_CHAOS, "chaos: queuing out-of-order packet: nextpacket=%d packet=%d\n", nextpacket, packet->pk_pkn);
		pthread_mutex_lock(&conn->queuelock);
		TAILQ_INSERT_TAIL(&conn->orderhead, node, next);
		pthread_mutex_unlock(&conn->queuelock);
		return 0;
	}
	{
		pthread_mutex_lock(&conn->queuelock);
		TAILQ_INSERT_TAIL(&conn->queuehead, node, next);
		pthread_mutex_unlock(&conn->queuelock);
	}
	pthread_mutex_lock(&conn->queuesem);
	pthread_cond_signal(&conn->queuecond);
	pthread_mutex_unlock(&conn->queuesem);
	return 0;
}

struct packet *
chaos_connection_dequeue(struct connection *conn)
{
	struct packet *packet;
	struct packet_queue *node;
#if 0
	unsigned short nextpacket;
#endif

	packet = NOPKT;
	node = 0;
#if 0
	nextpacket = conn->cn_rlast + 1;
#endif
	if (conn->cn_state == CSCLOSED)
		return NOPKT;
	for (;;) {
		pthread_mutex_lock(&conn->queuelock);
		if (TAILQ_EMPTY(&conn->orderhead) == false) {
#if 0
			struct packet_queue *prev;

			for (node = conn->orderhead; node; prev = node, node = node->next)
				if (node->packet->pk_pkn == nextpacket) {
					if (prev == 0)
						conn->orderhead = node->next;
					else
						prev->next = node->next;
					if (conn->ordertail == node)
						conn->ordertail = prev;
					packet = node->packet;
					break;
				}
#endif
#if 0
			TAILQ_FOREACH(node, &conn->orderhead, next) {
				if (node->packet->pk_pkn == nextpacket) {
					DEBUG(TRACE_CHAOS, "chaos: dequeued out-of-order packet %d\n", nextpacket);
					/*
					 * ---!! magic
					 */
					break;
				}
			}
#else
			DEBUG(TRACE_CHAOS, "chaos: ordered queue empty\n");
#endif
		}
		if (node == 0 && TAILQ_EMPTY(&conn->queuehead) == false) {
			node = TAILQ_FIRST(&conn->queuehead);
			packet = node->packet;
			TAILQ_REMOVE(&conn->queuehead, node, next);
		}
		pthread_mutex_unlock(&conn->queuelock);
		if (node) {
			free(node);
			node = 0;
		}
		if (packet) {
			if (cmp_gt(packet->pk_pkn, conn->cn_rlast))
				conn->cn_rlast = packet->pk_pkn;
			conn->cn_tacked = packet->pk_ackn;
			if (3 * (short) (conn->cn_rlast - conn->cn_racked) > conn->cn_rwsize) {
				struct packet *status;

				status = chaos_allocate_packet(conn, STSOP, 2 * sizeof(unsigned short));
				conn->cn_racked = conn->cn_rlast;
				*(unsigned short *) &status->pk_cdata[0] = conn->cn_rlast;
				*(unsigned short *) &status->pk_cdata[2] = conn->cn_rwsize;
				chaos_queue(status);
			}
			return packet;
		}
		pthread_mutex_lock(&conn->queuesem);
		pthread_cond_wait(&conn->queuecond, &conn->queuesem);
		pthread_mutex_unlock(&conn->queuesem);
		if (conn->cn_state == CSCLOSED)
			return NOPKT;
	}
}

static int
chaos_queue_time_pkt(unsigned short saddr, unsigned short sidx)
{
	time_t t;
	struct timeval time;
	struct packet *answer;

	INFO(TRACE_CHAOS, "chaos: RFC (TIME): answering...\n");
	gettimeofday(&time, NULL);
	t = time.tv_sec;
	t += 60UL * 60 * 24 * ((1970 - 1900) * 365L + 1970 / 4 - 1900 / 4);
	answer = pkalloc(sizeof(long), 0);
	answer->pk_op = ANSOP;
	SET_PH_LEN(answer->pk_phead, sizeof(long));
	SET_CH_ADDR(answer->pk_daddr, saddr);
	SET_CH_INDEX(answer->pk_didx, sidx);
	SET_CH_ADDR(answer->pk_saddr, chaos_addr(ucfg.chaos_servername, 0));
	SET_CH_INDEX(answer->pk_sidx, 0);
	answer->pk_pkn = 0;
	answer->pk_ackn = 0;
	*(long *) &answer->pk_cdata[0] = t;
	chaos_queue(answer);
	return 0;
}

static int
chaos_queue_uptime_pkt(unsigned short saddr, unsigned short sidx)
{
	struct packet *answer;

	INFO(TRACE_CHAOS, "chaos: RFC (UPTIME): answering...\n");
	answer = pkalloc(sizeof(long), 0);
	answer->pk_op = ANSOP;
	SET_PH_LEN(answer->pk_phead, sizeof(long));
	SET_CH_ADDR(answer->pk_daddr, saddr);
	SET_CH_INDEX(answer->pk_didx, sidx);
	SET_CH_ADDR(answer->pk_saddr, chaos_addr(ucfg.chaos_servername, 0));
	SET_CH_INDEX(answer->pk_sidx, 0);
	answer->pk_pkn = 0;
	answer->pk_ackn = 0;
	*(long *) &answer->pk_cdata[0] = 0;
	chaos_queue(answer);
	return 0;
}

static int
chaos_queue_status_pkt(unsigned short saddr, unsigned short sidx)
{
	struct packet *answer;
	struct status *status;

	INFO(TRACE_CHAOS, "chaos: RFC (STATUS): answering...\n");
	answer = pkalloc(CHSTATNAME + 2 * 2, 0);	/* Only room for name and subnet+nwords */
	answer->pk_op = ANSOP;
	SET_PH_LEN(answer->pk_phead, CHSTATNAME + 2 * 2);
	SET_CH_ADDR(answer->pk_daddr, saddr);
	SET_CH_INDEX(answer->pk_didx, sidx);
	SET_CH_ADDR(answer->pk_saddr, chaos_addr(ucfg.chaos_servername, 0));
	SET_CH_INDEX(answer->pk_sidx, 0);
	answer->pk_pkn = 0;
	answer->pk_ackn = 0;
	status = (struct status *) &answer->pk_cdata[0];
	memset(status, 0, sizeof(struct status));
	strncpy(status->sb_name, ucfg.chaos_servername, CHSTATNAME);
	status->sb_name[CHSTATNAME - 1] = '\0';
	/* Only put in the subnet (with the 400 marker) */
	status->sb_data->sb_ident = (chaos_addr(ucfg.chaos_servername, 0) >> 8) | 0400;
	/* and say no data is following */
	status->sb_data->sb_nshorts = 0 * sizeof(int) / sizeof(short);
	chaos_queue(answer);
	return 0;
}

static int
chaos_queue_file_pkt(struct packet *packet)
{
	void processdata(struct connection *conn);
	struct packet *answer;
	struct connection *conn;

	packet->pk_cdata[PH_LEN(packet->pk_phead)] = '\0';
	INFO(TRACE_CHAOS, "chaos: RFC (%s): answering...\n", &packet->pk_cdata);
	conn = allconn();
	conn->cn_faddr = packet->pk_saddr;
	conn->cn_fidx = packet->pk_sidx;
	answer = chaos_allocate_packet(conn, OPNOP, 2 * sizeof(unsigned short));
	answer->pk_ackn = packet->pk_pkn;
	conn->cn_racked = packet->pk_pkn;
	*(unsigned short *) &answer->pk_cdata[0] = packet->pk_pkn;	/* Last packed received. */
	*(unsigned short *) &answer->pk_cdata[2] = conn->cn_rwsize;
	chaos_connection_queue(conn, answer);
	conn->cn_state = CSLISTEN;
	processdata(conn);
	return 0;
}

static int
chaos_queue_mini_pkt(struct packet *packet)
{
	void processmini(struct connection *conn);
	struct packet *answer;
	struct connection *conn;

	packet->pk_cdata[PH_LEN(packet->pk_phead)] = '\0';
	INFO(TRACE_CHAOS, "chaos: RFC (%s): answering...\n", &packet->pk_cdata);
	conn = allconn();
	conn->cn_faddr = packet->pk_saddr;
	conn->cn_fidx = packet->pk_sidx;
	answer = chaos_allocate_packet(conn, OPNOP, 2 * sizeof(unsigned short));
	answer->pk_ackn = packet->pk_pkn;
	conn->cn_racked = packet->pk_pkn;
	*(unsigned short *) &answer->pk_cdata[0] = packet->pk_pkn;	/* Last packed received. */
	*(unsigned short *) &answer->pk_cdata[2] = conn->cn_rwsize;
	chaos_connection_queue(conn, answer);
	conn->cn_state = CSLISTEN;
	conn->cn_rlast = 1;
	processmini(conn);
	return 0;
}

static int
chaos_send_to_local(char *buffer, int size)
{				/* ---!!! rcvpkt ? */
	struct packet *packet;
	struct connection *conn;

	packet = (struct packet *) buffer;
	/*
	 * Local loopback.
	 */
	if (uch11_csr & CHAOS_CSR_LOOP_BACK) {
		DEBUG(TRACE_CHAOS, "chaos: loopback %d bytes\n", size);
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
		return 0;
	}
	DEBUG(TRACE_CHAOS, "chaos: transmitting packet (dest_addr = %o, uch11_myaddr=%o, size %d, wcount %d, op: %o)\n", CH_ADDR_SHORT(packet->pk_daddr), uch11_myaddr, size, (size + 1) / 2, packet->pk_op);
	/*
	 * Receive packets addressed to ourselves.
	 */
	if (CH_ADDR_SHORT(packet->pk_daddr) == uch11_myaddr) {
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
	}
	/*
	 * Ignore packets anything that isn't addressed to us.
	 */
	if (CH_ADDR_SHORT(packet->pk_daddr) != chaos_addr(ucfg.chaos_servername, 0)) {
		DEBUG(TRACE_CHAOS, "chaos: ignoring packet not to us (%o): %o\n", chaos_addr(ucfg.chaos_servername, 0), CH_ADDR_SHORT(packet->pk_daddr));
		return 0;
	}
	conn = chaos_find_connection(CH_INDEX_SHORT(packet->pk_didx));
	/*
	 * ---!!! Large parts of this is in rcvrfc.
	 */
	if (packet->pk_op == RFCOP) {
		DEBUG(TRACE_CHAOS, "chaos: got RFC packet\n");
		if (conn && conn->cn_state == CSLISTEN) {
			DEBUG(TRACE_CHAOS, "chaos: duplicate RFC\n");
			return 0;
		}
		if (conn) {
			struct packet *pkt;

			pkt = pkalloc((size_t) size, 0);
			memcpy(pkt, packet, size);
			chaos_connection_queue(conn, pkt);
			return 0;
		}
		if (memcmp(&packet->pk_cdata, "STATUS", 6) == 0)
			return chaos_queue_status_pkt(CH_ADDR_SHORT(packet->pk_saddr), CH_INDEX_SHORT(packet->pk_sidx));
		else if (memcmp(&packet->pk_cdata, "TIME", 4) == 0)
			return chaos_queue_time_pkt(CH_ADDR_SHORT(packet->pk_saddr), CH_INDEX_SHORT(packet->pk_sidx));
		else if (memcmp(&packet->pk_cdata, "UPTIME", 6) == 0)
			return chaos_queue_uptime_pkt(CH_ADDR_SHORT(packet->pk_saddr), CH_INDEX_SHORT(packet->pk_sidx));
		else if (memcmp(&packet->pk_cdata, "FILE", 4) == 0)
			return chaos_queue_file_pkt(packet);
		else if (memcmp(&packet->pk_cdata, "MINI", 4) == 0)
			return chaos_queue_mini_pkt(packet);
		else {
			char buffer[512];

			strncpy(buffer, (char *) packet->pk_cdata, PH_LEN(packet->pk_phead));
			buffer[PH_LEN(packet->pk_phead)] = '\0';
			WARNING(TRACE_CHAOS, "chaos: RFC (%s): protocol not implemented\n", buffer);
			return 0;
		}
	}
	if (packet->pk_op == SNSOP && conn) {
		struct packet *sts;

		sts = pkalloc(2 * sizeof(unsigned short) + 3 * sizeof(unsigned short), 1);
		sts->pk_op = STSOP;
		SET_PH_LEN(sts->pk_phead, 2 * sizeof(unsigned short));
		sts->pk_daddr = packet->pk_saddr;
		sts->pk_didx = packet->pk_sidx;
		conn->cn_faddr = packet->pk_saddr;
		conn->cn_fidx = packet->pk_sidx;
		sts->pk_saddr = conn->cn_laddr;
		sts->pk_sidx = conn->cn_lidx;
		sts->pk_pkn = packet->pk_pkn;
		if (cmp_gt(packet->pk_ackn, conn->cn_tacked))
			conn->cn_tacked = packet->pk_ackn;
		sts->pk_ackn = conn->cn_racked;
		*(unsigned short *) &sts->pk_cdata[0] = conn->cn_racked;
		*(unsigned short *) &sts->pk_cdata[2] = conn->cn_rwsize;
		chaos_connection_queue(conn, sts);
		return 0;
	}
	if (packet->pk_op == STSOP) {
		if (conn) {
			if (cmp_gt(packet->pk_ackn, conn->cn_tacked))
				conn->cn_tacked = packet->pk_ackn;
			if (conn->lastpacket && conn->cn_tacked == conn->lastpacket->pk_pkn) {
				free(conn->lastpacket);
				conn->lastpacket = 0;
			}
			conn->cn_state = CSOPEN;
			conn->cn_twsize = *(unsigned short *) &packet->pk_cdata[2];
			DEBUG(TRACE_CHAOS, "chaos: STSOP: twsize = %d\n", conn->cn_twsize);
			pthread_mutex_lock(&conn->twsem);
			pthread_cond_signal(&conn->twcond);
			pthread_mutex_unlock(&conn->twsem);
		}
		return 0;
	}
	if (conn && packet->pk_op == CLSOP) {	/* clsconn ? */
		DEBUG(TRACE_CHAOS, "chaos: CLSOP: got close \n");
		conn->cn_state = CSCLOSED;
		pthread_mutex_lock(&conn->queuesem);
		pthread_cond_signal(&conn->queuecond);
		pthread_mutex_unlock(&conn->queuesem);
		usleep(100000);	/* wait for queue to wake up */
		rlsconn(conn);
		return 0;
	}
	if (conn && (cmp_gt(conn->cn_rlast, packet->pk_pkn) || (conn->cn_rlast == packet->pk_pkn))) {
		struct packet *status;

		DEBUG(TRACE_CHAOS, "chaos: duplicate data packet\n");
		status = chaos_allocate_packet(conn, STSOP, 2 * sizeof(unsigned short));
		status->pk_pkn = packet->pk_pkn;
		conn->cn_racked = conn->cn_rlast;
		*(unsigned short *) &status->pk_cdata[0] = conn->cn_rlast;
		*(unsigned short *) &status->pk_cdata[2] = conn->cn_rwsize;
		chaos_connection_queue(conn, status);
		return 0;
	}
	if (conn) {
		struct packet *pkt;

		pkt = pkalloc((size_t) size, 0);
		memcpy(pkt, packet, size);
		chaos_connection_queue(conn, pkt);
	}
	return 0;
}

static int
chaos_poll_local(void)
{
	struct packet *packet;
	struct packet_queue *node;
	int size;

	/*
	 * Is RX buffer full?
	 */
	if (!uch11_rcv_buffer_empty && (uch11_csr & CHAOS_CSR_RECEIVE_DONE)) {
		DEBUG(TRACE_CHAOS, "chaos: polling, but unread data exists\n");
		return 0;
	}
	if (!uch11_rcv_buffer_empty) {
		DEBUG(TRACE_CHAOS, "chaos: polling, but buffer not empty\n");
		return 0;
	}
	if (TAILQ_EMPTY(&queuehead) == true) {
		return 0;
	}
	if (!(uch11_csr & CHAOS_CSR_RECEIVE_ENABLE)) {
		DEBUG(TRACE_CHAOS, "chaos: polling but rx not enabled\n");
		return 0;
	}
	pthread_mutex_lock(&recvqueue);
	node = TAILQ_FIRST(&queuehead);
	packet = node->packet;
	TAILQ_REMOVE(&queuehead, node, next);
	free(node);
	pthread_mutex_unlock(&recvqueue);
	size = ((PH_LEN(packet->pk_phead) & 0x0fff) + CHHEADSIZE + 1) / 2;
	/*
	 * Ignore any packets not to us.
	 */
	if (CH_ADDR_SHORT(packet->pk_daddr) != uch11_myaddr)
		return 0;
	memcpy(uch11_rcv_buffer, packet, (size_t) size * sizeof(unsigned short));
	/*
	 * Hardware header.
	 */
	uch11_rcv_buffer[size] = CH_ADDR_SHORT(packet->pk_daddr);
	uch11_rcv_buffer[size + 1] = CH_ADDR_SHORT(packet->pk_saddr);
	uch11_rcv_buffer[size + 2] = 0;
	size += 3;
	uch11_rcv_buffer_size = size;
	uch11_rcv_buffer_empty = false;
	DEBUG(TRACE_CHAOS, "chaos: polling: got chaos packet of %d bytes\n", uch11_rcv_buffer_size * 2);
#if 0
	dumpbuffer(uch11_rcv_buffer, size * 2);
#endif
	uch11_rx_pkt();
	return 0;
}

Added uch11-udp.c.



















































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/* Chaos over UDP */

// #include <sys/poll.h>
// #include <sys/socket.h>
// #include <sys/stat.h>
// #include <sys/time.h>
// #include <sys/types.h>
// #include <sys/uio.h>
// #include <sys/un.h>
// 
// #include <netinet/in.h>
// 
// #include <sys/types.h>
// #include <sys/socket.h>
// #include <netdb.h>
// #include <arpa/inet.h>
// 
// #include <err.h>
// #include <pthread.h>
// #include <stddef.h>
// #include <stdint.h>
// #include <stdio.h>
// #include <stdlib.h>
// #include <string.h>
// #include <time.h>
// #include <unistd.h>
// 
// #include "uch11.h"
// #include "chaosd.h"
// #include "hosttab.h"
// #include "misc.h"
// #include "ucfg.h"
// #include "ucode.h"
// #include "usim.h"
// #include "utrace.h"

int hybrid_udp_and_local = 0;

static int
chudpopen(void)
{
	int sock, lport, res, udp_dport, braddr;
	struct sockaddr_in sin;
	struct addrinfo *he, hi;
	struct in_addr udp_dest;

	if (hybrid_udp_and_local) {
		if (uch11_serveraddr == 0) {
			ERR(TRACE_CHAOS, "You configured udp_local_hybrid but there is no server address! Disabling hybrid.\n");
			hybrid_udp_and_local = 0;
		} else {
			/* Do the local init too */
			TAILQ_INIT(&queuehead);
			pthread_mutex_init(&recvqueue, NULL);
		}
	}

	/* Parse the local port given */
	if ((ucfg.chaos_bridgeport_local == NULL) || (ucfg.chaos_bridgeport_local[0] == '\0') || ((lport = atoi(ucfg.chaos_bridgeport_local)) <= 0) || (lport >= (1 << 16))) {
		/* Or default to 42042? */
		err(1, "bad bridgeport_local");
	}
	/* Parse the bridge port given */
	if ((ucfg.chaos_bridgeport == NULL) || (ucfg.chaos_bridgeport[0] == '\0') || ((udp_dport = atoi(ucfg.chaos_bridgeport)) <= 0) || (udp_dport >= (1 << 16))) {
		/* Or default to 42042? */
		err(1, "bad bridgeport");
	}
	/* Parse the bridge address given */
	if ((ucfg.chaos_bridgeip != NULL) && (ucfg.chaos_bridgeip[0] != '\0')) {
		/* @@@@ allow IPv6 */
		/* Check if it is an explicit IPv4 address */
		if (inet_aton(ucfg.chaos_bridgeip, &udp_dest) == 0) {
			/* Else try to parse a host name */
			memset(&hi, 0, sizeof(hi));
			hi.ai_family = AF_INET;
			hi.ai_flags = AI_ADDRCONFIG;
			if ((res = getaddrinfo(ucfg.chaos_bridgeip, NULL, &hi, &he)) == 0) {
				struct sockaddr_in *s = (struct sockaddr_in *) he->ai_addr;
				memcpy(&udp_dest.s_addr, (u_char *) & s->sin_addr, 4);
			} else {
				err(1, "bad bridgeip");
			}
		}
	} else {
		err(1, "no bridge?");
	}
	/* Parse bridge Chaos address */
	if ((ucfg.chaos_bridgechaos == NULL) || (ucfg.chaos_bridgechaos[0] == '\0') | (sscanf(ucfg.chaos_bridgechaos, "%o", &braddr) != 1) ||
	    /* Check it's a valid address */
	    (braddr == 0) || (braddr >= (1 << 16)) || ((braddr & 0xff) == 0) || (((braddr >> 8) & 0xff) == 0)) {
		err(1, "bad bridgechaos");
	} else {
		udp_bridge_chaddr = (braddr & 0xffff);
	}

	NOTICE(TRACE_USIM, "chaos: chudp init, bridge is %#o at %s:%d, local port %d, hybrid %s\n", udp_bridge_chaddr, inet_ntoa(udp_dest), udp_dport, lport, hybrid_udp_and_local ? "true" : "false");

	/* Now create a socket, and bind it to our local port */
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("socket failed");
		exit(1);
	}
	sin.sin_family = AF_INET;
	sin.sin_port = htons(lport);
	sin.sin_addr.s_addr = INADDR_ANY;
	if (bind(sock, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
		perror("udp bind failed");
		exit(1);
	}
	/* and then connect it to the remote address - since we're only using one and the same */
	sin.sin_port = htons(udp_dport);
	memcpy(&sin.sin_addr.s_addr, &udp_dest.s_addr, 4);
	if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
		perror("udp connect failed");
		exit(1);
	}
	return sock;
}

/* from chudp.h and cbridge-chaos.h */

// Max pkt size (12 bits) plus header
// The limit of 488 bytes is from MIT AIM 628, although more would fit any modern pkt (and 12 bits would give 4096 as max).
// This is due to original Chaos hardware pkts limited to 4032 bits, of which 16 bytes are header.
#define CH_PK_MAX_DATALEN 488

/* Protocol version */
#define CHUDP_VERSION 1
/* Protocol function codes */
#define CHUDP_PKT 1		/* Chaosnet packet */

struct chudp_header
{
	char chudp_version;
	char chudp_function;
	char chudp_arg1;
	char chudp_arg2;
};

struct chaos_hw_trailer
{
	unsigned short ch_hw_destaddr:16;
	unsigned short ch_hw_srcaddr:16;
	unsigned short ch_hw_checksum:16;
};

/* Max: CHUDP header, Chaos header, Chaos data, trailer */
#define CHUDP_MAXLEN (sizeof(struct chudp_header)+sizeof(struct pkt_header)+CH_PK_MAX_DATALEN+sizeof(struct chaos_hw_trailer))

static u_char trans_chudpbuf[CHUDP_MAXLEN];

/* So sorry about this. */
void
ntohs_buf(u_short *ibuf, u_short *obuf, int len)
{
	int i;
	for (i = 0; i < len; i += 2)
		*obuf++ = ntohs(*ibuf++);
}

static int
chaos_send_to_udp(char *buffer, int size)
{
	int wcount, dest_addr;

	/*
	 * Local loopback.
	 */
	if (uch11_csr & CHAOS_CSR_LOOP_BACK) {
		DEBUG(TRACE_CHAOS, "chaos: loopback %d bytes\n", size);
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
		return 0;
	}
	if (hybrid_udp_and_local) {
		/* Check if it is for our "local server" */
		struct packet *packet;
		packet = (struct packet *) buffer;
		if (CH_ADDR_SHORT(packet->pk_daddr) == chaos_addr(ucfg.chaos_servername, 0)) {
			return chaos_send_to_local(buffer, size);
		}
	}
	wcount = (size + 1) / 2;
	dest_addr = ((unsigned short *) buffer)[wcount - 3];
	DEBUG(TRACE_CHAOS, "chaos: sending packet to udp (dest_addr=%o, uch11_myaddr=%o, size %d, wcount %d)\n", dest_addr, uch11_myaddr, size, wcount);
	if (size > (int) CHUDP_MAXLEN) {
		ERR(TRACE_CHAOS, "chaos: packet too long: %d", size);
		return -1;
	}
	/*
	 * Receive packets addressed to us, or broadcasts.
	 */
	if ((dest_addr == uch11_myaddr) || (dest_addr == 0)) {
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
		if (dest_addr != 0)	/* Broadcasts should be sent also to other */
			return 0;
	}
	if (chaosd_fd == -1) {
		ERR(TRACE_CHAOS, "chaos: transmit but chaosd_fd not open!\n");
		return 0;
	}
	{
		struct chudp_header *hp = (struct chudp_header *) &trans_chudpbuf;
		u_char *op = trans_chudpbuf + sizeof(struct chudp_header);
		int nb;

		memset(trans_chudpbuf, 0, sizeof(trans_chudpbuf));
		/* Set up CHUDP header */
		hp->chudp_version = CHUDP_VERSION;
		hp->chudp_function = CHUDP_PKT;

		memcpy(op, buffer, size);

		/* Update the hw trailer dest (and checksum) since what is there is probably the ultimate dest,
		 * but it should be just the next hop */
		struct pkt_header *ph = (struct pkt_header *) ((char *) op);
		u_short pklen = LENFC_LEN(ph->ph_lenfc);
		u_short offs = sizeof(struct pkt_header) + pklen;
		if (offs % 2)
			offs++;
		struct chaos_hw_trailer *tp = (struct chaos_hw_trailer *) (op + offs);
		u_short hwdest = tp->ch_hw_destaddr;
		u_short cksum = tp->ch_hw_checksum;
		if (hwdest != udp_bridge_chaddr) {
			INFO(TRACE_CHAOS, "chaos: hw trailer dest is %#o should be %#o\n", hwdest, udp_bridge_chaddr);
			tp->ch_hw_destaddr = udp_bridge_chaddr;
		}
		tp->ch_hw_checksum = htons(uch11_checksum(op, size - 2));

		/* Now swap it */
		ntohs_buf((u_short *) op, (u_short *) op, size);

		INFO(TRACE_CHAOS, "chaos: sending %d bytes (pkt size %d)\n", size + sizeof(struct chudp_header), size);
		if ((nb = send(chaosd_fd, (char *) hp, size + sizeof(struct chudp_header), 0)) < 0) {
			perror("chaos: send to udp");
			ERR(TRACE_CHAOS, "chaos: send to udp failed");
			return -1;
		} else if (nb != size + sizeof(struct chudp_header)) {
			ERR(TRACE_CHAOS, "chaos: could not send the full pkt: %d sent, expected %d", nb, size + sizeof(struct chudp_header));
			return -1;
		}
	}
	return 0;
}

static int
chaos_poll_udp(void)
{
	/* basically copy chaos_poll_chaosd but skip CHUDP header and swap */
	ssize_t ret;
	struct pollfd pfd[1];
	int nfds, timeout;
	unsigned char lenbytes[4];
	ssize_t len;
	int dest_addr;

	if (hybrid_udp_and_local) {
		/* Prioritize local traffic */
		chaos_poll_local();
	}

	if (chaosd_fd == -1) {
		return 0;
	}
	timeout = 0;
	nfds = 1;
	pfd[0].fd = chaosd_fd;
	pfd[0].events = POLLIN;
	pfd[0].revents = 0;
	ret = poll(pfd, nfds, timeout);
	if (ret == -1) {
		ERR(TRACE_CHAOS, "chaos: polling udp: nothing there (RDN=%o)\n", uch11_csr & CHAOS_CSR_RECEIVE_DONE);
		return -1;
	} else if (ret == 0) {
		// this happens all the time so don't
		// ERR(TRACE_CHAOS, "chaos: udp poll timeout\n");
		return -1;
	}
	/*
	 * Is RX buffer full?
	 */
	if (!uch11_rcv_buffer_empty && (uch11_csr & CHAOS_CSR_RECEIVE_DONE)) {
		/*
		 * Toss packets arriving when buffer is already in
		 * use, they will be resent.
		 */
		ERR(TRACE_CHAOS, "chaos: polling udp: unread data, drop (RDN=%o, lost %d)\n", uch11_csr & CHAOS_CSR_RECEIVE_DONE, uch11_lost_count);
		uch11_lost_count++;
		/* Toss it by reading it */
		ret = recv(chaosd_fd, (char *) uch11_rcv_buffer_toss, sizeof(uch11_rcv_buffer_toss), 0);
		DEBUG(TRACE_CHAOS, "chaos: tossing udp packet of %d bytes\n", ret);
		return -1;
	}
	ret = recv(chaosd_fd, (char *) uch11_rcv_buffer, sizeof(uch11_rcv_buffer), 0);
	if (ret == -1) {
		perror("chaos: udp read");
		return -1;
	} else if (ret == 0) {
		ERR(TRACE_CHAOS, "chaos: udp read zero bytes\n");
		return -1;
	} else if (ret > (int) CHUDP_MAXLEN) {
		ERR(TRACE_CHAOS, "chaos: udp read too many bytes: %d\n", ret);
		return -1;
	}
	INFO(TRACE_CHAOS, "chaos: polling; got udp packet len %d\n", ret);
	struct chudp_header *hp = (struct chudp_header *) uch11_rcv_buffer;
	if (hp->chudp_version != CHUDP_VERSION) {
		ERR(TRACE_CHAOS, "chaos: chudp version is wrong: %d\n", hp->chudp_version);
		return -1;
	}
	if (hp->chudp_function != CHUDP_PKT) {
		ERR(TRACE_CHAOS, "chaos: chudp function is wrong: %d\n", hp->chudp_function);
		return -1;
	}
	/* zap chudp header */
	memmove((char *) uch11_rcv_buffer, ((char *) uch11_rcv_buffer) + sizeof(struct chudp_header), ret - sizeof(struct chudp_header));
	ret -= sizeof(struct chudp_header);

	/* and swap it */
	ntohs_buf(uch11_rcv_buffer, uch11_rcv_buffer, ret);

	uch11_rcv_buffer_size = (ret + 1) / 2;
	uch11_rcv_buffer_empty = false;
	dest_addr = uch11_rcv_buffer[uch11_rcv_buffer_size - 3];
	/*
	 * If not to us (or broadcast), ignore.
	 */
	if ((dest_addr != uch11_myaddr) && (dest_addr != 0)) {
		INFO(TRACE_CHAOS, "chaos: ignoring packet not to us (%o): %o\n", uch11_myaddr, dest_addr);
		uch11_rcv_buffer_size = 0;
		uch11_rcv_buffer_empty = true;
		/*
		 * Should uch11_rx_pkt be called here?
		 */
		return 0;
	}
	INFO(TRACE_CHAOS, "chaos: udp receiving packet: from %o, my %o\n", dest_addr, uch11_myaddr);
	uch11_rx_pkt();
	return 0;
}

Changes to uch11.c.

73
74
75
76
77
78
79

80



81
82
83
84
85


86



87







88
89
90
91
92
93
94

static int reconnect_delay;
static bool reconnect_chaos;

static int (*uch11_send)(char *, int);

static void uch11_force_reconect(void);





static u_short udp_bridge_chaddr;
static int chudpopen(void);
static int chaos_send_to_udp(char *buffer, int size);
static int chaos_poll_udp(void);
extern void uch11_reconnect(void);






extern void settreeroot(const char *, const char *prefix);








/*
 * RFC1071: Compute Internet Checksum for COUNT bytes beginning at
 * location ADDR.
 */
static unsigned short
uch11_checksum(const unsigned char *addr, int count)







>

>
>
>




|
>
>

>
>
>
|
>
>
>
>
>
>
>







73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

static int reconnect_delay;
static bool reconnect_chaos;

static int (*uch11_send)(char *, int);

static void uch11_force_reconect(void);
extern void uch11_reconnect(void);

extern void settreeroot(const char *, const char *prefix);

// udp
static u_short udp_bridge_chaddr;
static int chudpopen(void);
static int chaos_send_to_udp(char *buffer, int size);
static int chaos_poll_udp(void);

// deamon
static int chaosd_fd;

static pthread_mutex_t recvqueue;
static pthread_mutex_t recvqueue;
struct queue_head queuehead = TAILQ_HEAD_INITIALIZER(queuehead);

static int chaos_send_to_chaosd(char *buffer, int size);
static int chaos_poll_chaosd(void);

// local

static int chaos_send_to_local(char *buffer, int size);
static int chaos_poll_local(void);

/*
 * RFC1071: Compute Internet Checksum for COUNT bytes beginning at
 * location ADDR.
 */
static unsigned short
uch11_checksum(const unsigned char *addr, int count)
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
		if ((old_csr & CHAOS_CSR_TRANSMIT_ENABLE) == 0)
			DEBUG(TRACE_CHAOS, "chaos: CSR transmit enable\n");
		uch11_csr |= CHAOS_CSR_TRANSMIT_DONE;
	} else if (old_csr & CHAOS_CSR_TRANSMIT_ENABLE)
		DEBUG(TRACE_CHAOS, "chaos: CSR transmit DISable\n");
	DEBUG(TRACE_CHAOS, "chaos: set csr bits 0%o, old 0%o, new 0%o\n", v, old_csr, uch11_csr);
}

/* Connect to a chaos daemon via a Unix socket.
 */

#define UNIX_SOCKET_PATH	"/var/tmp/"
#define UNIX_SOCKET_CLIENT_NAME	"chaosd_"
#define UNIX_SOCKET_SERVER_NAME	"chaosd_server"
#define UNIX_SOCKET_PERM	S_IRWXU

static int chaosd_fd;

static int
chaos_send_to_chaosd(char *buffer, int size)
{
	int wcount, dest_addr;

	/*
	 * Local loopback.
	 */
	if (uch11_csr & CHAOS_CSR_LOOP_BACK) {
		DEBUG(TRACE_CHAOS, "chaos: loopback %d bytes\n", size);
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
		return 0;
	}
	wcount = (size + 1) / 2;
	dest_addr = ((unsigned short *) buffer)[wcount - 3];
	DEBUG(TRACE_CHAOS, "chaos: sending packet to chaosd (dest_addr=%o, uch11_myaddr=%o, size %d, wcount %d)\n", dest_addr, uch11_myaddr, size, wcount);
	/*
	 * Recieve packets addressed to us, but don't receive broadcasts we send
	 */
	if (dest_addr == uch11_myaddr) {
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
	}
	if (chaosd_fd == -1)
		return 0;
	{
		struct iovec iov[2];
		unsigned char lenbytes[4];
		int ret;

		lenbytes[0] = size >> 8;
		lenbytes[1] = size;
		lenbytes[2] = 1;
		lenbytes[3] = 0;
		iov[0].iov_base = lenbytes;
		iov[0].iov_len = 4;
		iov[1].iov_base = buffer;
		iov[1].iov_len = size;
		ret = writev(chaosd_fd, iov, 2);
		if (ret < 0) {
			perror("chaos write");
			return -1;
		}
	}
	return 0;
}

static int
chaos_poll_chaosd(void)
{
	ssize_t ret;
	struct pollfd pfd[1];
	int nfds, timeout;
	unsigned char lenbytes[4];
	ssize_t len;
	int dest_addr;

	if (reconnect_chaos == true) {
		uch11_reconnect();
	}
	if (chaosd_fd == -1) {
		return 0;
	}
	timeout = 0;
	nfds = 1;
	pfd[0].fd = chaosd_fd;
	pfd[0].events = POLLIN;
	pfd[0].revents = 0;
	ret = poll(pfd, nfds, timeout);
	if (ret == -1) {
		ERR(TRACE_CHAOS, "chaos: polling chaosd: nothing there (RDN=%o)\n", uch11_csr & CHAOS_CSR_RECEIVE_DONE);
		reconnect_chaos = true;
		return -1;
	} else if (ret == 0) {
		ERR(TRACE_CHAOS, "chaos: timeout\n");
		return -1;
	}
	/*
	 * Is RX buffer full?
	 */
	if (!uch11_rcv_buffer_empty && (uch11_csr & CHAOS_CSR_RECEIVE_DONE)) {
		/*
		 * Toss packets arriving when buffer is already in
		 * use, they will be resent.
		 */
		ERR(TRACE_CHAOS, "chaos: polling chaosd: unread data, drop (RDN=%o, lost %d)\n", uch11_csr & CHAOS_CSR_RECEIVE_DONE, uch11_lost_count);
		uch11_lost_count++;
		ret = read(chaosd_fd, lenbytes, 4);
		if (ret != 4)
			perror("read");
		len = (lenbytes[0] << 8) | lenbytes[1];
		DEBUG(TRACE_CHAOS, "chaos: tossing packet of %d bytes\n", len);
		if (len > (ssize_t) sizeof(uch11_rcv_buffer_toss)) {
			ERR(TRACE_CHAOS, "chaos: packet won't fit (len=%d)", len);
			uch11_force_reconect();
			return -1;
		}
		/*
		 * Toss it...
		 */
		ret = read(chaosd_fd, (char *) uch11_rcv_buffer_toss, len);
		if (ret != len)
			perror("read");
		return -1;
	}
	/*
	 * Read header from chaosd.
	 */
	ret = read(chaosd_fd, lenbytes, 4);
	if (ret <= 0) {
		perror("chaos: header read error");
		uch11_force_reconect();
		return -1;
	}
	len = (lenbytes[0] << 8) | lenbytes[1];
	if (len > (ssize_t) sizeof(uch11_rcv_buffer)) {
		ERR(TRACE_CHAOS, "chaos: packet too big: pkt size %d, buffer size %lu\n", len, sizeof(uch11_rcv_buffer));
		/*
		 * When we get out of synch break socket conn.
		 */
		uch11_force_reconect();
		return -1;
	}
	ret = read(chaosd_fd, (char *) uch11_rcv_buffer, len);
	if (ret == -1) {
		perror("chaos: read");
		uch11_force_reconect();
		return -1;
	} else if (ret == 0) {
		ERR(TRACE_CHAOS, "chaos: read zero bytes\n");
		return -1;
	}
	DEBUG(TRACE_CHAOS, "chaos: polling; got chaosd packet %d\n", ret);
	uch11_rcv_buffer_size = (ret + 1) / 2;
	uch11_rcv_buffer_empty = false;
	dest_addr = uch11_rcv_buffer[uch11_rcv_buffer_size - 3];
	/*
	 * If not to us, ignore.
	 */
	if (dest_addr != uch11_myaddr) {
		DEBUG(TRACE_CHAOS, "chaos: ignoring packet not to us (%o): %o\n", uch11_myaddr, dest_addr);
		uch11_rcv_buffer_size = 0;
		uch11_rcv_buffer_empty = true;
		/*
		 * Should uch11_rx_pkt be called here?
		 */
		return 0;
	}
	DEBUG(TRACE_CHAOS, "chaos: recieving packet: from %o, my %o\n", dest_addr, uch11_myaddr);
	uch11_rx_pkt();
	return 0;
}

/* Local Chaos -- this should go into chlib.c
 */

static pthread_mutex_t recvqueue;
static pthread_mutex_t recvqueue;
struct queue_head queuehead = TAILQ_HEAD_INITIALIZER(queuehead);

static void
chaos_queue(struct packet *packet)
{
	struct packet_queue *node;

	node = malloc(sizeof(struct packet_queue));
	node->packet = packet;
	pthread_mutex_lock(&recvqueue);
	TAILQ_INSERT_TAIL(&queuehead, node, next);
	pthread_mutex_unlock(&recvqueue);
}

int
chaos_connection_queue(struct connection *conn, struct packet *packet)
{
	struct packet_queue *node;
	unsigned short nextpacket;

	INFO(TRACE_CHAOS, "chaos: sending packet (0%o) to 0%o from 0%o (length: %d)\n", packet->pk_op, CH_ADDR_SHORT(packet->pk_daddr), CH_ADDR_SHORT(packet->pk_saddr), PH_LEN(packet->pk_phead));
	if (trace_level == LOG_DEBUG && (trace_facilities & TRACE_CHAOS)) {
		dumpmem(packet->pk_cdata, PH_LEN(packet->pk_phead));
	}
	/*
	 * Any packet for remote gets queued.
	 */
	if (CH_ADDR_SHORT(packet->pk_daddr) == CH_ADDR_SHORT(conn->cn_faddr)) {
		for (;;) {
			if (chtfull(conn) && packet->pk_op != STSOP) {
				struct timespec ts;

				DEBUG(TRACE_CHAOS, "chaos: waiting for remote ack packet=%d (cn_tlast = %d cn_tacked = %d twsize = %d)\n", packet->pk_pkn, conn->cn_tlast, conn->cn_tacked, conn->cn_twsize);
				pthread_mutex_lock(&conn->twsem);
				clock_gettime(CLOCK_REALTIME, &ts);
				ts.tv_sec += 5;
				if (pthread_cond_timedwait(&conn->twcond, &conn->twsem, &ts)) {
					if (conn->lastpacket) {
						struct packet *retransmit;

						DEBUG(TRACE_CHAOS, "chaos: re-transmit last packet\n");
						retransmit = conn->lastpacket;
						conn->lastpacket = 0;
						chaos_queue(retransmit);
					}
				}
				pthread_mutex_unlock(&conn->twsem);
			} else
				break;
		}
		if (packet->pk_op != STSOP && CH_INDEX_SHORT(packet->pk_didx) == CH_INDEX_SHORT(conn->cn_fidx) && cmp_gt(packet->pk_pkn, conn->cn_tlast))
			conn->cn_tlast = packet->pk_pkn;
		conn->lastpacket = packet;
		chaos_queue(packet);
		return 0;
	}
	node = malloc(sizeof(struct packet_queue));
	node->packet = packet;
	nextpacket = conn->cn_rlast + 1;
	if (cmp_gt(packet->pk_pkn, nextpacket)) {
		DEBUG(TRACE_CHAOS, "chaos: queuing out-of-order packet: nextpacket=%d packet=%d\n", nextpacket, packet->pk_pkn);
		pthread_mutex_lock(&conn->queuelock);
		TAILQ_INSERT_TAIL(&conn->orderhead, node, next);
		pthread_mutex_unlock(&conn->queuelock);
		return 0;
	}
	{
		pthread_mutex_lock(&conn->queuelock);
		TAILQ_INSERT_TAIL(&conn->queuehead, node, next);
		pthread_mutex_unlock(&conn->queuelock);
	}
	pthread_mutex_lock(&conn->queuesem);
	pthread_cond_signal(&conn->queuecond);
	pthread_mutex_unlock(&conn->queuesem);
	return 0;
}

struct packet *
chaos_connection_dequeue(struct connection *conn)
{
	struct packet *packet;
	struct packet_queue *node;
#if 0
	unsigned short nextpacket;
#endif

	packet = NOPKT;
	node = 0;
#if 0
	nextpacket = conn->cn_rlast + 1;
#endif
	if (conn->cn_state == CSCLOSED)
		return NOPKT;
	for (;;) {
		pthread_mutex_lock(&conn->queuelock);
		if (TAILQ_EMPTY(&conn->orderhead) == false) {
#if 0
			struct packet_queue *prev;

			for (node = conn->orderhead; node; prev = node, node = node->next)
				if (node->packet->pk_pkn == nextpacket) {
					if (prev == 0)
						conn->orderhead = node->next;
					else
						prev->next = node->next;
					if (conn->ordertail == node)
						conn->ordertail = prev;
					packet = node->packet;
					break;
				}
#endif
#if 0
			TAILQ_FOREACH(node, &conn->orderhead, next) {
				if (node->packet->pk_pkn == nextpacket) {
					DEBUG(TRACE_CHAOS, "chaos: dequeued out-of-order packet %d\n", nextpacket);
					/*
					 * ---!! magic
					 */
					break;
				}
			}
#else
			DEBUG(TRACE_CHAOS, "chaos: ordered queue empty\n");
#endif
		}
		if (node == 0 && TAILQ_EMPTY(&conn->queuehead) == false) {
			node = TAILQ_FIRST(&conn->queuehead);
			packet = node->packet;
			TAILQ_REMOVE(&conn->queuehead, node, next);
		}
		pthread_mutex_unlock(&conn->queuelock);
		if (node) {
			free(node);
			node = 0;
		}
		if (packet) {
			if (cmp_gt(packet->pk_pkn, conn->cn_rlast))
				conn->cn_rlast = packet->pk_pkn;
			conn->cn_tacked = packet->pk_ackn;
			if (3 * (short) (conn->cn_rlast - conn->cn_racked) > conn->cn_rwsize) {
				struct packet *status;

				status = chaos_allocate_packet(conn, STSOP, 2 * sizeof(unsigned short));
				conn->cn_racked = conn->cn_rlast;
				*(unsigned short *) &status->pk_cdata[0] = conn->cn_rlast;
				*(unsigned short *) &status->pk_cdata[2] = conn->cn_rwsize;
				chaos_queue(status);
			}
			return packet;
		}
		pthread_mutex_lock(&conn->queuesem);
		pthread_cond_wait(&conn->queuecond, &conn->queuesem);
		pthread_mutex_unlock(&conn->queuesem);
		if (conn->cn_state == CSCLOSED)
			return NOPKT;
	}
}

static int
chaos_queue_time_pkt(unsigned short saddr, unsigned short sidx)
{
	time_t t;
	struct timeval time;
	struct packet *answer;

	INFO(TRACE_CHAOS, "chaos: RFC (TIME): answering...\n");
	gettimeofday(&time, NULL);
	t = time.tv_sec;
	t += 60UL * 60 * 24 * ((1970 - 1900) * 365L + 1970 / 4 - 1900 / 4);
	answer = pkalloc(sizeof(long), 0);
	answer->pk_op = ANSOP;
	SET_PH_LEN(answer->pk_phead, sizeof(long));
	SET_CH_ADDR(answer->pk_daddr, saddr);
	SET_CH_INDEX(answer->pk_didx, sidx);
	SET_CH_ADDR(answer->pk_saddr, chaos_addr(ucfg.chaos_servername, 0));
	SET_CH_INDEX(answer->pk_sidx, 0);
	answer->pk_pkn = 0;
	answer->pk_ackn = 0;
	*(long *) &answer->pk_cdata[0] = t;
	chaos_queue(answer);
	return 0;
}

static int
chaos_queue_uptime_pkt(unsigned short saddr, unsigned short sidx)
{
	struct packet *answer;

	INFO(TRACE_CHAOS, "chaos: RFC (UPTIME): answering...\n");
	answer = pkalloc(sizeof(long), 0);
	answer->pk_op = ANSOP;
	SET_PH_LEN(answer->pk_phead, sizeof(long));
	SET_CH_ADDR(answer->pk_daddr, saddr);
	SET_CH_INDEX(answer->pk_didx, sidx);
	SET_CH_ADDR(answer->pk_saddr, chaos_addr(ucfg.chaos_servername, 0));
	SET_CH_INDEX(answer->pk_sidx, 0);
	answer->pk_pkn = 0;
	answer->pk_ackn = 0;
	*(long *) &answer->pk_cdata[0] = 0;
	chaos_queue(answer);
	return 0;
}

static int
chaos_queue_status_pkt(unsigned short saddr, unsigned short sidx)
{
	struct packet *answer;
	struct status *status;

	INFO(TRACE_CHAOS, "chaos: RFC (STATUS): answering...\n");
	answer = pkalloc(CHSTATNAME + 2 * 2, 0);	/* Only room for name and subnet+nwords */
	answer->pk_op = ANSOP;
	SET_PH_LEN(answer->pk_phead, CHSTATNAME + 2 * 2);
	SET_CH_ADDR(answer->pk_daddr, saddr);
	SET_CH_INDEX(answer->pk_didx, sidx);
	SET_CH_ADDR(answer->pk_saddr, chaos_addr(ucfg.chaos_servername, 0));
	SET_CH_INDEX(answer->pk_sidx, 0);
	answer->pk_pkn = 0;
	answer->pk_ackn = 0;
	status = (struct status *) &answer->pk_cdata[0];
	memset(status, 0, sizeof(struct status));
	strncpy(status->sb_name, ucfg.chaos_servername, CHSTATNAME);
	status->sb_name[CHSTATNAME - 1] = '\0';
	/* Only put in the subnet (with the 400 marker) */
	status->sb_data->sb_ident = (chaos_addr(ucfg.chaos_servername, 0) >> 8) | 0400;
	/* and say no data is following */
	status->sb_data->sb_nshorts = 0 * sizeof(int) / sizeof(short);
	chaos_queue(answer);
	return 0;
}

static int
chaos_queue_file_pkt(struct packet *packet)
{
	void processdata(struct connection *conn);
	struct packet *answer;
	struct connection *conn;

	packet->pk_cdata[PH_LEN(packet->pk_phead)] = '\0';
	INFO(TRACE_CHAOS, "chaos: RFC (%s): answering...\n", &packet->pk_cdata);
	conn = allconn();
	conn->cn_faddr = packet->pk_saddr;
	conn->cn_fidx = packet->pk_sidx;
	answer = chaos_allocate_packet(conn, OPNOP, 2 * sizeof(unsigned short));
	answer->pk_ackn = packet->pk_pkn;
	conn->cn_racked = packet->pk_pkn;
	*(unsigned short *) &answer->pk_cdata[0] = packet->pk_pkn;	/* Last packed received. */
	*(unsigned short *) &answer->pk_cdata[2] = conn->cn_rwsize;
	chaos_connection_queue(conn, answer);
	conn->cn_state = CSLISTEN;
	processdata(conn);
	return 0;
}

static int
chaos_queue_mini_pkt(struct packet *packet)
{
	void processmini(struct connection *conn);
	struct packet *answer;
	struct connection *conn;

	packet->pk_cdata[PH_LEN(packet->pk_phead)] = '\0';
	INFO(TRACE_CHAOS, "chaos: RFC (%s): answering...\n", &packet->pk_cdata);
	conn = allconn();
	conn->cn_faddr = packet->pk_saddr;
	conn->cn_fidx = packet->pk_sidx;
	answer = chaos_allocate_packet(conn, OPNOP, 2 * sizeof(unsigned short));
	answer->pk_ackn = packet->pk_pkn;
	conn->cn_racked = packet->pk_pkn;
	*(unsigned short *) &answer->pk_cdata[0] = packet->pk_pkn;	/* Last packed received. */
	*(unsigned short *) &answer->pk_cdata[2] = conn->cn_rwsize;
	chaos_connection_queue(conn, answer);
	conn->cn_state = CSLISTEN;
	conn->cn_rlast = 1;
	processmini(conn);
	return 0;
}

static int
chaos_send_to_local(char *buffer, int size)
{				/* ---!!! rcvpkt ? */
	struct packet *packet;
	struct connection *conn;

	packet = (struct packet *) buffer;
	/*
	 * Local loopback.
	 */
	if (uch11_csr & CHAOS_CSR_LOOP_BACK) {
		DEBUG(TRACE_CHAOS, "chaos: loopback %d bytes\n", size);
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
		return 0;
	}
	DEBUG(TRACE_CHAOS, "chaos: transmitting packet (dest_addr = %o, uch11_myaddr=%o, size %d, wcount %d, op: %o)\n", CH_ADDR_SHORT(packet->pk_daddr), uch11_myaddr, size, (size + 1) / 2, packet->pk_op);
	/*
	 * Receive packets addressed to ourselves.
	 */
	if (CH_ADDR_SHORT(packet->pk_daddr) == uch11_myaddr) {
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
	}
	/*
	 * Ignore packets anything that isn't addressed to us.
	 */
	if (CH_ADDR_SHORT(packet->pk_daddr) != chaos_addr(ucfg.chaos_servername, 0)) {
		DEBUG(TRACE_CHAOS, "chaos: ignoring packet not to us (%o): %o\n", chaos_addr(ucfg.chaos_servername, 0), CH_ADDR_SHORT(packet->pk_daddr));
		return 0;
	}
	conn = chaos_find_connection(CH_INDEX_SHORT(packet->pk_didx));
	/*
	 * ---!!! Large parts of this is in rcvrfc.
	 */
	if (packet->pk_op == RFCOP) {
		DEBUG(TRACE_CHAOS, "chaos: got RFC packet\n");
		if (conn && conn->cn_state == CSLISTEN) {
			DEBUG(TRACE_CHAOS, "chaos: duplicate RFC\n");
			return 0;
		}
		if (conn) {
			struct packet *pkt;

			pkt = pkalloc((size_t) size, 0);
			memcpy(pkt, packet, size);
			chaos_connection_queue(conn, pkt);
			return 0;
		}
		if (memcmp(&packet->pk_cdata, "STATUS", 6) == 0)
			return chaos_queue_status_pkt(CH_ADDR_SHORT(packet->pk_saddr), CH_INDEX_SHORT(packet->pk_sidx));
		else if (memcmp(&packet->pk_cdata, "TIME", 4) == 0)
			return chaos_queue_time_pkt(CH_ADDR_SHORT(packet->pk_saddr), CH_INDEX_SHORT(packet->pk_sidx));
		else if (memcmp(&packet->pk_cdata, "UPTIME", 6) == 0)
			return chaos_queue_uptime_pkt(CH_ADDR_SHORT(packet->pk_saddr), CH_INDEX_SHORT(packet->pk_sidx));
		else if (memcmp(&packet->pk_cdata, "FILE", 4) == 0)
			return chaos_queue_file_pkt(packet);
		else if (memcmp(&packet->pk_cdata, "MINI", 4) == 0)
			return chaos_queue_mini_pkt(packet);
		else {
			char buffer[512];

			strncpy(buffer, (char *) packet->pk_cdata, PH_LEN(packet->pk_phead));
			buffer[PH_LEN(packet->pk_phead)] = '\0';
			WARNING(TRACE_CHAOS, "chaos: RFC (%s): protocol not implemented\n", buffer);
			return 0;
		}
	}
	if (packet->pk_op == SNSOP && conn) {
		struct packet *sts;

		sts = pkalloc(2 * sizeof(unsigned short) + 3 * sizeof(unsigned short), 1);
		sts->pk_op = STSOP;
		SET_PH_LEN(sts->pk_phead, 2 * sizeof(unsigned short));
		sts->pk_daddr = packet->pk_saddr;
		sts->pk_didx = packet->pk_sidx;
		conn->cn_faddr = packet->pk_saddr;
		conn->cn_fidx = packet->pk_sidx;
		sts->pk_saddr = conn->cn_laddr;
		sts->pk_sidx = conn->cn_lidx;
		sts->pk_pkn = packet->pk_pkn;
		if (cmp_gt(packet->pk_ackn, conn->cn_tacked))
			conn->cn_tacked = packet->pk_ackn;
		sts->pk_ackn = conn->cn_racked;
		*(unsigned short *) &sts->pk_cdata[0] = conn->cn_racked;
		*(unsigned short *) &sts->pk_cdata[2] = conn->cn_rwsize;
		chaos_connection_queue(conn, sts);
		return 0;
	}
	if (packet->pk_op == STSOP) {
		if (conn) {
			if (cmp_gt(packet->pk_ackn, conn->cn_tacked))
				conn->cn_tacked = packet->pk_ackn;
			if (conn->lastpacket && conn->cn_tacked == conn->lastpacket->pk_pkn) {
				free(conn->lastpacket);
				conn->lastpacket = 0;
			}
			conn->cn_state = CSOPEN;
			conn->cn_twsize = *(unsigned short *) &packet->pk_cdata[2];
			DEBUG(TRACE_CHAOS, "chaos: STSOP: twsize = %d\n", conn->cn_twsize);
			pthread_mutex_lock(&conn->twsem);
			pthread_cond_signal(&conn->twcond);
			pthread_mutex_unlock(&conn->twsem);
		}
		return 0;
	}
	if (conn && packet->pk_op == CLSOP) {	/* clsconn ? */
		DEBUG(TRACE_CHAOS, "chaos: CLSOP: got close \n");
		conn->cn_state = CSCLOSED;
		pthread_mutex_lock(&conn->queuesem);
		pthread_cond_signal(&conn->queuecond);
		pthread_mutex_unlock(&conn->queuesem);
		usleep(100000);	/* wait for queue to wake up */
		rlsconn(conn);
		return 0;
	}
	if (conn && (cmp_gt(conn->cn_rlast, packet->pk_pkn) || (conn->cn_rlast == packet->pk_pkn))) {
		struct packet *status;

		DEBUG(TRACE_CHAOS, "chaos: duplicate data packet\n");
		status = chaos_allocate_packet(conn, STSOP, 2 * sizeof(unsigned short));
		status->pk_pkn = packet->pk_pkn;
		conn->cn_racked = conn->cn_rlast;
		*(unsigned short *) &status->pk_cdata[0] = conn->cn_rlast;
		*(unsigned short *) &status->pk_cdata[2] = conn->cn_rwsize;
		chaos_connection_queue(conn, status);
		return 0;
	}
	if (conn) {
		struct packet *pkt;

		pkt = pkalloc((size_t) size, 0);
		memcpy(pkt, packet, size);
		chaos_connection_queue(conn, pkt);
	}
	return 0;
}

static int
chaos_poll_local(void)
{
	struct packet *packet;
	struct packet_queue *node;
	int size;

	/*
	 * Is RX buffer full?
	 */
	if (!uch11_rcv_buffer_empty && (uch11_csr & CHAOS_CSR_RECEIVE_DONE)) {
		DEBUG(TRACE_CHAOS, "chaos: polling, but unread data exists\n");
		return 0;
	}
	if (!uch11_rcv_buffer_empty) {
		DEBUG(TRACE_CHAOS, "chaos: polling, but buffer not empty\n");
		return 0;
	}
	if (TAILQ_EMPTY(&queuehead) == true) {
		return 0;
	}
	if (!(uch11_csr & CHAOS_CSR_RECEIVE_ENABLE)) {
		DEBUG(TRACE_CHAOS, "chaos: polling but rx not enabled\n");
		return 0;
	}
	pthread_mutex_lock(&recvqueue);
	node = TAILQ_FIRST(&queuehead);
	packet = node->packet;
	TAILQ_REMOVE(&queuehead, node, next);
	free(node);
	pthread_mutex_unlock(&recvqueue);
	size = ((PH_LEN(packet->pk_phead) & 0x0fff) + CHHEADSIZE + 1) / 2;
	/*
	 * Ignore any packets not to us.
	 */
	if (CH_ADDR_SHORT(packet->pk_daddr) != uch11_myaddr)
		return 0;
	memcpy(uch11_rcv_buffer, packet, (size_t) size * sizeof(unsigned short));
	/*
	 * Hardware header.
	 */
	uch11_rcv_buffer[size] = CH_ADDR_SHORT(packet->pk_daddr);
	uch11_rcv_buffer[size + 1] = CH_ADDR_SHORT(packet->pk_saddr);
	uch11_rcv_buffer[size + 2] = 0;
	size += 3;
	uch11_rcv_buffer_size = size;
	uch11_rcv_buffer_empty = false;
	DEBUG(TRACE_CHAOS, "chaos: polling: got chaos packet of %d bytes\n", uch11_rcv_buffer_size * 2);
#if 0
	dumpbuffer(uch11_rcv_buffer, size * 2);
#endif
	uch11_rx_pkt();
	return 0;
}

void
uch11_poll(void)
{
	if (uch11_backend == UCH11_BACKEND_LOCAL)
		chaos_poll_local();
	else if (uch11_backend == UCH11_BACKEND_DAEMON)







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







287
288
289
290
291
292
293








































































































































































































































































































































































































































































































































































































































































294
295
296
297
298
299
300
		if ((old_csr & CHAOS_CSR_TRANSMIT_ENABLE) == 0)
			DEBUG(TRACE_CHAOS, "chaos: CSR transmit enable\n");
		uch11_csr |= CHAOS_CSR_TRANSMIT_DONE;
	} else if (old_csr & CHAOS_CSR_TRANSMIT_ENABLE)
		DEBUG(TRACE_CHAOS, "chaos: CSR transmit DISable\n");
	DEBUG(TRACE_CHAOS, "chaos: set csr bits 0%o, old 0%o, new 0%o\n", v, old_csr, uch11_csr);
}









































































































































































































































































































































































































































































































































































































































































void
uch11_poll(void)
{
	if (uch11_backend == UCH11_BACKEND_LOCAL)
		chaos_poll_local();
	else if (uch11_backend == UCH11_BACKEND_DAEMON)
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
	}
	if (root_directory == NULL)
		err(1, "could not resolve %s", whichconf);
	NOTICE(TRACE_USIM, "chaos: mapping %s to %s\n", whichdir, root_directory);
	return 0;
}

/* Chaos over UDP */

int hybrid_udp_and_local = 0;

static int
chudpopen(void)
{
	int sock, lport, res, udp_dport, braddr;
	struct sockaddr_in sin;
	struct addrinfo *he, hi;
	struct in_addr udp_dest;

	if (hybrid_udp_and_local) {
		if (uch11_serveraddr == 0) {
			ERR(TRACE_CHAOS, "You configured udp_local_hybrid but there is no server address! Disabling hybrid.\n");
			hybrid_udp_and_local = 0;
		} else {
			/* Do the local init too */
			TAILQ_INIT(&queuehead);
			pthread_mutex_init(&recvqueue, NULL);
		}
	}

	/* Parse the local port given */
	if ((ucfg.chaos_bridgeport_local == NULL) || (ucfg.chaos_bridgeport_local[0] == '\0') || ((lport = atoi(ucfg.chaos_bridgeport_local)) <= 0) || (lport >= (1 << 16))) {
		/* Or default to 42042? */
		err(1, "bad bridgeport_local");
	}
	/* Parse the bridge port given */
	if ((ucfg.chaos_bridgeport == NULL) || (ucfg.chaos_bridgeport[0] == '\0') || ((udp_dport = atoi(ucfg.chaos_bridgeport)) <= 0) || (udp_dport >= (1 << 16))) {
		/* Or default to 42042? */
		err(1, "bad bridgeport");
	}
	/* Parse the bridge address given */
	if ((ucfg.chaos_bridgeip != NULL) && (ucfg.chaos_bridgeip[0] != '\0')) {
		/* @@@@ allow IPv6 */
		/* Check if it is an explicit IPv4 address */
		if (inet_aton(ucfg.chaos_bridgeip, &udp_dest) == 0) {
			/* Else try to parse a host name */
			memset(&hi, 0, sizeof(hi));
			hi.ai_family = AF_INET;
			hi.ai_flags = AI_ADDRCONFIG;
			if ((res = getaddrinfo(ucfg.chaos_bridgeip, NULL, &hi, &he)) == 0) {
				struct sockaddr_in *s = (struct sockaddr_in *) he->ai_addr;
				memcpy(&udp_dest.s_addr, (u_char *) & s->sin_addr, 4);
			} else {
				err(1, "bad bridgeip");
			}
		}
	} else {
		err(1, "no bridge?");
	}
	/* Parse bridge Chaos address */
	if ((ucfg.chaos_bridgechaos == NULL) || (ucfg.chaos_bridgechaos[0] == '\0') | (sscanf(ucfg.chaos_bridgechaos, "%o", &braddr) != 1) ||
	    /* Check it's a valid address */
	    (braddr == 0) || (braddr >= (1 << 16)) || ((braddr & 0xff) == 0) || (((braddr >> 8) & 0xff) == 0)) {
		err(1, "bad bridgechaos");
	} else {
		udp_bridge_chaddr = (braddr & 0xffff);
	}

	NOTICE(TRACE_USIM, "chaos: chudp init, bridge is %#o at %s:%d, local port %d, hybrid %s\n", udp_bridge_chaddr, inet_ntoa(udp_dest), udp_dport, lport, hybrid_udp_and_local ? "true" : "false");

	/* Now create a socket, and bind it to our local port */
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("socket failed");
		exit(1);
	}
	sin.sin_family = AF_INET;
	sin.sin_port = htons(lport);
	sin.sin_addr.s_addr = INADDR_ANY;
	if (bind(sock, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
		perror("udp bind failed");
		exit(1);
	}
	/* and then connect it to the remote address - since we're only using one and the same */
	sin.sin_port = htons(udp_dport);
	memcpy(&sin.sin_addr.s_addr, &udp_dest.s_addr, 4);
	if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
		perror("udp connect failed");
		exit(1);
	}
	return sock;
}

/* from chudp.h and cbridge-chaos.h */

// Max pkt size (12 bits) plus header
// The limit of 488 bytes is from MIT AIM 628, although more would fit any modern pkt (and 12 bits would give 4096 as max).
// This is due to original Chaos hardware pkts limited to 4032 bits, of which 16 bytes are header.
#define CH_PK_MAX_DATALEN 488

/* Protocol version */
#define CHUDP_VERSION 1
/* Protocol function codes */
#define CHUDP_PKT 1		/* Chaosnet packet */

struct chudp_header
{
	char chudp_version;
	char chudp_function;
	char chudp_arg1;
	char chudp_arg2;
};

struct chaos_hw_trailer
{
	unsigned short ch_hw_destaddr:16;
	unsigned short ch_hw_srcaddr:16;
	unsigned short ch_hw_checksum:16;
};

/* Max: CHUDP header, Chaos header, Chaos data, trailer */
#define CHUDP_MAXLEN (sizeof(struct chudp_header)+sizeof(struct pkt_header)+CH_PK_MAX_DATALEN+sizeof(struct chaos_hw_trailer))

static u_char trans_chudpbuf[CHUDP_MAXLEN];

/* So sorry about this. */
void
ntohs_buf(u_short *ibuf, u_short *obuf, int len)
{
	int i;
	for (i = 0; i < len; i += 2)
		*obuf++ = ntohs(*ibuf++);
}

static int
chaos_send_to_udp(char *buffer, int size)
{
	int wcount, dest_addr;

	/*
	 * Local loopback.
	 */
	if (uch11_csr & CHAOS_CSR_LOOP_BACK) {
		DEBUG(TRACE_CHAOS, "chaos: loopback %d bytes\n", size);
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
		return 0;
	}
	if (hybrid_udp_and_local) {
		/* Check if it is for our "local server" */
		struct packet *packet;
		packet = (struct packet *) buffer;
		if (CH_ADDR_SHORT(packet->pk_daddr) == chaos_addr(ucfg.chaos_servername, 0)) {
			return chaos_send_to_local(buffer, size);
		}
	}
	wcount = (size + 1) / 2;
	dest_addr = ((unsigned short *) buffer)[wcount - 3];
	DEBUG(TRACE_CHAOS, "chaos: sending packet to udp (dest_addr=%o, uch11_myaddr=%o, size %d, wcount %d)\n", dest_addr, uch11_myaddr, size, wcount);
	if (size > (int) CHUDP_MAXLEN) {
		ERR(TRACE_CHAOS, "chaos: packet too long: %d", size);
		return -1;
	}
	/*
	 * Receive packets addressed to us, or broadcasts.
	 */
	if ((dest_addr == uch11_myaddr) || (dest_addr == 0)) {
		memcpy(uch11_rcv_buffer, buffer, size);
		uch11_rcv_buffer_size = (size + 1) / 2;
		uch11_rcv_buffer_empty = false;
		uch11_rx_pkt();
		if (dest_addr != 0)	/* Broadcasts should be sent also to other */
			return 0;
	}
	if (chaosd_fd == -1) {
		ERR(TRACE_CHAOS, "chaos: transmit but chaosd_fd not open!\n");
		return 0;
	}
	{
		struct chudp_header *hp = (struct chudp_header *) &trans_chudpbuf;
		u_char *op = trans_chudpbuf + sizeof(struct chudp_header);
		int nb;

		memset(trans_chudpbuf, 0, sizeof(trans_chudpbuf));
		/* Set up CHUDP header */
		hp->chudp_version = CHUDP_VERSION;
		hp->chudp_function = CHUDP_PKT;

		memcpy(op, buffer, size);

		/* Update the hw trailer dest (and checksum) since what is there is probably the ultimate dest,
		 * but it should be just the next hop */
		struct pkt_header *ph = (struct pkt_header *) ((char *) op);
		u_short pklen = LENFC_LEN(ph->ph_lenfc);
		u_short offs = sizeof(struct pkt_header) + pklen;
		if (offs % 2)
			offs++;
		struct chaos_hw_trailer *tp = (struct chaos_hw_trailer *) (op + offs);
		u_short hwdest = tp->ch_hw_destaddr;
		u_short cksum = tp->ch_hw_checksum;
		if (hwdest != udp_bridge_chaddr) {
			INFO(TRACE_CHAOS, "chaos: hw trailer dest is %#o should be %#o\n", hwdest, udp_bridge_chaddr);
			tp->ch_hw_destaddr = udp_bridge_chaddr;
		}
		tp->ch_hw_checksum = htons(uch11_checksum(op, size - 2));

		/* Now swap it */
		ntohs_buf((u_short *) op, (u_short *) op, size);

		INFO(TRACE_CHAOS, "chaos: sending %d bytes (pkt size %d)\n", size + sizeof(struct chudp_header), size);
		if ((nb = send(chaosd_fd, (char *) hp, size + sizeof(struct chudp_header), 0)) < 0) {
			perror("chaos: send to udp");
			ERR(TRACE_CHAOS, "chaos: send to udp failed");
			return -1;
		} else if (nb != size + sizeof(struct chudp_header)) {
			ERR(TRACE_CHAOS, "chaos: could not send the full pkt: %d sent, expected %d", nb, size + sizeof(struct chudp_header));
			return -1;
		}
	}
	return 0;
}

static int
chaos_poll_udp(void)
{
	/* basically copy chaos_poll_chaosd but skip CHUDP header and swap */
	ssize_t ret;
	struct pollfd pfd[1];
	int nfds, timeout;
	unsigned char lenbytes[4];
	ssize_t len;
	int dest_addr;

	if (hybrid_udp_and_local) {
		/* Prioritize local traffic */
		chaos_poll_local();
	}

	if (chaosd_fd == -1) {
		return 0;
	}
	timeout = 0;
	nfds = 1;
	pfd[0].fd = chaosd_fd;
	pfd[0].events = POLLIN;
	pfd[0].revents = 0;
	ret = poll(pfd, nfds, timeout);
	if (ret == -1) {
		ERR(TRACE_CHAOS, "chaos: polling udp: nothing there (RDN=%o)\n", uch11_csr & CHAOS_CSR_RECEIVE_DONE);
		return -1;
	} else if (ret == 0) {
		// this happens all the time so don't
		// ERR(TRACE_CHAOS, "chaos: udp poll timeout\n");
		return -1;
	}
	/*
	 * Is RX buffer full?
	 */
	if (!uch11_rcv_buffer_empty && (uch11_csr & CHAOS_CSR_RECEIVE_DONE)) {
		/*
		 * Toss packets arriving when buffer is already in
		 * use, they will be resent.
		 */
		ERR(TRACE_CHAOS, "chaos: polling udp: unread data, drop (RDN=%o, lost %d)\n", uch11_csr & CHAOS_CSR_RECEIVE_DONE, uch11_lost_count);
		uch11_lost_count++;
		/* Toss it by reading it */
		ret = recv(chaosd_fd, (char *) uch11_rcv_buffer_toss, sizeof(uch11_rcv_buffer_toss), 0);
		DEBUG(TRACE_CHAOS, "chaos: tossing udp packet of %d bytes\n", ret);
		return -1;
	}
	ret = recv(chaosd_fd, (char *) uch11_rcv_buffer, sizeof(uch11_rcv_buffer), 0);
	if (ret == -1) {
		perror("chaos: udp read");
		return -1;
	} else if (ret == 0) {
		ERR(TRACE_CHAOS, "chaos: udp read zero bytes\n");
		return -1;
	} else if (ret > (int) CHUDP_MAXLEN) {
		ERR(TRACE_CHAOS, "chaos: udp read too many bytes: %d\n", ret);
		return -1;
	}
	INFO(TRACE_CHAOS, "chaos: polling; got udp packet len %d\n", ret);
	struct chudp_header *hp = (struct chudp_header *) uch11_rcv_buffer;
	if (hp->chudp_version != CHUDP_VERSION) {
		ERR(TRACE_CHAOS, "chaos: chudp version is wrong: %d\n", hp->chudp_version);
		return -1;
	}
	if (hp->chudp_function != CHUDP_PKT) {
		ERR(TRACE_CHAOS, "chaos: chudp function is wrong: %d\n", hp->chudp_function);
		return -1;
	}
	/* zap chudp header */
	memmove((char *) uch11_rcv_buffer, ((char *) uch11_rcv_buffer) + sizeof(struct chudp_header), ret - sizeof(struct chudp_header));
	ret -= sizeof(struct chudp_header);

	/* and swap it */
	ntohs_buf(uch11_rcv_buffer, uch11_rcv_buffer, ret);

	uch11_rcv_buffer_size = (ret + 1) / 2;
	uch11_rcv_buffer_empty = false;
	dest_addr = uch11_rcv_buffer[uch11_rcv_buffer_size - 3];
	/*
	 * If not to us (or broadcast), ignore.
	 */
	if ((dest_addr != uch11_myaddr) && (dest_addr != 0)) {
		INFO(TRACE_CHAOS, "chaos: ignoring packet not to us (%o): %o\n", uch11_myaddr, dest_addr);
		uch11_rcv_buffer_size = 0;
		uch11_rcv_buffer_empty = true;
		/*
		 * Should uch11_rx_pkt be called here?
		 */
		return 0;
	}
	INFO(TRACE_CHAOS, "chaos: udp receiving packet: from %o, my %o\n", dest_addr, uch11_myaddr);
	uch11_rx_pkt();
	return 0;
}







<
|
<
|
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
392
393
394
395
396
397
398

399

400







401











































































































































































































































































































	}
	if (root_directory == NULL)
		err(1, "could not resolve %s", whichconf);
	NOTICE(TRACE_USIM, "chaos: mapping %s to %s\n", whichdir, root_directory);
	return 0;
}


#include "uch11-chaosd.c"

#include "uch11-local.c"







#include "uch11-udp.c"