stream.h 21.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * Copyright (c) 2015-2016 Hanspeter Portner (dev@open-music-kontrollers.ch)
 *
 * This is free software: you can redistribute it and/or modify
 * it under the terms of the Artistic License 2.0 as published by
 * The Perl Foundation.
 *
 * This source 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
 * Artistic License 2.0 for more details.
 *
 * You should have received a copy of the Artistic License 2.0
 * along the source as a COPYING file. If not, obtain it from
 * http://www.perlfoundation.org/artistic_license_2_0.
 */

#ifndef LV2_OSC_STREAM_H
#define LV2_OSC_STREAM_H

#include <stdbool.h>
#include <string.h>
23 24 25 26 27 28 29
#if !defined(_WIN32)
#	include <arpa/inet.h>
#	include <sys/socket.h>
#	include <net/if.h>
#	include <netinet/tcp.h>
#	include <netdb.h>
#endif
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
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>

#include <osc.lv2/osc.h>

#if !defined(LV2_OSC_STREAM_SNDBUF)
#	define LV2_OSC_STREAM_SNDBUF 0x100000 // 1 M
#endif

#if !defined(LV2_OSC_STREAM_RCVBUF)
#	define LV2_OSC_STREAM_RCVBUF 0x100000 // 1 M
#endif

#if !defined(LV2_OSC_STREAM_REQBUF)
#	define LV2_OSC_STREAM_REQBUF 1024
#endif

