summaryrefslogtreecommitdiff
path: root/seq/aseqnet/aseqnet.c
blob: 77a885d7865cdc9702cd033fcb393161b4b0327e (plain)
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
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
/*
 * network server/client for ALSA sequencer
 *   ver.0.1
 *
 * Copyright (C) 1999-2000 Takashi Iwai
 * 
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/asoundlib.h>
#include <getopt.h>
#include <signal.h>

/*
 * prototypes
 */
static void usage(void);
static void init_buf(void);
static void init_pollfds(void);
static void close_files(void);
static void init_seq(char *source, char *dest);
static int get_port(char *service);
static void sigterm_exit(int sig);
static void init_server(int port);
static void init_client(char *server, int port);
static void do_loop(void);
static int copy_local_to_remote(void);
static int copy_remote_to_local(int fd);

/*
 * default TCP port number
 */
#define DEFAULT_PORT	40002

/*
 * local input buffer
 */
static char *readbuf;
static int max_rdlen;
static char *writebuf;
static int cur_wrlen, max_wrlen;

#define MAX_BUF_EVENTS	200
#define MAX_CONNECTION	10

static snd_seq_t *handle;
static struct pollfd *seqifds = NULL;
static struct pollfd *seqofds = NULL;
static struct pollfd *pollfds = NULL;
static int seqifds_count = 0;
static int seqofds_count = 0;
static int pollfds_count = 0;
static int sockfd, netfd[MAX_CONNECTION] = {[0 ... MAX_CONNECTION-1] = -1};
static int max_connection;
static int cur_connected;
static int seq_port;

static int server_mode;
static int verbose = 0;


/*
 * main routine
 */

static struct option long_option[] = {
	{"port", 1, NULL, 'p'},
	{"source", 1, NULL, 's'},
	{"dest", 1, NULL, 'd'},
	{"help", 0, NULL, 'h'},
	{"verbose", 0, NULL, 'v'},
	{NULL, 0, NULL, 0},
};

int main(int argc, char **argv)
{
	int c;
	int port = DEFAULT_PORT;
	char *source = NULL, *dest = NULL;

	while ((c = getopt_long(argc, argv, "p:s:d:v", long_option, NULL)) != -1) {
		switch (c) {
		case 'p':
			if (isdigit(*optarg))
				port = atoi(optarg);
			else
				port = get_port(optarg);
			break;
		case 's':
			source = optarg;
			break;
		case 'd':
			dest = optarg;
			break;
		case 'v':
			verbose++;
			break;
		default:
			usage();
			exit(1);
		}
	}

	signal(SIGINT, sigterm_exit);
	signal(SIGTERM, sigterm_exit);

	init_buf();
	init_seq(source, dest);

	if (optind >= argc) {
		server_mode = 1;
		max_connection = MAX_CONNECTION;
		init_pollfds();
		init_server(port);
	} else {
		server_mode = 0;
		max_connection = 1;
		init_pollfds();
		init_client(argv[optind], port);
	}

	do_loop();

	close_files();

	return 0;
}


/*
 * print usage
 */
static void usage(void)
{
	fprintf(stderr, "aseqnet - network client/server on ALSA sequencer\n");
	fprintf(stderr, "  Copyright (C) 1999 Takashi Iwai\n");
	fprintf(stderr, "usage:\n");
	fprintf(stderr, "  server mode: aseqnet [-options]\n");
	fprintf(stderr, "  client mode: aseqnet [-options] server_host\n");
	fprintf(stderr, "options:\n");
	fprintf(stderr, "  -p,--port # : sepcify TCP port (digit or service name)\n");
	fprintf(stderr, "  -s,--source addr : read from given addr (client:port)\n");
	fprintf(stderr, "  -d,--dest addr : write to given addr (client:port)\n");
	fprintf(stderr, "  -v, --verbose : print verbose messages\n");
}


/*
 * allocate and initialize buffers
 */
