1 /*
2  * Copyright (c) 2015-2016 Hanspeter Portner (dev@open-music-kontrollers.ch)
3  *
4  * This is free software: you can redistribute it and/or modify
5  * it under the terms of the Artistic License 2.0 as published by
6  * The Perl Foundation.
7  *
8  * This source is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * Artistic License 2.0 for more details.
12  *
13  * You should have received a copy of the Artistic License 2.0
14  * along the source as a COPYING file. If not, obtain it from
15  * http://www.perlfoundation.org/artistic_license_2_0.
16  */
17 
18 #ifndef LV2_OSC_STREAM_H
19 #define LV2_OSC_STREAM_H
20 
21 #include <stdbool.h>
22 #include <string.h>
23 #if !defined(_WIN32)
24 #	include <arpa/inet.h>
25 #	include <sys/socket.h>
26 #	include <net/if.h>
27 #	include <netinet/tcp.h>
28 #	include <netinet/in.h>
29 #	include <netdb.h>
30 #	include <termios.h>
31 #	include <limits.h>
32 #endif
33 #include <sys/types.h>
34 #include <fcntl.h>
35 #include <errno.h>
36 #include <unistd.h>
37 
38 #include <osc.lv2/osc.h>
39 
40 #if !defined(LV2_OSC_STREAM_SNDBUF)
41 #	define LV2_OSC_STREAM_SNDBUF 0x100000 // 1 M
42 #endif
43 
44 #if !defined(LV2_OSC_STREAM_RCVBUF)
45 #	define LV2_OSC_STREAM_RCVBUF 0x100000 // 1 M
46 #endif
47 
48 #if !defined(LV2_OSC_STREAM_REQBUF)
49 #	define LV2_OSC_STREAM_REQBUF 1024
50 #endif
51 
52 #ifdef __cplusplus
53 extern "C" {
54 #endif
55 
56 typedef void *
57 (*LV2_OSC_Stream_Write_Request)(void *data, size_t minimum, size_t *maximum);
58 
59 typedef void
60 (*LV2_OSC_Stream_Write_Advance)(void *data, size_t written);
61 
62 typedef const void *
63 (*LV2_OSC_Stream_Read_Request)(void *data, size_t *toread);
64 
65 typedef void
66 (*LV2_OSC_Stream_Read_Advance)(void *data);
67 
68 typedef struct _LV2_OSC_Address LV2_OSC_Address;
69 typedef struct _LV2_OSC_Driver LV2_OSC_Driver;
70 typedef struct _LV2_OSC_Stream LV2_OSC_Stream;
71 
72 struct _LV2_OSC_Address {
73 	socklen_t len;
74 	union {
75 		struct sockaddr_in in4;
76 		struct sockaddr_in6 in6;
77 	};
78 };
79 
80 struct _LV2_OSC_Driver {
81 	LV2_OSC_Stream_Write_Request write_req;
82 	LV2_OSC_Stream_Write_Advance write_adv;
83 	LV2_OSC_Stream_Read_Request read_req;
84 	LV2_OSC_Stream_Read_Advance read_adv;
85 };
86 
87 struct _LV2_OSC_Stream {
88 	int socket_family;
89 	int socket_type;
90 	int protocol;
91 	bool server;
92 	bool slip;
93 	bool serial;
94 	bool connected;
95 	int sock;
96 	int fd;
97 	LV2_OSC_Address self;
98 	LV2_OSC_Address peer;
99 	const LV2_OSC_Driver *driv;
100 	void *data;
101 	uint8_t tx_buf [0x4000];
102 	uint8_t rx_buf [0x4000];
103 	size_t rx_off;
104 	char url [PATH_MAX];
105 };
106 
107 typedef enum _LV2_OSC_Enum {
108 	LV2_OSC_NONE = 0x000000,
109 
110 	LV2_OSC_SEND = 0x800000,
111 	LV2_OSC_RECV = 0x400000,
112 	LV2_OSC_CONN = 0x200000,
113 
114 	LV2_OSC_ERR  = 0x00ffff
115 } LV2_OSC_Enum;
116 
117 static const char *udp_prefix = "osc.udp://";
118 static const char *tcp_prefix = "osc.tcp://";
119 static const char *tcp_slip_prefix = "osc.slip.tcp://";
120 static const char *tcp_prefix_prefix = "osc.prefix.tcp://";
121 static const char *ser_prefix = "osc.serial://";
122 //FIXME serial
123 
124 
125 static int
_lv2_osc_stream_interface_attribs(int fd,int speed)126 _lv2_osc_stream_interface_attribs(int fd, int speed)
127 {
128 	struct termios tty;
129 
130 	if(tcgetattr(fd, &tty) < 0)
131 	{
132 		return -1;
133 	}
134 
135 	cfsetospeed(&tty, (speed_t)speed);
136 	cfsetispeed(&tty, (speed_t)speed);
137 
138 	tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
139 	tty.c_cflag &= ~CSIZE;
140 	tty.c_cflag |= CS8;         /* 8-bit characters */
141 	tty.c_cflag &= ~PARENB;     /* no parity bit */
142 	tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
143 	tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */
144 
145 	/* setup for non-canonical mode */
146 	tty.c_iflag &= ~(IGNCR | ONLCR | IXON);
147 	tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
148 	tty.c_oflag &= ~OPOST;
149 
150 	/* fetch bytes as they become available */
151 	tty.c_cc[VMIN] = 0;
152 	tty.c_cc[VTIME] = 0;
153 
154 	if(tcsetattr(fd, TCSANOW, &tty) != 0)
155 	{
156 		return -1;
157 	}
158 
159 	return 0;
160 }
161 
162 #define LV2_OSC_STREAM_ERRNO(EV, ERRNO) ( (EV & (~LV2_OSC_ERR)) | (ERRNO) )
163 
164 static void
_close_socket(int * fd)165 _close_socket(int *fd)
166 {
167 	if(fd)
168 	{
169 		if(*fd >= 0)
170 		{
171 			close(*fd);
172 		}
173 
174 		*fd = -1;
175 	}
176 }
177 
178 static int
lv2_osc_stream_deinit(LV2_OSC_Stream * stream)179 lv2_osc_stream_deinit(LV2_OSC_Stream *stream)
180 {
181 	_close_socket(&stream->fd);
182 	_close_socket(&stream->sock);
183 
184 	return 0;
185 }
186 
187 static int
_lv2_osc_stream_reinit(LV2_OSC_Stream * stream)188 _lv2_osc_stream_reinit(LV2_OSC_Stream *stream)
189 {
190 	LV2_OSC_Enum ev = LV2_OSC_NONE;
191 	lv2_osc_stream_deinit(stream);
192 
193 	char *dup = strdup(stream->url);
194 	if(!dup)
195 	{
196 		ev = LV2_OSC_STREAM_ERRNO(ev, ENOMEM);
197 		goto fail;
198 	}
199 
200 	char *ptr = dup;
201 	char *tmp;
202 
203 	if(strncmp(ptr, udp_prefix, strlen(udp_prefix)) == 0)
204 	{
205 		stream->slip = false;
206 		stream->socket_family = AF_INET;
207 		stream->socket_type = SOCK_DGRAM;
208 		stream->protocol = IPPROTO_UDP;
209 		ptr += strlen(udp_prefix);
210 	}
211 	else if(strncmp(ptr, tcp_prefix, strlen(tcp_prefix)) == 0)
212 	{
213 		stream->slip = true;
214 		stream->socket_family = AF_INET;
215 		stream->socket_type = SOCK_STREAM;
216 		stream->protocol = IPPROTO_TCP;
217 		ptr += strlen(tcp_prefix);
218 	}
219 	else if(strncmp(ptr, tcp_slip_prefix, strlen(tcp_slip_prefix)) == 0)
220 	{
221 		stream->slip = true;
222 		stream->socket_family = AF_INET;
223 		stream->socket_type = SOCK_STREAM;
224 		stream->protocol = IPPROTO_TCP;
225 		ptr += strlen(tcp_slip_prefix);
226 	}
227 	else if(strncmp(ptr, tcp_prefix_prefix, strlen(tcp_prefix_prefix)) == 0)
228 	{
229 		stream->slip = false;
230 		stream->socket_family = AF_INET;
231 		stream->socket_type = SOCK_STREAM;
232 		stream->protocol = IPPROTO_TCP;
233 		ptr += strlen(tcp_prefix_prefix);
234 	}
235 	else if(strncmp(ptr, ser_prefix, strlen(ser_prefix)) == 0)
236 	{
237 		stream->slip = true;
238 		stream->serial = true;
239 		ptr += strlen(ser_prefix);
240 	}
241 	else
242 	{
243 		ev = LV2_OSC_STREAM_ERRNO(ev, ENOPROTOOPT);
244 		goto fail;
245 	}
246 
247 	if(ptr[0] == '\0')
248 	{
249 		ev = LV2_OSC_STREAM_ERRNO(ev, EDESTADDRREQ);
250 		goto fail;
251 	}
252 
253 	if(stream->serial)
254 	{
255 		stream->sock = open(ptr, O_RDWR | O_NOCTTY | O_NDELAY);
256 		if(stream->sock < 0)
257 		{
258 			ev = LV2_OSC_STREAM_ERRNO(ev, errno);
259 			goto fail;
260 		}
261 
262 		if(fcntl(stream->sock, F_SETFL, FNDELAY) == -1) //FIXME
263 		{
264 			ev = LV2_OSC_STREAM_ERRNO(ev, errno);
265 			goto fail;
266 		}
267 
268 		if(_lv2_osc_stream_interface_attribs(stream->sock, B115200) == -1)
269 		{
270 			ev = LV2_OSC_STREAM_ERRNO(ev, errno);
271 			goto fail;
272 		}
273 
274 		stream->connected = true;
275 	}
276 	else // !stream->serial
277 	{
278 		const char *node = NULL;
279 		const char *iface = NULL;
280 		const char *service = NULL;
281 
282 		// optional IPv6
283 		if(ptr[0] == '[')
284 		{
285 			stream->socket_family = AF_INET6;
286 			++ptr;
287 		}
288 
289 		node = ptr;
290 
291 		// optional IPv6
292 		if( (tmp = strchr(ptr, '%')) )
293 		{
294 			if(stream->socket_family != AF_INET6)
295 			{
296 				ev = LV2_OSC_STREAM_ERRNO(ev, EPROTOTYPE);
297 				goto fail;
298 			}
299 
300 			ptr = tmp;
301 			ptr[0] = '\0';
302 			iface = ++ptr;
303 		}
304 
305 		// optional IPv6
306 		if( (tmp = strchr(ptr, ']')) )
307 		if(ptr)
308 		{
309 			if(stream->socket_family != AF_INET6)
310 			{
311 				ev = LV2_OSC_STREAM_ERRNO(ev, EDESTADDRREQ);
312 				goto fail;
313 			}
314 
315 			ptr = tmp;
316 			ptr[0] = '\0';
317 			++ptr;
318 		}
319 
320 		// mandatory IPv4/6
321 		ptr = strchr(ptr, ':');
322 		if(!ptr)
323 		{
324 			ev = LV2_OSC_STREAM_ERRNO(ev, EDESTADDRREQ);
325 			goto fail;
326 		}
327 
328 		ptr[0] = '\0';
329 
330 		service = ++ptr;
331 
332 		if(strlen(node) == 0)
333 		{
334 			node = NULL;
335 			stream->server = true;
336 		}
337 
338 		stream->sock = socket(stream->socket_family, stream->socket_type,
339 			stream->protocol);
340 
341 		if(stream->sock < 0)
342 		{
343 			ev = LV2_OSC_STREAM_ERRNO(ev, errno);
344 			goto fail;
345 		}
346 
347 		if(fcntl(stream->sock, F_SETFL, O_NONBLOCK) == -1)
348 		{
349 			ev = LV2_OSC_STREAM_ERRNO(ev, errno);
350 			goto fail;
351 		}
352 
353 		const int sendbuff = LV2_OSC_STREAM_SNDBUF;
354 		const int recvbuff = LV2_OSC_STREAM_RCVBUF;
355 		const int reuseaddr = 1;
356 
357 		if(setsockopt(stream->sock, SOL_SOCKET,
358 			SO_SNDBUF, &sendbuff, sizeof(sendbuff)) == -1)
359 		{
360 			ev = LV2_OSC_STREAM_ERRNO(ev, errno);
361 			goto fail;
362 		}
363 
364 		if(setsockopt(stream->sock, SOL_SOCKET,
365 			SO_RCVBUF, &recvbuff, sizeof(recvbuff)) == -1)
366 		{
367 			ev = LV2_OSC_STREAM_ERRNO(ev, errno);
368 			goto fail;
369 		}
370 
371 		if(setsockopt(stream->sock, SOL_SOCKET,
372 			SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)) == -1)
373 		{
374 			ev = LV2_OSC_STREAM_ERRNO(ev, errno);
375 			goto fail;
376 		}
377 
378 		if(stream->socket_family == AF_INET) // IPv4
379 		{
380 			if(stream->server)
381 			{
382 				// resolve self address
383 				struct addrinfo hints;
384 				memset(&hints, 0x0, sizeof(struct addrinfo));
385 				hints.ai_family = stream->socket_family;
386 				hints.ai_socktype = stream->socket_type;
387 				hints.ai_protocol = stream->protocol;
388 
389 				struct addrinfo *res;
390 				if(getaddrinfo(node, service, &hints, &res) != 0)
391 				{
392 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
393 					goto fail;
394 				}
395 				if(res->ai_addrlen != sizeof(stream->peer.in4))
396 				{
397 					ev = LV2_OSC_STREAM_ERRNO(ev, EPROTOTYPE);
398 					goto fail;
399 				}
400 
401 				stream->self.len = res->ai_addrlen;
402 				memcpy(&stream->self.in4, res->ai_addr, res->ai_addrlen);
403 				stream->self.in4.sin_addr.s_addr = htonl(INADDR_ANY);
404 
405 				freeaddrinfo(res);
406 
407 				if(bind(stream->sock, (struct sockaddr *)&stream->self.in4,
408 					stream->self.len) != 0)
409 				{
410 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
411 					goto fail;
412 				}
413 			}
414 			else // client
415 			{
416 				stream->self.len = sizeof(stream->self.in4);
417 				stream->self.in4.sin_family = stream->socket_family;
418 				stream->self.in4.sin_port = htons(0);
419 				stream->self.in4.sin_addr.s_addr = htonl(INADDR_ANY);
420 
421 				if(bind(stream->sock, (struct sockaddr *)&stream->self.in4,
422 					stream->self.len) != 0)
423 				{
424 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
425 					goto fail;
426 				}
427 
428 				// resolve peer address
429 				struct addrinfo hints;
430 				memset(&hints, 0x0, sizeof(struct addrinfo));
431 				hints.ai_family = stream->socket_family;
432 				hints.ai_socktype = stream->socket_type;
433 				hints.ai_protocol = stream->protocol;
434 
435 				struct addrinfo *res;
436 				if(getaddrinfo(node, service, &hints, &res) != 0)
437 				{
438 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
439 					goto fail;
440 				}
441 				if(res->ai_addrlen != sizeof(stream->peer.in4))
442 				{
443 					ev = LV2_OSC_STREAM_ERRNO(ev, EPROTOTYPE);
444 					goto fail;
445 				}
446 
447 				stream->peer.len = res->ai_addrlen;
448 				memcpy(&stream->peer.in4, res->ai_addr, res->ai_addrlen);
449 
450 				freeaddrinfo(res);
451 			}
452 
453 			if(stream->socket_type == SOCK_DGRAM)
454 			{
455 				const int broadcast = 1;
456 
457 				if(setsockopt(stream->sock, SOL_SOCKET, SO_BROADCAST,
458 					&broadcast, sizeof(broadcast)) != 0)
459 				{
460 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
461 					goto fail;
462 				}
463 
464 				//FIXME handle multicast
465 			}
466 			else if(stream->socket_type == SOCK_STREAM)
467 			{
468 				const int flag = 1;
469 
470 				if(setsockopt(stream->sock, stream->protocol,
471 					TCP_NODELAY, &flag, sizeof(flag)) != 0)
472 				{
473 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
474 					goto fail;
475 				}
476 
477 				if(setsockopt(stream->sock, SOL_SOCKET,
478 					SO_KEEPALIVE, &flag, sizeof(flag)) != 0)
479 				{
480 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
481 					goto fail;
482 				}
483 
484 				if(stream->server)
485 				{
486 					if(listen(stream->sock, 1) != 0)
487 					{
488 						ev = LV2_OSC_STREAM_ERRNO(ev, errno);
489 						goto fail;
490 					}
491 				}
492 				else // client
493 				{
494 					if(connect(stream->sock, (struct sockaddr *)&stream->peer.in4,
495 						stream->peer.len) == 0)
496 					{
497 						stream->connected = true;
498 					}
499 				}
500 			}
501 			else
502 			{
503 				ev = LV2_OSC_STREAM_ERRNO(ev, EPROTOTYPE);
504 				goto fail;
505 			}
506 		}
507 		else if(stream->socket_family == AF_INET6) // IPv6
508 		{
509 			if(stream->server)
510 			{
511 				// resolve self address
512 				struct addrinfo hints;
513 				memset(&hints, 0x0, sizeof(struct addrinfo));
514 				hints.ai_family = stream->socket_family;
515 				hints.ai_socktype = stream->socket_type;
516 				hints.ai_protocol = stream->protocol;
517 
518 				struct addrinfo *res;
519 				if(getaddrinfo(node, service, &hints, &res) != 0)
520 				{
521 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
522 					goto fail;
523 				}
524 				if(res->ai_addrlen != sizeof(stream->peer.in6))
525 				{
526 					ev = LV2_OSC_STREAM_ERRNO(ev, EPROTOTYPE);
527 					goto fail;
528 				}
529 
530 				stream->self.len = res->ai_addrlen;
531 				memcpy(&stream->self.in6, res->ai_addr, res->ai_addrlen);
532 				stream->self.in6.sin6_addr = in6addr_any;
533 				if(iface)
534 				{
535 					stream->self.in6.sin6_scope_id = if_nametoindex(iface);
536 				}
537 
538 				freeaddrinfo(res);
539 
540 				if(bind(stream->sock, (struct sockaddr *)&stream->self.in6,
541 					stream->self.len) != 0)
542 				{
543 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
544 					goto fail;
545 				}
546 			}
547 			else // client
548 			{
549 				stream->self.len = sizeof(stream->self.in6);
550 				stream->self.in6.sin6_family = stream->socket_family;
551 				stream->self.in6.sin6_port = htons(0);
552 				stream->self.in6.sin6_addr = in6addr_any;
553 				if(iface)
554 				{
555 					stream->self.in6.sin6_scope_id = if_nametoindex(iface);
556 				}
557 
558 				if(bind(stream->sock, (struct sockaddr *)&stream->self.in6,
559 					stream->self.len) != 0)
560 				{
561 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
562 					goto fail;
563 				}
564 
565 				// resolve peer address
566 				struct addrinfo hints;
567 				memset(&hints, 0x0, sizeof(struct addrinfo));
568 				hints.ai_family = stream->socket_family;
569 				hints.ai_socktype = stream->socket_type;
570 				hints.ai_protocol = stream->protocol;
571 
572 				struct addrinfo *res;
573 				if(getaddrinfo(node, service, &hints, &res) != 0)
574 				{
575 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
576 					goto fail;
577 				}
578 				if(res->ai_addrlen != sizeof(stream->peer.in6))
579 				{
580 					ev = LV2_OSC_STREAM_ERRNO(ev, EPROTOTYPE);
581 					goto fail;
582 				}
583 
584 				stream->peer.len = res->ai_addrlen;
585 				memcpy(&stream->peer.in6, res->ai_addr, res->ai_addrlen);
586 
587 				if(iface)
588 				{
589 					stream->peer.in6.sin6_scope_id = if_nametoindex(iface);
590 				}
591 
592 				freeaddrinfo(res);
593 			}
594 
595 			if(stream->socket_type == SOCK_DGRAM)
596 			{
597 				// nothing to do
598 			}
599 			else if(stream->socket_type == SOCK_STREAM)
600 			{
601 				const int flag = 1;
602 
603 				if(setsockopt(stream->sock, stream->protocol,
604 					TCP_NODELAY, &flag, sizeof(flag)) != 0)
605 				{
606 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
607 					goto fail;
608 				}
609 
610 				if(setsockopt(stream->sock, SOL_SOCKET,
611 					SO_KEEPALIVE, &flag, sizeof(flag)) != 0)
612 				{
613 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
614 					goto fail;
615 				}
616 
617 				if(stream->server)
618 				{
619 					if(listen(stream->sock, 1) != 0)
620 					{
621 						ev = LV2_OSC_STREAM_ERRNO(ev, errno);
622 						goto fail;
623 					}
624 				}
625 				else // client
626 				{
627 					if(connect(stream->sock, (struct sockaddr *)&stream->peer.in6,
628 						stream->peer.len) == 0)
629 					{
630 						stream->connected = true;
631 					}
632 				}
633 			}
634 			else
635 			{
636 				ev = LV2_OSC_STREAM_ERRNO(ev, EPROTOTYPE);
637 				goto fail;
638 			}
639 		}
640 		else
641 		{
642 			ev = LV2_OSC_STREAM_ERRNO(ev, EPROTOTYPE);
643 			goto fail;
644 		}
645 	}
646 
647 	free(dup);
648 
649 	return ev;
650 
651 fail:
652 	if(dup)
653 	{
654 		free(dup);
655 	}
656 
657 	_close_socket(&stream->sock);
658 
659 	return ev;
660 }
661 
662 static int
lv2_osc_stream_init(LV2_OSC_Stream * stream,const char * url,const LV2_OSC_Driver * driv,void * data)663 lv2_osc_stream_init(LV2_OSC_Stream *stream, const char *url,
664 	const LV2_OSC_Driver *driv, void *data)
665 {
666 	memset(stream, 0x0, sizeof(LV2_OSC_Stream));
667 
668 	strncpy(stream->url, url, sizeof(stream->url));
669 	stream->driv = driv;
670 	stream->data = data;
671 	stream->sock = -1;
672 	stream->fd = -1;
673 
674 	return _lv2_osc_stream_reinit(stream);
675 }
676 
677 #define SLIP_END					0300	// 0xC0, 192, indicates end of packet
678 #define SLIP_ESC					0333	// 0xDB, 219, indicates byte stuffing
679 #define SLIP_END_REPLACE	0334	// 0xDC, 220, ESC ESC_END means END data byte
680 #define SLIP_ESC_REPLACE	0335	// 0xDD, 221, ESC ESC_ESC means ESC data byte
681 
682 // SLIP encoding
683 static size_t
lv2_osc_slip_encode_inline(uint8_t * dst,size_t len)684 lv2_osc_slip_encode_inline(uint8_t *dst, size_t len)
685 {
686 	if(len == 0)
687 		return 0;
688 
689 	const uint8_t *end = dst + len;
690 
691 	// estimate new size
692 	size_t size = 2; // double ended SLIP
693 	for(const uint8_t *from=dst; from<end; from++, size++)
694 	{
695 		if( (*from == SLIP_END) || (*from == SLIP_ESC))
696 			size ++;
697 	}
698 
699 	// fast track if no escaping needed
700 	if(size == len + 2)
701 	{
702 		memmove(dst+1, dst, len);
703 		dst[0] = SLIP_END;
704 		dst[size-1] = SLIP_END;
705 
706 		return size;
707 	}
708 
709 	// slow track if some escaping needed
710 	uint8_t *to = dst + size - 1;
711 	*to-- = SLIP_END;
712 	for(const uint8_t *from=end-1; from>=dst; from--)
713 	{
714 		if(*from == SLIP_END)
715 		{
716 			*to-- = SLIP_END_REPLACE;
717 			*to-- = SLIP_ESC;
718 		}
719 		else if(*from == SLIP_ESC)
720 		{
721 			*to-- = SLIP_ESC_REPLACE;
722 			*to-- = SLIP_ESC;
723 		}
724 		else
725 			*to-- = *from;
726 	}
727 	*to-- = SLIP_END;
728 
729 	return size;
730 }
731 
732 // SLIP decoding
733 static size_t
lv2_osc_slip_decode_inline(uint8_t * dst,size_t len,size_t * size)734 lv2_osc_slip_decode_inline(uint8_t *dst, size_t len, size_t *size)
735 {
736 	const uint8_t *src = dst;
737 	const uint8_t *end = dst + len;
738 	uint8_t *ptr = dst;
739 
740 	bool whole = false;
741 
742 	if( (src < end) && (*src == SLIP_END) )
743 	{
744 		 whole = true;
745 		 src++;
746 	}
747 
748 	while(src < end)
749 	{
750 		if(*src == SLIP_ESC)
751 		{
752 			if(src == end-1)
753 				break;
754 
755 			src++;
756 			if(*src == SLIP_END_REPLACE)
757 				*ptr++ = SLIP_END;
758 			else if(*src == SLIP_ESC_REPLACE)
759 				*ptr++ = SLIP_ESC;
760 			src++;
761 		}
762 		else if(*src == SLIP_END)
763 		{
764 			src++;
765 
766 			*size = whole ? ptr - dst : 0;
767 			return src - dst;
768 		}
769 		else
770 		{
771 			*ptr++ = *src++;
772 		}
773 	}
774 
775 	*size = 0;
776 	return 0;
777 }
778 
779 static LV2_OSC_Enum
_lv2_osc_stream_run_udp(LV2_OSC_Stream * stream)780 _lv2_osc_stream_run_udp(LV2_OSC_Stream *stream)
781 {
782 	LV2_OSC_Enum ev = LV2_OSC_NONE;
783 
784 	// send everything
785 	if(stream->peer.len) // has a peer
786 	{
787 		const uint8_t *buf;
788 		size_t tosend;
789 
790 		while( (buf = stream->driv->read_req(stream->data, &tosend)) )
791 		{
792 			const ssize_t sent = sendto(stream->sock, buf, tosend, 0,
793 				(struct sockaddr *)&stream->peer.in6, stream->peer.len);
794 
795 			if(sent == -1)
796 			{
797 				if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
798 				{
799 					// full queue
800 					break;
801 				}
802 
803 				ev = LV2_OSC_STREAM_ERRNO(ev, errno);
804 				break;
805 			}
806 			else if(sent != (ssize_t)tosend)
807 			{
808 				ev = LV2_OSC_STREAM_ERRNO(ev, EIO);
809 				break;
810 			}
811 
812 			stream->driv->read_adv(stream->data);
813 			ev |= LV2_OSC_SEND;
814 		}
815 	}
816 
817 	// recv everything
818 	{
819 		uint8_t *buf;
820 		size_t max_len;
821 
822 		while( (buf = stream->driv->write_req(stream->data,
823 			LV2_OSC_STREAM_REQBUF, &max_len)) )
824 		{
825 			struct sockaddr_in6 in;
826 			socklen_t in_len = sizeof(in);
827 
828 			memset(&in, 0, in_len);
829 			const ssize_t recvd = recvfrom(stream->sock, buf, max_len, 0,
830 				(struct sockaddr *)&in, &in_len);
831 
832 			if(recvd == -1)
833 			{
834 				if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
835 				{
836 					// empty queue
837 					break;
838 				}
839 
840 				ev = LV2_OSC_STREAM_ERRNO(ev, errno);
841 				break;
842 			}
843 			else if(recvd == 0)
844 			{
845 				// peer has shut down
846 				break;
847 			}
848 
849 			stream->peer.len = in_len;
850 			memcpy(&stream->peer.in6, &in, in_len);
851 
852 			stream->driv->write_adv(stream->data, recvd);
853 			ev |= LV2_OSC_RECV;
854 		}
855 	}
856 
857 	return ev;
858 }
859 
860 static LV2_OSC_Enum
_lv2_osc_stream_run_tcp(LV2_OSC_Stream * stream)861 _lv2_osc_stream_run_tcp(LV2_OSC_Stream *stream)
862 {
863 	LV2_OSC_Enum ev = LV2_OSC_NONE;
864 
865 	// handle connections
866 	if(!stream->connected) // no peer
867 	{
868 		if(stream->server)
869 		{
870 			stream->peer.len = sizeof(stream->peer.in6);
871 			stream->fd = accept(stream->sock, (struct sockaddr *)&stream->peer.in6,
872 				&stream->peer.len);
873 
874 			if(stream->fd >= 0)
875 			{
876 				const int flag = 1;
877 				const int sendbuff = LV2_OSC_STREAM_SNDBUF;
878 				const int recvbuff = LV2_OSC_STREAM_RCVBUF;
879 
880 				if(fcntl(stream->fd, F_SETFL, O_NONBLOCK) == -1)
881 				{
882 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
883 				}
884 
885 				if(setsockopt(stream->fd, stream->protocol,
886 					TCP_NODELAY, &flag, sizeof(flag)) != 0)
887 				{
888 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
889 				}
890 
891 				if(setsockopt(stream->sock, SOL_SOCKET,
892 					SO_KEEPALIVE, &flag, sizeof(flag)) != 0)
893 				{
894 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
895 				}
896 
897 				if(setsockopt(stream->fd, SOL_SOCKET,
898 					SO_SNDBUF, &sendbuff, sizeof(sendbuff)) == -1)
899 				{
900 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
901 				}
902 
903 				if(setsockopt(stream->fd, SOL_SOCKET,
904 					SO_RCVBUF, &recvbuff, sizeof(recvbuff)) == -1)
905 				{
906 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
907 				}
908 
909 				stream->connected = true; // orderly accept
910 			}
911 			else
912 			{
913 				//ev = LV2_OSC_STREAM_ERRNO(ev, errno);
914 			}
915 		}
916 		else
917 		{
918 			if(stream->sock < 0)
919 			{
920 				ev = _lv2_osc_stream_reinit(stream);
921 			}
922 
923 			if(connect(stream->sock, (struct sockaddr *)&stream->peer.in6,
924 				stream->peer.len) == 0)
925 			{
926 				stream->connected = true; // orderly (re)connect
927 			}
928 			else
929 			{
930 				//if(errno == EISCONN)
931 				//{
932 				//	_close_socket(&stream->sock);
933 				//}
934 
935 				//ev = LV2_OSC_STREAM_ERRNO(ev, errno);
936 			}
937 		}
938 	}
939 
940 	// send everything
941 	if(stream->connected)
942 	{
943 		int *fd = stream->server
944 			? &stream->fd
945 			: &stream->sock;
946 
947 		if(*fd >= 0)
948 		{
949 			const uint8_t *buf;
950 			size_t tosend;
951 
952 			while( (buf = stream->driv->read_req(stream->data, &tosend)) )
953 			{
954 				if(stream->slip) // SLIP framed
955 				{
956 					if(tosend <= sizeof(stream->tx_buf)) // check if there is enough memory
957 					{
958 						memcpy(stream->tx_buf, buf, tosend);
959 						tosend = lv2_osc_slip_encode_inline(stream->tx_buf, tosend);
960 					}
961 					else
962 					{
963 						tosend = 0;
964 					}
965 				}
966 				else // uint32_t prefix frames
967 				{
968 					const size_t nsize = tosend + sizeof(uint32_t);
969 
970 					if(nsize <= sizeof(stream->tx_buf)) // check if there is enough memory
971 					{
972 						const uint32_t prefix = htonl(tosend);
973 
974 						memcpy(stream->tx_buf, &prefix, sizeof(uint32_t));
975 						memcpy(stream->tx_buf + sizeof(uint32_t), buf, tosend);
976 						tosend = nsize;
977 					}
978 					else
979 					{
980 						tosend = 0;
981 					}
982 				}
983 
984 				const ssize_t sent = tosend
985 					? send(*fd, stream->tx_buf, tosend, 0)
986 					: 0;
987 
988 				if(sent == -1)
989 				{
990 					if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
991 					{
992 						// empty queue
993 						break;
994 					}
995 
996 					_close_socket(fd);
997 					stream->connected = false;
998 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
999 					break;
1000 				}
1001 				else if(sent != (ssize_t)tosend)
1002 				{
1003 					ev = LV2_OSC_STREAM_ERRNO(ev, EIO);
1004 					break;
1005 				}
1006 
1007 				stream->driv->read_adv(stream->data);
1008 				ev |= LV2_OSC_SEND;
1009 			}
1010 		}
1011 	}
1012 
1013 	// recv everything
1014 	if(stream->connected)
1015 	{
1016 		int *fd = stream->server
1017 			? &stream->fd
1018 			: &stream->sock;
1019 
1020 		if(*fd >= 0)
1021 		{
1022 			if(stream->slip) // SLIP framed
1023 			{
1024 				while(true)
1025 				{
1026 					ssize_t recvd = recv(*fd, stream->rx_buf + stream->rx_off,
1027 						sizeof(stream->rx_buf) - stream->rx_off, 0);
1028 
1029 					if(recvd == -1)
1030 					{
1031 						if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
1032 						{
1033 							// empty queue
1034 							break;
1035 						}
1036 
1037 						_close_socket(fd);
1038 						stream->connected = false;
1039 						ev = LV2_OSC_STREAM_ERRNO(ev, errno);
1040 						break;
1041 					}
1042 					else if(recvd == 0)
1043 					{
1044 						_close_socket(fd);
1045 						stream->connected = false; // orderly shutdown
1046 						break;
1047 					}
1048 
1049 					uint8_t *ptr = stream->rx_buf;
1050 					recvd += stream->rx_off;
1051 
1052 					while(recvd > 0)
1053 					{
1054 						size_t size;
1055 						size_t parsed = lv2_osc_slip_decode_inline(ptr, recvd, &size);
1056 
1057 						if(size) // dispatch
1058 						{
1059 							uint8_t *buf;
1060 
1061 							if( (buf = stream->driv->write_req(stream->data, size, NULL)) )
1062 							{
1063 								memcpy(buf, ptr, size);
1064 
1065 								stream->driv->write_adv(stream->data, size);
1066 								ev |= LV2_OSC_RECV;
1067 							}
1068 							else
1069 							{
1070 								parsed = 0;
1071 								ev = LV2_OSC_STREAM_ERRNO(ev, ENOMEM);
1072 							}
1073 						}
1074 
1075 						if(parsed)
1076 						{
1077 							ptr += parsed;
1078 							recvd -= parsed;
1079 						}
1080 						else
1081 						{
1082 							break;
1083 						}
1084 					}
1085 
1086 					if(recvd > 0) // is there remaining chunk for next call?
1087 					{
1088 						memmove(stream->rx_buf, ptr, recvd);
1089 						stream->rx_off = recvd;
1090 					}
1091 					else
1092 					{
1093 						stream->rx_off = 0;
1094 					}
1095 
1096 					break;
1097 				}
1098 			}
1099 			else // uint32_t prefix frames
1100 			{
1101 				uint8_t *buf;
1102 
1103 				while( (buf = stream->driv->write_req(stream->data,
1104 					LV2_OSC_STREAM_REQBUF, NULL)) )
1105 				{
1106 					uint32_t prefix;
1107 
1108 					ssize_t recvd = recv(*fd, &prefix, sizeof(uint32_t), 0);
1109 					if(recvd == sizeof(uint32_t))
1110 					{
1111 						prefix = ntohl(prefix); //FIXME check prefix <= max_len
1112 						recvd = recv(*fd, buf, prefix, 0);
1113 					}
1114 					else if(recvd == -1)
1115 					{
1116 						if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
1117 						{
1118 							// empty queue
1119 							break;
1120 						}
1121 
1122 						_close_socket(fd);
1123 						stream->connected = false;
1124 						ev = LV2_OSC_STREAM_ERRNO(ev, errno);
1125 						break;
1126 					}
1127 					else if(recvd == 0)
1128 					{
1129 						_close_socket(fd);
1130 						stream->connected = false; // orderly shutdown
1131 						break;
1132 					}
1133 
1134 					stream->driv->write_adv(stream->data, recvd);
1135 					ev |= LV2_OSC_RECV;
1136 				}
1137 			}
1138 		}
1139 	}
1140 
1141 	if(stream->connected)
1142 	{
1143 		ev |= LV2_OSC_CONN;
1144 	}
1145 
1146 	return ev;
1147 }
1148 
1149 static LV2_OSC_Enum
_lv2_osc_stream_run_ser(LV2_OSC_Stream * stream)1150 _lv2_osc_stream_run_ser(LV2_OSC_Stream *stream)
1151 {
1152 	LV2_OSC_Enum ev = LV2_OSC_NONE;
1153 
1154 	// send everything
1155 	{
1156 		const int fd = stream->sock;
1157 
1158 		if(fd >= 0)
1159 		{
1160 			const uint8_t *buf;
1161 			size_t tosend;
1162 
1163 			while( (buf = stream->driv->read_req(stream->data, &tosend)) )
1164 			{
1165 				if(stream->slip) // SLIP framed
1166 				{
1167 					if(tosend <= sizeof(stream->tx_buf)) // check if there is enough memory
1168 					{
1169 						memcpy(stream->tx_buf, buf, tosend);
1170 						tosend = lv2_osc_slip_encode_inline(stream->tx_buf, tosend);
1171 					}
1172 					else
1173 					{
1174 						tosend = 0;
1175 					}
1176 				}
1177 				else // uint32_t prefix frames
1178 				{
1179 					const size_t nsize = tosend + sizeof(uint32_t);
1180 
1181 					if(nsize <= sizeof(stream->tx_buf)) // check if there is enough memory
1182 					{
1183 						const uint32_t prefix = htonl(tosend);
1184 
1185 						memcpy(stream->tx_buf, &prefix, sizeof(uint32_t));
1186 						memcpy(stream->tx_buf + sizeof(uint32_t), buf, tosend);
1187 						tosend = nsize;
1188 					}
1189 					else
1190 					{
1191 						tosend = 0;
1192 					}
1193 				}
1194 
1195 				const ssize_t sent = tosend
1196 					? write(fd, stream->tx_buf, tosend)
1197 					: 0;
1198 
1199 				if(sent == -1)
1200 				{
1201 					if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
1202 					{
1203 						// empty queue
1204 						break;
1205 					}
1206 
1207 					ev = LV2_OSC_STREAM_ERRNO(ev, errno);
1208 					break;
1209 				}
1210 				else if(sent != (ssize_t)tosend)
1211 				{
1212 					ev = LV2_OSC_STREAM_ERRNO(ev, EIO);
1213 					break;
1214 				}
1215 
1216 				stream->driv->read_adv(stream->data);
1217 				ev |= LV2_OSC_SEND;
1218 			}
1219 		}
1220 	}
1221 
1222 	// recv everything
1223 	{
1224 		const int fd = stream->sock;
1225 
1226 		if(fd >= 0)
1227 		{
1228 			if(stream->slip) // SLIP framed
1229 			{
1230 				while(true)
1231 				{
1232 					ssize_t recvd = read(fd, stream->rx_buf + stream->rx_off,
1233 						sizeof(stream->rx_buf) - stream->rx_off);
1234 
1235 					if(recvd == -1)
1236 					{
1237 						if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
1238 						{
1239 							// empty queue
1240 							break;
1241 						}
1242 
1243 						stream->connected = false;
1244 						ev = LV2_OSC_STREAM_ERRNO(ev, errno);
1245 						break;
1246 					}
1247 					else if(recvd == 0)
1248 					{
1249 						// orderly shutdown
1250 						break;
1251 					}
1252 
1253 					uint8_t *ptr = stream->rx_buf;
1254 					recvd += stream->rx_off;
1255 
1256 					while(recvd > 0)
1257 					{
1258 						size_t size;
1259 						size_t parsed = lv2_osc_slip_decode_inline(ptr, recvd, &size);
1260 
1261 						if(size) // dispatch
1262 						{
1263 							uint8_t *buf;
1264 
1265 							if( (buf = stream->driv->write_req(stream->data, size, NULL)) )
1266 							{
1267 								memcpy(buf, ptr, size);
1268 
1269 								stream->driv->write_adv(stream->data, size);
1270 								ev |= LV2_OSC_RECV;
1271 							}
1272 							else
1273 							{
1274 								parsed = 0;
1275 								ev = LV2_OSC_STREAM_ERRNO(ev, ENOMEM);
1276 							}
1277 						}
1278 
1279 						if(parsed)
1280 						{
1281 							ptr += parsed;
1282 							recvd -= parsed;
1283 						}
1284 						else
1285 						{
1286 							break;
1287 						}
1288 					}
1289 
1290 					if(recvd > 0) // is there remaining chunk for next call?
1291 					{
1292 						memmove(stream->rx_buf, ptr, recvd);
1293 						stream->rx_off = recvd;
1294 					}
1295 					else
1296 					{
1297 						stream->rx_off = 0;
1298 					}
1299 
1300 					break;
1301 				}
1302 			}
1303 			else // uint32_t prefix frames
1304 			{
1305 				uint8_t *buf;
1306 
1307 				while( (buf = stream->driv->write_req(stream->data,
1308 					LV2_OSC_STREAM_REQBUF, NULL)) )
1309 				{
1310 					uint32_t prefix;
1311 
1312 					ssize_t recvd = read(fd, &prefix, sizeof(uint32_t));
1313 					if(recvd == sizeof(uint32_t))
1314 					{
1315 						prefix = ntohl(prefix); //FIXME check prefix <= max_len
1316 						recvd = read(fd, buf, prefix);
1317 					}
1318 					else if(recvd == -1)
1319 					{
1320 						if( (errno == EAGAIN) || (errno == EWOULDBLOCK) )
1321 						{
1322 							// empty queue
1323 							break;
1324 						}
1325 
1326 						stream->connected = false;
1327 						ev = LV2_OSC_STREAM_ERRNO(ev, errno);
1328 						break;
1329 					}
1330 					else if(recvd == 0)
1331 					{
1332 						// orderly shutdown
1333 						break;
1334 					}
1335 
1336 					stream->driv->write_adv(stream->data, recvd);
1337 					ev |= LV2_OSC_RECV;
1338 				}
1339 			}
1340 		}
1341 	}
1342 
1343 	if(stream->connected)
1344 	{
1345 		ev |= LV2_OSC_CONN;
1346 	}
1347 
1348 	return ev;
1349 }
1350 
1351 static LV2_OSC_Enum
lv2_osc_stream_run(LV2_OSC_Stream * stream)1352 lv2_osc_stream_run(LV2_OSC_Stream *stream)
1353 {
1354 	LV2_OSC_Enum ev = LV2_OSC_NONE;
1355 
1356 	switch(stream->socket_type)
1357 	{
1358 		case SOCK_DGRAM:
1359 		{
1360 			ev |= _lv2_osc_stream_run_udp(stream);
1361 		} break;
1362 		case SOCK_STREAM:
1363 		{
1364 			ev |= _lv2_osc_stream_run_tcp(stream);
1365 		} break;
1366 		default:
1367 		{
1368 			ev |= _lv2_osc_stream_run_ser(stream);
1369 		} break;
1370 	}
1371 
1372 	return ev;
1373 }
1374 
1375 #ifdef __cplusplus
1376 } // extern "C"
1377 #endif
1378 
1379 #endif // LV2_OSC_STREAM_H
1380