#ifdef __cplusplus
extern "C" {
#endif

typedef void *
(*LV2_OSC_Stream_Write_Request)(void *data, size_t minimum, size_t *maximum);

typedef void
(*LV2_OSC_Stream_Write_Advance)(void *data, size_t written);

typedef const void *
(*LV2_OSC_Stream_Read_Request)(void *data, size_t *toread);

typedef void
(*LV2_OSC_Stream_Read_Advance)(void *data);

typedef struct _LV2_OSC_Address LV2_OSC_Address;
typedef struct _LV2_OSC_Driver LV2_OSC_Driver;
typedef struct _LV2_OSC_Stream LV2_OSC_Stream;

struct _LV2_OSC_Address {
	socklen_t len;
	union {
		struct sockaddr in;
		struct sockaddr_in in4;
		struct sockaddr_in6 in6;
	};
};

struct _LV2_OSC_Driver {
	LV2_OSC_Stream_Write_Request write_req;
	LV2_OSC_Stream_Write_Advance write_adv;
	LV2_OSC_Stream_Read_Request read_req;
	LV2_OSC_Stream_Read_Advance read_adv;
};

struct _LV2_OSC_Stream {
	int socket_family;
	int socket_type;
	int protocol;
	bool server;
	bool slip;
91
	bool connected;
92 93 94 95 96 97
	int sock;
	int fd;
	LV2_OSC_Address self;
	LV2_OSC_Address peer;
	const LV2_OSC_Driver *driv;
	void *data;
98 99
	uint8_t tx_buf [0x4000];
	uint8_t rx_buf [0x4000];
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
	size_t rx_off;
};

typedef enum _LV2_OSC_Enum {
	LV2_OSC_NONE = (0 << 0),
	LV2_OSC_SEND = (1 << 0),
	LV2_OSC_RECV = (1 << 1)
} LV2_OSC_Enum;

static const char *udp_prefix = "osc.udp://";
static const char *tcp_prefix = "osc.tcp://";
static const char *tcp_slip_prefix = "osc.slip.tcp://";
static const char *tcp_prefix_prefix = "osc.prefix.tcp://";
//FIXME serial

static int
lv2_osc_stream_init(LV2_OSC_Stream *stream, const char *url,
	const LV2_OSC_Driver *driv, void *data)
{
	memset(stream, 0x0, sizeof(LV2_OSC_Stream));

	char *dup = strdup(url);
	if(!dup)
	{
		fprintf(stderr, "%s: out-of-memory\n", __func__);
		goto fail;
	}

	char *ptr = dup;
	char *tmp;

	if(strncmp(ptr, udp_prefix, strlen(udp_prefix)) == 0)
	{
		stream->slip = false;
		stream->socket_family = AF_INET;
		stream->socket_type = SOCK_DGRAM;
		stream->protocol = IPPROTO_UDP;
		ptr += strlen(udp_prefix);
	}
	else if(strncmp(ptr, tcp_prefix, strlen(tcp_prefix)) == 0)
	{
		stream->slip = true;
		stream->socket_family = AF_INET;
		stream->socket_type = SOCK_STREAM;
		stream->protocol = IPPROTO_TCP;
		ptr += strlen(tcp_prefix);
	}
	else if(strncmp(ptr, tcp_slip_prefix, strlen(tcp_slip_prefix)) == 0)
	{
		stream->slip = true;
		stream->socket_family = AF_INET;
		stream->socket_type = SOCK_STREAM;
		stream->protocol = IPPROTO_TCP;
		ptr += strlen(tcp_slip_prefix);
	}
	else if(strncmp(ptr, tcp_prefix_prefix, strlen(tcp_prefix_prefix)) == 0)
	{
		stream->slip = false;
		stream->socket_family = AF_INET;
		stream->socket_type = SOCK_STREAM;
		stream->protocol = IPPROTO_TCP;
		ptr += strlen(tcp_prefix_prefix);
	}
	else
	{
		fprintf(stderr, "%s: invalid protocol\n", __func__);
		goto fail;
	}

	if(ptr[0] == '\0')
	{
		fprintf(stderr, "%s: URI has no colon\n", __func__);
		goto fail;
	}

	const char *node = NULL;
	const char *iface = NULL;
	const char *service = NULL;

	// optional IPv6
	if(ptr[0] == '[')
	{
		stream->socket_family = AF_INET6;
		++ptr;
	}

	node = ptr;

	// optional IPv6
	if( (tmp = strchr(ptr, '%')) )
	{
		if(stream->socket_family != AF_INET6)
		{
			fprintf(stderr, "%s: no IPv6 interface delimiter expected here\n", __func__);
			goto fail;
		}

		ptr = tmp;
		ptr[0] = '\0';
		iface = ++ptr;
	}

	// optional IPv6
	if( (tmp = strchr(ptr, ']')) )
	if(ptr)
	{
		if(stream->socket_family != AF_INET6)
		{
			fprintf(stderr, "%s: no closing IPv6 bracket expected here\n", __func__);
			goto fail;
		}

		ptr = tmp;
		ptr[0] = '\0';
		++ptr;
	}

	// mandatory IPv4/6
	ptr = strchr(ptr, ':');
	if(!ptr)
	{
		fprintf(stderr, "%s: pre-service colon expected\n", __func__);
		goto fail;
	}

	ptr[0] = '\0';

	service = ++ptr;

	if(strlen(node) == 0)
	{
		node = NULL;
		stream->server = true;
	}

	stream->sock = socket(stream->socket_family, stream->socket_type,
		stream->protocol);

	if(stream->sock < 0)
	{
		fprintf(stderr, "%s: socket failed\n", __func__);
		goto fail;
	}

	if(fcntl(stream->sock, F_SETFL, O_NONBLOCK) == -1)
	{
		fprintf(stderr, "%s: fcntl failed\n", __func__);
		goto fail;
	}

	const int sendbuff = LV2_OSC_STREAM_SNDBUF;
	const int recvbuff = LV2_OSC_STREAM_RCVBUF;

	if(setsockopt(stream->sock, SOL_SOCKET,
		SO_SNDBUF, &sendbuff, sizeof(int))== -1)
	{
		fprintf(stderr, "%s: setsockopt failed\n", __func__);
		goto fail;
	}

	if(setsockopt(stream->sock, SOL_SOCKET,
		SO_RCVBUF, &recvbuff, sizeof(int))== -1)
	{
		fprintf(stderr, "%s: setsockopt failed\n", __func__);
		goto fail;
	}

	stream->driv = driv;
	stream->data = data;

	if(stream->socket_family == AF_INET) // IPv4
	{
		if(stream->server)
		{
			// resolve self address
			struct addrinfo hints;
			memset(&hints, 0x0, sizeof(struct addrinfo));
			hints.ai_family = stream->socket_family;
			hints.ai_socktype = stream->socket_type;
			hints.ai_protocol = stream->protocol;

			struct addrinfo *res;
			if(getaddrinfo(node, service, &hints, &res) != 0)
			{
				fprintf(stderr, "%s: getaddrinfo failed\n", __func__);
				goto fail;
			}
			if(res->ai_addrlen != sizeof(stream->peer.in4))
			{
				fprintf(stderr, "%s: IPv4 address expected\n", __func__);
				goto fail;
			}

			stream->self.len = res->ai_addrlen;
			stream->self.in = *res->ai_addr;
			stream->self.in4.sin_addr.s_addr = htonl(INADDR_ANY);

			freeaddrinfo(res);

			if(bind(stream->sock, &stream->self.in, stream->self.len) != 0)
			{
				fprintf(stderr, "%s: bind failed\n", __func__);
				goto fail;
			}
		}
		else // client
		{
			stream->self.len = sizeof(stream->self.in4);
			stream->self.in4.sin_family = stream->socket_family;
			stream->self.in4.sin_port = htons(0);
			stream->self.in4.sin_addr.s_addr = htonl(INADDR_ANY);

			if(bind(stream->sock, &stream->self.in, stream->self.len) != 0)
			{
				fprintf(stderr, "%s: bind failed\n", __func__);
				goto fail;
			}

			// resolve peer address
			struct addrinfo hints;
			memset(&hints, 0x0, sizeof(struct addrinfo));
			hints.ai_family = stream->socket_family;
			hints.ai_socktype = stream->socket_type;
			hints.ai_protocol = stream->protocol;

			struct addrinfo *res;
			if(getaddrinfo(node, service, &hints, &res) != 0)
			{
				fprintf(stderr, "%s: getaddrinfo failed\n", __func__);
				goto fail;
			}
			if(res->ai_addrlen != sizeof(stream->peer.in4))
			{
				fprintf(stderr, "%s: IPv4 address failed\n", __func__);
				goto fail;
			}

			stream->peer.len = res->ai_addrlen;
			stream->peer.in = *res->ai_addr;

			freeaddrinfo(res);
		}

		if(stream->socket_type == SOCK_DGRAM)
		{
			const int broadcast = 1;

			if(setsockopt(stream->sock, SOL_SOCKET, SO_BROADCAST,
				&broadcast, sizeof(broadcast)) != 0)
			{
				fprintf(stderr, "%s: setsockopt failed\n", __func__);
				goto fail;
			}

			//FIXME handle multicast
		}
		else if(stream->socket_type == SOCK_STREAM)
		{
			const int flag = 1;

			if(setsockopt(stream->sock, stream->protocol,
				TCP_NODELAY, &flag, sizeof(int)) != 0)
			{
				fprintf(stderr, "%s: setsockopt failed\n", __func__);
				goto fail;
			}

			if(setsockopt(stream->sock, SOL_SOCKET,
				SO_KEEPALIVE, &flag, sizeof(int)) != 0)
			{
				fprintf(stderr, "%s: setsockopt failed\n", __func__);
				goto fail;
			}

			if(stream->server)
			{
				if(listen(stream->sock, 1) != 0)
				{
					fprintf(stderr, "%s: listen failed\n", __func__);
					goto fail;
				}
			}
			else // client
			{
384 385 386 387
				if(connect(stream->sock, &stream->peer.in, stream->peer.len) == 0)
				{
					stream->connected = true;
				}
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
			}
		}
		else
		{
			fprintf(stderr, "%s: invalid socket type\n", __func__);
			goto fail;
		}
	}
	else if(stream->socket_family == AF_INET6) // IPv6
	{
		if(stream->server)
		{
			// resolve self address
			struct addrinfo hints;
			memset(&hints, 0x0, sizeof(struct addrinfo));
			hints.ai_family = stream->socket_family;
			hints.ai_socktype = stream->socket_type;
			hints.ai_protocol = stream->protocol;

			struct addrinfo *res;
			if(getaddrinfo(node, service, &hints, &res) != 0)
			{
				fprintf(stderr, "%s: getaddrinfo failed\n", __func__);
				goto fail;
			}
			if(res->ai_addrlen != sizeof(stream->peer.in6))
			{
				fprintf(stderr, "%s: IPv6 address expected\n", __func__);
				goto fail;
			}

			stream->self.len = res->ai_addrlen;
			stream->self.in = *res->ai_addr;
			stream->self.in6.sin6_addr = in6addr_any;
			if(iface)
			{
				stream->self.in6.sin6_scope_id = if_nametoindex(iface);
			}

			freeaddrinfo(res);

			if(bind(stream->sock, &stream->self.in, stream->self.len) != 0)
			{
				fprintf(stderr, "%s: bind failed\n", __func__);
				goto fail;
			}
		}
		else // client
		{
			stream->self.len = sizeof(stream->self.in6);
			stream->self.in6.sin6_family = stream->socket_family;
			stream->self.in6.sin6_port = htons(0);
			stream->self.in6.sin6_addr = in6addr_any;
			if(iface)
			{
				stream->self.in6.sin6_scope_id = if_nametoindex(iface);
			}

			if(bind(stream->sock, &stream->self.in, stream->self.len) != 0)
			{
				fprintf(stderr, "%s: bind failed\n", __func__);
				goto fail;
			}

			// resolve peer address
			struct addrinfo hints;
			memset(&hints, 0x0, sizeof(struct addrinfo));
			hints.ai_family = stream->socket_family;
			hints.ai_socktype = stream->socket_type;
			hints.ai_protocol = stream->protocol;

			struct addrinfo *res;
			if(getaddrinfo(node, service, &hints, &res) != 0)
			{
				fprintf(stderr, "%s: getaddrinfo failed\n", __func__);
				goto fail;
			}
			if(res->ai_addrlen != sizeof(stream->peer.in6))
			{
				fprintf(stderr, "%s: IPv6 address expected\n", __func__);
				goto fail;
			}
			stream->peer.len = res->ai_addrlen;
			stream->peer.in = *res->ai_addr;
			if(iface)
			{
				stream->peer.in6.sin6_scope_id = if_nametoindex(iface);
			}

			freeaddrinfo(res);
		}

		if(stream->socket_type == SOCK_DGRAM)
		{
			// nothing to do
		}
		else if(stream->socket_type == SOCK_STREAM)
		{
			const int flag = 1;

			if(setsockopt(stream->sock, stream->protocol,
				TCP_NODELAY, &flag, sizeof(int)) != 0)
			{
				fprintf(stderr, "%s: setsockopt failed\n", __func__);
				goto fail;
			}

			if(setsockopt(stream->sock, SOL_SOCKET,
				SO_KEEPALIVE, &flag, sizeof(int)) != 0)
			{
				fprintf(stderr, "%s: setsockopt failed\n", __func__);
				goto fail;
			}

			if(stream->server)
			{
				if(listen(stream->sock, 1) != 0)
				{
					fprintf(stderr, "%s: listen failed\n", __func__);
					goto fail;
				}
			}
			else // client
			{
512 513 514 515
				if(connect(stream->sock, &stream->peer.in, stream->peer.len) == 0)
				{
					stream->connected = true;
				}
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
			}
		}
		else
		{
			fprintf(stderr, "%s: invalid socket type\n", __func__);
			goto fail;
		}
	}
	else
	{
		fprintf(stderr, "%s: invalid socket family\n", __func__);
		goto fail;
	}

	free(dup);

	return 0;

fail:
	if(dup)
	{
		free(dup);
	}

	if(stream->sock >= 0)
	{
		close(stream->sock);
543
		stream->sock = -1;
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
	}

	return -1;
}

#define SLIP_END					0300	// 0xC0, 192, indicates end of packet
#define SLIP_ESC					0333	// 0xDB, 219, indicates byte stuffing
#define SLIP_END_REPLACE	0334	// 0xDC, 220, ESC ESC_END means END data byte
#define SLIP_ESC_REPLACE	0335	// 0xDD, 221, ESC ESC_ESC means ESC data byte

// SLIP encoding
static size_t
lv2_osc_slip_encode_inline(uint8_t *dst, size_t len)
{
	if(len == 0)
		return 0;

	const uint8_t *end = dst + len;

	// estimate new size
	size_t size = 2; // double ended SLIP
	for(const uint8_t *from=dst; from<end; from++, size++)
	{
		if( (*from == SLIP_END) || (*from == SLIP_ESC))
			size ++;
	}

	// fast track if no escaping needed
	if(size == len + 2)
	{
		memmove(dst+1, dst, len);
		dst[0] = SLIP_END;
		dst[size-1] = SLIP_END;

		return size;
	}

	// slow track if some escaping needed
	uint8_t *to = dst + size - 1;
	*to-- = SLIP_END;
	for(const uint8_t *from=end-1; from>=dst; from--)
	{
		if(*from == SLIP_END)
		{
			*to-- = SLIP_END_REPLACE;
			*to-- = SLIP_ESC;
		}
		else if(*from == SLIP_ESC)
		{
			*to-- = SLIP_ESC_REPLACE;
			*to-- = SLIP_ESC;
		}
		else
			*to-- = *from;
	}
	*to-- = SLIP_END;

	return size;
}

// SLIP decoding
static size_t 
lv2_osc_slip_decode_inline(uint8_t *dst, size_t len, size_t *size)
{
	const uint8_t *src = dst;
	const uint8_t *end = dst + len;
	uint8_t *ptr = dst;

	bool whole = false;

	if( (src < end) && (*src == SLIP_END) )
	{
		 whole = true;
		 src++;
	}

	while(src < end)
	{
		if(*src == SLIP_ESC)
		{
			if(src == end-1)
				break;

			src++;
			if(*src == SLIP_END_REPLACE)
				*ptr++ = SLIP_END;
			else if(*src == SLIP_ESC_REPLACE)
				*ptr++ = SLIP_ESC;
			src++;
		}
		else if(*src == SLIP_END)
		{
			src++;

			*size = whole ? ptr - dst : 0;
			return src - dst;
		}
		else
		{
			*ptr++ = *src++;
		}
	}

	*size = 0;
	return 0;
}

static LV2_OSC_Enum
652
_lv2_osc_stream_run_udp(LV2_OSC_Stream *stream)
653 654 655
{
	LV2_OSC_Enum ev = LV2_OSC_NONE;

656 657
	// send everything
	if(stream->peer.len) // has a peer
658
	{
659 660
		const uint8_t *buf;
		size_t tosend;
661

662
		while( (buf = stream->driv->read_req(stream->data, &tosend)) )
663
		{
664 665
			const ssize_t sent = sendto(stream->sock, buf, tosend, 0,
				&stream->peer.in, stream->peer.len);
666

667
			if(sent == -1)
668
			{
669 670 671 672 673
				if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
				{
					// full queue
					break;
				}
674

675 676
				fprintf(stderr, "%s: sendto: %s\n", __func__, strerror(errno));
				break;
677
			}
678
			else if(sent != (ssize_t)tosend)
679
			{
680 681
				fprintf(stderr, "%s: only sent %zi of %zu bytes", __func__, sent, tosend);
				break;
682 683
			}

684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
			stream->driv->read_adv(stream->data);
			ev |= LV2_OSC_SEND;
		}
	}

	// recv everything
	{
		uint8_t *buf;
		size_t max_len;

		while( (buf = stream->driv->write_req(stream->data,
			LV2_OSC_STREAM_REQBUF, &max_len)) )
		{
			struct sockaddr in;
			socklen_t in_len = sizeof(in);

			const ssize_t recvd = recvfrom(stream->sock, buf, max_len, 0,
				&in, &in_len);

			if(recvd == -1)
704
			{
705 706 707 708 709
				if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
				{
					// empty queue
					break;
				}
710

711 712 713 714
				fprintf(stderr, "%s: recv: %s\n", __func__, strerror(errno));
				break;
			}
			else if(recvd == 0)
715
			{
716 717
				// peer has shut down
				break;
718 719
			}

720 721 722 723 724
			stream->peer.len = in_len;
			stream->peer.in = in;

			stream->driv->write_adv(stream->data, recvd);
			ev |= LV2_OSC_RECV;
725 726 727
		}
	}

728 729 730 731 732 733 734 735 736 737
	return ev;
}

static LV2_OSC_Enum
_lv2_osc_stream_run_tcp(LV2_OSC_Stream *stream)
{
	LV2_OSC_Enum ev = LV2_OSC_NONE;

	// handle connections
	if(!stream->connected) // no peer
738
	{
739
		if(stream->server)
740
		{
741 742
			stream->peer.len = sizeof(stream->peer.in);
			stream->fd = accept(stream->sock, &stream->peer.in, &stream->peer.len);
743

744
			if(stream->fd >= 0)
745
			{
746 747 748
				const int flag = 1;
				const int sendbuff = LV2_OSC_STREAM_SNDBUF;
				const int recvbuff = LV2_OSC_STREAM_RCVBUF;
749

750
				if(fcntl(stream->fd, F_SETFL, O_NONBLOCK) == -1)
751
				{
752 753
					fprintf(stderr, "%s: fcntl failed\n", __func__);
				}
754

755 756 757 758
				if(setsockopt(stream->fd, stream->protocol,
					TCP_NODELAY, &flag, sizeof(int)) != 0)
				{
					fprintf(stderr, "%s: setsockopt failed\n", __func__);
759
				}
760 761 762

				if(setsockopt(stream->sock, SOL_SOCKET,
					SO_KEEPALIVE, &flag, sizeof(int)) != 0)
763
				{
764
					fprintf(stderr, "%s: setsockopt failed\n", __func__);
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
				if(setsockopt(stream->fd, SOL_SOCKET,
					SO_SNDBUF, &sendbuff, sizeof(int))== -1)
				{
					fprintf(stderr, "%s: setsockopt failed\n", __func__);
				}

				if(setsockopt(stream->fd, SOL_SOCKET,
					SO_RCVBUF, &recvbuff, sizeof(int))== -1)
				{
					fprintf(stderr, "%s: setsockopt failed\n", __func__);
				}

				stream->connected = true;
				//fprintf(stderr, "%s: orderly accept\n", __func__);
				//FIXME ev |=
			}
		}
		else
		{
			if(connect(stream->sock, &stream->peer.in, stream->peer.len) == 0)
			{
				stream->connected = true;
				//fprintf(stderr, "%s: orderly (re)connect\n", __func__);
				//FIXME ev |=
791 792 793
			}
		}
	}
794 795 796

	// send everything
	if(stream->connected)
797 798 799 800 801
	{
		const int fd = stream->server
			? stream->fd
			: stream->sock;

802
		if(fd >= 0)
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
		{
			const uint8_t *buf;
			size_t tosend;

			while( (buf = stream->driv->read_req(stream->data, &tosend)) )
			{
				if(stream->slip) // SLIP framed
				{
					if(tosend <= sizeof(stream->tx_buf)) // check if there is enough memory
					{
						memcpy(stream->tx_buf, buf, tosend);
						tosend = lv2_osc_slip_encode_inline(stream->tx_buf, tosend);
					}
					else
					{
						tosend = 0;
					}
				}
				else // uint32_t prefix frames
				{
					const size_t nsize = tosend + sizeof(uint32_t);

					if(nsize <= sizeof(stream->tx_buf)) // check if there is enough memory
					{
						const uint32_t prefix = htonl(tosend);

						memcpy(stream->tx_buf, &prefix, sizeof(uint32_t));
						memcpy(stream->tx_buf + sizeof(uint32_t), buf, tosend);
						tosend = nsize;
					}
					else
					{
						tosend = 0;
					}
				}

				const ssize_t sent = tosend
					? send(fd, stream->tx_buf, tosend, 0)
					: 0;

				if(sent == -1)
				{
					if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
					{
847
						// empty queue
848 849
						break;
					}
850
					else if(stream->server)
851
					{
852 853 854
						// peer has shut down
						close(stream->fd);
						stream->fd = -1;
855 856
					}

857
					stream->connected = false;
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
					fprintf(stderr, "%s: send: %s\n", __func__, strerror(errno));
					break;
				}
				else if(sent != (ssize_t)tosend)
				{
					fprintf(stderr, "%s: only sent %zi of %zu bytes", __func__, sent, tosend);
					break;
				}

				stream->driv->read_adv(stream->data);
				ev |= LV2_OSC_SEND;
			}
		}
	}

	// recv everything
874
	if(stream->connected)
875 876 877 878 879
	{
		const int fd = stream->server
			? stream->fd
			: stream->sock;

880
		if(fd >= 0)
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
		{
			if(stream->slip) // SLIP framed
			{
				while(true)
				{
					ssize_t recvd = recv(fd, stream->rx_buf + stream->rx_off,
						sizeof(stream->rx_buf) - stream->rx_off, 0);

					if(recvd == -1)
					{
						if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
						{
							// empty queue
							break;
						}
896
						else if(stream->server)
897
						{
898 899 900
							// peer has shut down
							close(stream->fd);
							stream->fd = -1;
901 902
						}

903 904
						stream->connected = false;
						fprintf(stderr, "%s: recv(slip): %s\n", __func__, strerror(errno));
905 906
						break;
					}
907
					else if(recvd == 0)
908
					{
909 910 911 912 913 914 915 916 917
						if(stream->server)
						{
							// peer has shut down
							close(stream->fd);
							stream->fd = -1;
						}

						stream->connected = false;
						//fprintf(stderr, "%s: recv(slip): %s\n", __func__, "orderly shutdown");
918 919 920 921 922 923 924 925 926
						break;
					}

					uint8_t *ptr = stream->rx_buf;
					recvd += stream->rx_off;

					while(recvd > 0)
					{
						size_t size;
927
						size_t parsed = lv2_osc_slip_decode_inline(ptr, recvd, &size);
928 929 930

						if(size) // dispatch
						{
931
							uint8_t *buf;
932 933 934 935 936 937 938 939 940 941

							if( (buf = stream->driv->write_req(stream->data, size, NULL)) )
							{
								memcpy(buf, ptr, size);

								stream->driv->write_adv(stream->data, size);
								ev |= LV2_OSC_RECV;
							}
							else
							{
942 943
								parsed = 0;
								fprintf(stderr, "%s: write buffer overflow\n", __func__);
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
							}
						}

						if(parsed)
						{
							ptr += parsed;
							recvd -= parsed;
						}
						else
						{
							break;
						}
					}

					if(recvd > 0) // is there remaining chunk for next call?
					{
						memmove(stream->rx_buf, ptr, recvd);
						stream->rx_off = recvd;
					}
					else
					{
						stream->rx_off = 0;
					}

					break;
				}
			}
			else // uint32_t prefix frames
			{
				uint8_t *buf;
				
				while( (buf = stream->driv->write_req(stream->data,
					LV2_OSC_STREAM_REQBUF, NULL)) )
				{
					uint32_t prefix;

					ssize_t recvd = recv(fd, &prefix, sizeof(uint32_t), 0);
					if(recvd == sizeof(uint32_t))
					{
						prefix = ntohl(prefix); //FIXME check prefix <= max_len
						recvd = recv(fd, buf, prefix, 0);
					}
986
					else if(recvd == -1)
987 988 989 990 991 992
					{
						if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
						{
							// empty queue
							break;
						}
993
						else if(stream->server)
994
						{
995 996 997
							// peer has shut down
							close(stream->fd);
							stream->fd = -1;
998 999
						}

1000 1001
						stream->connected = false;
						fprintf(stderr, "%s: recv(prefix): %s\n", __func__, strerror(errno));
1002 1003
						break;
					}
1004
					else if(recvd == 0)
1005
					{
1006 1007 1008 1009 1010 1011 1012 1013 1014
						if(stream->server)
						{
							// peer has shut down
							close(stream->fd);
							stream->fd = -1;
						}

						stream->connected = false;
						//fprintf(stderr, "%s: recv(prefix): %s\n", __func__, "orderly shutdown");
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
						break;
					}

					stream->driv->write_adv(stream->data, recvd);
					ev |= LV2_OSC_RECV;
				}
			}
		}
	}

	return ev;
}

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
static LV2_OSC_Enum
lv2_osc_stream_run(LV2_OSC_Stream *stream)
{
	LV2_OSC_Enum ev = LV2_OSC_NONE;

	switch(stream->socket_type)
	{
		case SOCK_DGRAM:
		{
			ev |= _lv2_osc_stream_run_udp(stream);
		} break;
		case SOCK_STREAM:
		{
			ev |= _lv2_osc_stream_run_tcp(stream);
		} break;
	}

	return ev;
}

1048 1049 1050 1051 1052 1053
static int
lv2_osc_stream_deinit(LV2_OSC_Stream *stream)
{
	if(stream->fd >= 0)
	{
		close(stream->fd);
1054
		stream->fd = -1;
1055 1056 1057 1058 1059
	}

	if(stream->sock >= 0)
	{
		close(stream->sock);
1060
		stream->sock = -1;
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	}

	return 0;
}

#ifdef __cplusplus
} // extern "C"
#endif

#endif // LV2_OSC_STREAM_H