static void init_buf(void)
{
	max_wrlen = MAX_BUF_EVENTS * sizeof(snd_seq_event_t);
	max_rdlen = MAX_BUF_EVENTS * sizeof(snd_seq_event_t);
	writebuf = malloc(max_wrlen);
	readbuf = malloc(max_rdlen);
	if (writebuf == NULL || readbuf == NULL) {
		fprintf(stderr, "can't malloc\n");
		exit(1);
	}
	memset(writebuf, 0, max_wrlen);
	memset(readbuf, 0, max_rdlen);
	cur_wrlen = 0;
}

/*
 * allocate and initialize poll array
 */
static void init_pollfds(void)
{
	pollfds_count = seqifds_count + seqofds_count + 1 + max_connection;
	pollfds = (struct pollfd *)calloc(pollfds_count, sizeof(struct pollfd));
	assert(pollfds);
}

/*
 * parse command line to client:port
 * NB: the given string will be broken.
 */
static int parse_address(snd_seq_t *seq, snd_seq_addr_t *addr, char *arg)
{
	char *p;
	int client, port;

	if ((p = strpbrk(arg, ":.")) == NULL)
		return -1;
	if ((port = atoi(p + 1)) < 0)
		return -1;
	addr->port = port;
	if (isdigit(*arg)) {
		client = atoi(arg);
		if (client < 0)
			return -1;
		addr->client = client;
	} else {
		/* convert from the name */
		snd_seq_client_info_t cinfo;
		int len;

		*p = 0;
		len = strlen(arg);
		if (len <= 0)
			return -1;
		cinfo.client = -1;
		while (snd_seq_query_next_client(seq, &cinfo) >= 0) {
			if (! strncmp(cinfo.name, arg, len)) {
				addr->client = cinfo.client;
				return 0;
			}
		}
		return -1; /* not found */
	}
	return 0;
}


/*
 * close all files
 */
static void close_files(void)
{
	int i;
	if (verbose)
		fprintf(stderr, "closing files..\n");
	for (i = 0; i < max_connection; i++) {
		if (netfd[i] >= 0)
			close(netfd[i]);
	}
	if (sockfd >= 0)
		close(sockfd);
}


/*
 * initialize sequencer
 */
static void init_seq(char *source, char *dest)
{
	snd_seq_addr_t addr;
	int err, counti, counto;

	if (snd_seq_open(&handle, "hw", SND_SEQ_OPEN_DUPLEX, 0) < 0) {
		perror("snd_seq_open");
		exit(1);
	}
	if (seqifds)
		free(seqifds);
	if (seqofds)
		free(seqofds);
	counti = seqifds_count = snd_seq_poll_descriptors_count(handle, POLLIN);
	assert(counti > 0);
	counto = seqofds_count = snd_seq_poll_descriptors_count(handle, POLLOUT);
	assert(counto > 0);
	seqifds = (struct pollfd *)calloc(counti, sizeof(struct pollfd));
	assert(seqifds);
	seqofds = (struct pollfd *)calloc(counto, sizeof(struct pollfd));
	assert(seqofds);
	err = snd_seq_poll_descriptors(handle, seqifds, counti, POLLIN);
	assert(err == counti);
	err = snd_seq_poll_descriptors(handle, seqofds, counto, POLLOUT);
	assert(err == counto);

	snd_seq_nonblock(handle, 0);

	/* set client info */
	if (server_mode)
		snd_seq_set_client_name(handle, "Net Server");
	else
		snd_seq_set_client_name(handle, "Net Client");

	/* create a port */
	seq_port = snd_seq_create_simple_port(handle, "Network",
					      SND_SEQ_PORT_CAP_READ |
					      SND_SEQ_PORT_CAP_WRITE |
					      SND_SEQ_PORT_CAP_SUBS_READ |
					      SND_SEQ_PORT_CAP_SUBS_WRITE,
					      SND_SEQ_PORT_TYPE_MIDI_GENERIC);
	if (seq_port < 0) {
		perror("create seq port");
		exit(1);
	}
	if (verbose)
		fprintf(stderr, "sequencer opened: %d:%d\n",
			snd_seq_client_id(handle), seq_port);

	/* explicit subscriptions */
	if (source) {
		/* read subscription */
		if (parse_address(handle, &addr, source) < 0) {
			fprintf(stderr, "invalid source address %s\n", source);
			exit(1);
		}
		if (snd_seq_connect_from(handle, seq_port, addr.client, addr.port)) {
			perror("read subscription");
			exit(1);
		}
	}
	if (dest) {
		/* write subscription */
		if (parse_address(handle, &addr, dest) < 0) {
			fprintf(stderr, "invalid destination address %s\n", dest);
			exit(1);
		}
		if (snd_seq_connect_to(handle, seq_port, addr.client, addr.port)) {
			perror("write subscription");
			exit(1);
		}
	}
}


/*
 * convert from string to TCP port number
 */
static int get_port(char *service)
{
	struct servent *sp;

	if ((sp = getservbyname(service, "tcp")) == NULL){
		fprintf(stderr, "service '%s' is not found in /etc/services\n", service);
		return -1;
	}
	return sp->s_port;
}

/*
 * signal handler
 */
static void sigterm_exit(int sig)
{
	close_files();
	exit(1);
}


/*
 * initialize network server
 */
static void init_server(int port)
{
	int i;
	int curstate = 1;
	struct sockaddr_in addr;

	memset(&addr, 0, sizeof(addr));

	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = INADDR_ANY;
	addr.sin_port = htons(port);

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0)  {
		perror("create socket");
		exit(1);
	}
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &curstate, sizeof(curstate));
	/* the return value is ignored.. */

	if (bind(sockfd, &addr, sizeof(addr)) < 0)  {
		perror("can't bind");
		exit(1);
	}

	if (listen(sockfd, 5) < 0)  {
		perror("can't listen");
		exit(1);
	}

	cur_connected = 0;
	for (i = 0; i < max_connection; i++)
		netfd[i] = -1;
}

/*
 * start connection on server
 */
static void start_connection(void)
{
	struct sockaddr_in addr;
	int i;
	int addr_len;

	for (i = 0; i < max_connection; i++) {
		if (netfd[i] < 0)
			break;
	}
	if (i >= max_connection) {
		fprintf(stderr, "too many connections!\n");
		exit(1);
	}
	memset(&addr, 0, sizeof(addr));
	addr_len = sizeof(addr);
	netfd[i] = accept(sockfd, (struct sockaddr *)&addr, &addr_len);
	if (netfd[i] < 0) {
		perror("accept");
		exit(1);
	}
	if (verbose)
		fprintf(stderr, "accepted[%d]\n", netfd[i]);
	cur_connected++;
}

/*
 * initialize network client
 */
static void init_client(char *server, int port)
{
	struct sockaddr_in addr;
	struct hostent *host;
	int curstate = 1;
	int fd;

	if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
		perror("create socket");
		exit(1);
	}
	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &curstate, sizeof(curstate)) < 0) {
		perror("setsockopt");
		exit(1);
	}
	if ((host = gethostbyname(server)) == NULL){
		fprintf(stderr,"can't get address %s\n", server);
		exit(1);
	}
	addr.sin_port = htons(port);
	addr.sin_family = AF_INET;
	memcpy(&addr.sin_addr, host->h_addr, host->h_length);
	if (connect(fd, &addr, sizeof(addr)) < 0) {
		perror("connect");
		exit(1);
	}
	if (verbose)
		fprintf(stderr, "ok.. connected\n");
	netfd[0] = fd;
	cur_connected = 1;
}

/*
 * event loop
 */
static void do_loop(void)
{
	int i, rc, width;
	int seqifd_ptr, sockfd_ptr = -1, netfd_ptr;

	for (;;) {
		memset(pollfds, 0, pollfds_count * sizeof(struct pollfd));
		seqifd_ptr = 0;
		memcpy(pollfds, seqifds, width = seqifds_count);
		if (server_mode) {
			sockfd_ptr = width;
			pollfds[width].fd = sockfd;
			pollfds[width].events = POLLIN;
			width++;
		}
		netfd_ptr = width;
		for (i = 0; i < max_connection; i++) {
			if (netfd[i] >= 0) {
				pollfds[width].fd = netfd[i];
				pollfds[width].events = POLLIN;
				width++;
			}
		}
		rc = poll(pollfds, width, -1);
		if (rc <= 0)
			exit(1);
		if (server_mode) {
			if (pollfds[sockfd_ptr].revents & (POLLIN|POLLOUT))
				start_connection();
		}
		for (i = 0; i < seqifds_count; i++)
			if (pollfds[seqifd_ptr + i].revents & (POLLIN|POLLOUT)) {
				if (copy_local_to_remote())
					return;
				break;
			}
		for (i = 0; i < max_connection; i++) {
			if (netfd[i] < 0)
				continue;
			if (pollfds[netfd_ptr + i].revents & (POLLIN|POLLOUT)) {
				if (copy_remote_to_local(netfd[i])) {
					netfd[i] = -1;
					cur_connected--;
					if (cur_connected <= 0)
						return;
				}
			}
		}
	}
}


/*
 * flush write buffer - send data to the socket
 */
static void flush_writebuf(void)
{
	if (cur_wrlen) {
		int i;
		for (i = 0; i < max_connection; i++) {
			if (netfd[i] >= 0)
				write(netfd[i], writebuf, cur_wrlen);
		}
		cur_wrlen = 0;
	}
}

/*
 * get space from write buffer
 */
static char *get_writebuf(int len)
{
	char *buf;
	if (cur_wrlen + len >= max_wrlen)
		flush_writebuf();
	buf = writebuf + cur_wrlen;
	cur_wrlen += len;
	return buf;
}

/*
 * copy events from sequencer to port(s)
 */
static int copy_local_to_remote(void)
{
	int rc;
	snd_seq_event_t *ev;
	char *buf;

	while ((rc = snd_seq_event_input(handle, &ev)) >= 0 && ev) {
		if (ev->type >= SND_SEQ_EVENT_CLIENT_START &&
		    ! snd_seq_ev_is_variable_type(ev)) {
			snd_seq_free_event(ev);
			continue;
		}
		if (snd_seq_ev_is_variable(ev)) {
			int len;
			len = sizeof(snd_seq_event_t) + ev->data.ext.len;
			buf = get_writebuf(len);
			memcpy(buf, ev, sizeof(snd_seq_event_t));
			memcpy(buf + sizeof(snd_seq_event_t), ev->data.ext.ptr, ev->data.ext.len);
		} else {
			buf = get_writebuf(sizeof(snd_seq_event_t));
			memcpy(buf, ev, sizeof(snd_seq_event_t));
		}
		snd_seq_free_event(ev);
	}
	flush_writebuf();
	return 0;
}

/*
 * copy events from a port to sequencer
 */
static int copy_remote_to_local(int fd)
{
	int count;
	char *buf;
	snd_seq_event_t *ev;

	count = read(fd, readbuf, MAX_BUF_EVENTS * sizeof(snd_seq_event_t));
	buf = readbuf;

	if (count == 0) {
		if (verbose)
			fprintf(stderr, "disconnected\n");
		return 1;
	}

	while (count > 0) {
		ev = (snd_seq_event_t*)buf;
		buf += sizeof(snd_seq_event_t);
		count -= sizeof(snd_seq_event_t);
		if (snd_seq_ev_is_variable(ev) && ev->data.ext.len > 0) {
			ev->data.ext.ptr = buf;
			buf += ev->data.ext.len;
			count -= ev->data.ext.len;
		}
		snd_seq_ev_set_direct(ev);
		snd_seq_ev_set_source(ev, seq_port);
		snd_seq_ev_set_subs(ev);
		snd_seq_event_output(handle, ev);
	}

	snd_seq_drain_output(handle);
	return 0;
}