Debian Codegraph @

src/core/lo/server.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2014 Steve Harris et al. (see AUTHORS)
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License as
6 * published by the Free Software Foundation; either version 2.1 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Lesser General Public License for more details.
13 *
14 * $Id$
15 */
16
17 #include "config.h"
18
19 #include <assert.h>
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #include <float.h>
26 #include <sys/types.h>
27 #include <fcntl.h>
28 #include <time.h>
29
30 #ifdef _MSC_VER
31 #define _WINSOCKAPI_
32 #define snprintf _snprintf
33 #else
34 #include <unistd.h>
35 #include <sys/time.h>
36 #endif
37
38 #if defined(_WIN32) || defined(_MSC_VER)
39 #include <winsock2.h>
40 #include <ws2tcpip.h>
41 #include <malloc.h>
42 // TODO: Does this make sense on any platform? At least mingw defines
43 // both EADDRINUSE and WSAEADDRINUSE and the values differ. We need to
44 // check for WSAEADDRINUSE though on Windows.
45 #ifndef EADDRINUSE
46 #define EADDRINUSE WSAEADDRINUSE
47 #endif
48 #else
49 #include <netdb.h>
50 #include <sys/socket.h>
51 #ifdef HAVE_POLL
52 #include <poll.h>
53 #endif
54 #include <sys/un.h>
55 #include <arpa/inet.h>
56 #include <netinet/in.h>
57 #ifdef HAVE_GETIFADDRS
58 #include <ifaddrs.h>
59 #endif
60 #endif
61
62 #if defined(_WIN32) || defined(_MSC_VER)
63 #define geterror() WSAGetLastError()
64 #else
65 #define geterror() errno
66 #endif
67
68 #ifndef SOCKET_ERROR
69 #define SOCKET_ERROR -1
70 #endif
71
72 #include "lo_types_internal.h"
73 #include "lo_internal.h"
74 #include "lo.h"
75 #include "lo_lowlevel.h"
76 #include "lo_throw.h"
77
78 typedef struct {
79 lo_timetag ts;
80 char *path;
81 lo_message msg;
82 int sock;
83 void *next;
84 } queued_msg_list;
85
86 struct lo_cs lo_client_sockets = { -1, -1 };
87 static int reuseport_supported = 1;
88
89 static int lo_can_coerce_spec(const char *a, const char *b);
90 static int lo_can_coerce(char a, char b);
91 static void dispatch_method(lo_server s, const char *path,
92 lo_message msg, int sock);
93 static int dispatch_data(lo_server s, void *data,
94 size_t size, int sock);
95 static int dispatch_queued(lo_server s, int dispatch_all);
96 static void queue_data(lo_server s, lo_timetag ts, const char *path,
97 lo_message msg, int sock);
98 static lo_server lo_server_new_with_proto_internal(const char *group,
99 const char *port,
100 const char *iface,
101 const char *ip,
102 int proto,
103 lo_err_handler err_h,
104 void *err_h_context);
105 static int lo_server_join_multicast_group(lo_server s, const char *group,
106 int family,
107 const char *iface, const char *ip);
108
109 #if defined(_WIN32) || defined(_MSC_VER)
110 #ifndef gai_strerror
111 // Copied from the Win32 SDK
112
113 // WARNING: The gai_strerror inline functions below use static buffers,
114 // and hence are not thread-safe. We'll use buffers long enough to hold
115 // 1k characters. Any system error messages longer than this will be
116 // returned as empty strings. However 1k should work for the error codes
117 // used by getaddrinfo().
118 #define GAI_STRERROR_BUFFER_SIZE 1024
119
120 char *WSAAPI gai_strerrorA(int ecode)
121 {
122 DWORD dwMsgLen;
123 static char buff[GAI_STRERROR_BUFFER_SIZE + 1];
124
125 dwMsgLen = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM
126 | FORMAT_MESSAGE_IGNORE_INSERTS
127 | FORMAT_MESSAGE_MAX_WIDTH_MASK,
128 NULL,
129 ecode,
130 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
131 (LPSTR) buff,
132 GAI_STRERROR_BUFFER_SIZE, NULL);
133 return buff;
134 }
135 #endif
136
137 static int stateWSock = -1;
138
139 int initWSock()
140 {
141 WORD reqversion;
142 WSADATA wsaData;
143 if (stateWSock >= 0)
144 return stateWSock;
145 /* TODO - which version of Winsock do we actually need? */
146
147 reqversion = MAKEWORD(2, 2);
148 if (WSAStartup(reqversion, &wsaData) != 0) {
149 /* Couldn't initialize Winsock */
150 stateWSock = 0;
151 } else if (LOBYTE(wsaData.wVersion) != LOBYTE(reqversion) ||
152 HIBYTE(wsaData.wVersion) != HIBYTE(reqversion)) {
153 /* wrong version */
154 WSACleanup();
155 stateWSock = 0;
156 } else
157 stateWSock = 1;
158
159 return stateWSock;
160 }
161
162 static int detect_windows_server_2003_or_later()
163 {
164 OSVERSIONINFOEX osvi;
165 DWORDLONG dwlConditionMask = 0;
166 int op=VER_GREATER_EQUAL;
167
168 ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
169 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
170 osvi.dwMajorVersion = 5;
171 osvi.dwMinorVersion = 2;
172
173 VER_SET_CONDITION( dwlConditionMask, VER_MAJORVERSION, op );
174 VER_SET_CONDITION( dwlConditionMask, VER_MINORVERSION, op );
175
176 return VerifyVersionInfo(
177 &osvi,
178 VER_MAJORVERSION | VER_MINORVERSION |
179 VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
180 dwlConditionMask);
181 }
182
183 #endif
184
185 #ifdef ENABLE_IPV6
186 static unsigned int get_family_PF(const char *ip, const char *port)
187 {
188 struct addrinfo *ai=0;
189 unsigned int fam=PF_UNSPEC;
190 int ret = getaddrinfo(ip, port, 0, &ai);
191 if (ai) {
192 if (ret==0)
193 fam = ai->ai_family;
194 freeaddrinfo(ai);
195 }
196 return fam;
197 }
198 #endif
199
200 static int lo_server_setsock_reuseaddr(lo_server s, int do_throw)
201 {
202 unsigned int yes = 1;
203 if (setsockopt(s->sockets[0].fd, SOL_SOCKET, SO_REUSEADDR,
204 (char*)&yes, sizeof(yes)) < 0) {
205 int err = geterror();
206 if (do_throw)
207 lo_throw(s, err, strerror(err), "setsockopt(SO_REUSEADDR)");
208 return err;
209 }
210 return 0;
211 }
212
213 static int lo_server_setsock_reuseport(lo_server s, int do_throw)
214 {
215 #ifdef SO_REUSEPORT
216 unsigned int yes = 1;
217 if (setsockopt(s->sockets[0].fd, SOL_SOCKET, SO_REUSEPORT,
218 &yes, sizeof(yes)) < 0) {
219 int err = geterror();
220 if (do_throw)
221 lo_throw(s, err, strerror(err), "setsockopt(SO_REUSEPORT)");
222 return err;
223 }
224 #endif
225 return 0;
226 }
227
228 lo_server lo_server_new(const char *port, lo_err_handler err_h)
229 {
230 return lo_server_new_with_proto(port, LO_DEFAULT, err_h);
231 }
232
233 lo_server lo_server_new_multicast(const char *group, const char *port,
234 lo_err_handler err_h)
235 {
236 return lo_server_new_with_proto_internal(group, port, 0, 0, LO_UDP, err_h, 0);
237 }
238
239 #if defined(_WIN32) || defined(_MSC_VER) || defined(HAVE_GETIFADDRS)
240 lo_server lo_server_new_multicast_iface(const char *group, const char *port,
241 const char *iface, const char *ip,
242 lo_err_handler err_h)
243 {
244 return lo_server_new_with_proto_internal(group, port, iface, ip, LO_UDP, err_h, 0);
245 }
246 #endif
247
248 lo_server lo_server_new_with_proto(const char *port, int proto,
249 lo_err_handler err_h)
250 {
251 return lo_server_new_with_proto_internal(NULL, port, 0, 0, proto, err_h, 0);
252 }
253
254 lo_server lo_server_new_from_url(const char *url,
255 lo_err_handler err_h)
256 {
257 lo_server s;
258 int protocol;
259 char *group, *port, *proto;
260
261 if (!url || !*url) {
262 return NULL;
263 }
264
265 protocol = lo_url_get_protocol_id(url);
266 if (protocol == LO_UDP || protocol == LO_TCP) {
267 group = lo_url_get_hostname(url);
268 port = lo_url_get_port(url);
269 s = lo_server_new_with_proto_internal(group, port, 0, 0,
270 protocol, err_h, 0);
271 if (group)
272 free(group);
273 if (port)
274 free(port);
275 #if !defined(_WIN32) && !defined(_MSC_VER)
276 } else if (protocol == LO_UNIX) {
277 port = lo_url_get_path(url);
278 s = lo_server_new_with_proto_internal(0, port, 0, 0,
279 LO_UNIX, err_h, 0);
280 if (port)
281 free(port);
282 #endif
283 } else {
284 proto = lo_url_get_protocol(url);
285 fprintf(stderr,
286 PACKAGE_NAME ": protocol '%s' not supported by this "
287 "version\n", proto);
288 if (proto)
289 free(proto);
290
291 return NULL;
292 }
293
294 return s;
295 }
296
297 lo_server lo_server_new_from_config(lo_server_config *config)
298 {
299 if (config->size < sizeof(lo_server_config))
300 return NULL;
301
302 return lo_server_new_with_proto_internal(config->group,
303 config->port,
304 config->iface,
305 config->ip,
306 config->proto,
307 config->err_handler,
308 config->err_handler_context);
309 }
310
311 static
312 void lo_server_resolve_hostname(lo_server s)
313 {
314 char hostname[LO_HOST_SIZE];
315
316 /* Set hostname to empty string */
317 hostname[0] = '\0';
318
319 #if defined(ENABLE_IPV6) && defined(HAVE_GETIFADDRS)
320 /* Try it the IPV6 friendly way first */
321 do {
322 struct ifaddrs *ifa, *ifa_list;
323 if (getifaddrs(&ifa_list))
324 break;
325 ifa = ifa_list;
326
327 while (ifa) {
328 if (!ifa->ifa_addr) {
329 ifa = ifa->ifa_next;
330 continue;
331 }
332
333 if (s->addr_if.iface) {
334 if (s->addr_if.size == sizeof(struct in_addr)
335 && (ifa->ifa_addr->sa_family == AF_INET))
336 {
337 struct sockaddr_in *sin = (struct sockaddr_in*)ifa->ifa_addr;
338 if (memcmp(&sin->sin_addr, &s->addr_if.a.addr, sizeof(struct in_addr))!=0
339 || (s->addr_if.iface && ifa->ifa_name
340 && strcmp(s->addr_if.iface, ifa->ifa_name)!=0))
341 {
342 ifa = ifa->ifa_next;
343 continue;
344 }
345 }
346 else if (s->addr_if.size == sizeof(struct in6_addr)
347 && (ifa->ifa_addr->sa_family == AF_INET6))
348 {
349 struct sockaddr_in6 *sin = (struct sockaddr_in6*)ifa->ifa_addr;
350 if (memcmp(&sin->sin6_addr, &s->addr_if.a.addr6,
351 sizeof(struct in6_addr))!=0
352 || (s->addr_if.iface && ifa->ifa_name
353 && strcmp(s->addr_if.iface, ifa->ifa_name)!=0))
354 {
355 ifa = ifa->ifa_next;
356 continue;
357 }
358 }
359 }
360
361 if ((ifa->ifa_addr->sa_family == AF_INET
362 && (!s->addr_if.iface || s->addr_if.size == sizeof(struct in_addr))
363 && (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), hostname,
364 sizeof(hostname), NULL, 0, NI_NAMEREQD) == 0))
365 || (ifa->ifa_addr->sa_family == AF_INET6
366 && (!s->addr_if.iface || s->addr_if.size == sizeof(struct in6_addr))
367 && (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), hostname,
368 sizeof(hostname), NULL, 0, NI_NAMEREQD) == 0)))
369 {
370 /* check to make sure getnameinfo() didn't just set the hostname to "::".
371 Needed on Darwin. */
372 if (hostname[0] == ':')
373 hostname[0] = '\0';
374 else if (strcmp(hostname, "localhost")==0)
375 hostname[0] = '\0';
376 else
377 break;
378 }
379 ifa = ifa->ifa_next;
380 }
381
382 freeifaddrs(ifa_list);
383 }
384 while (0);
385 #endif
386
387 /* Fallback to the oldschool (i.e. more reliable) way */
388 if (!hostname[0]) {
389 struct hostent *he;
390
391 gethostname(hostname, sizeof(hostname));
392 he = gethostbyname(hostname);
393 if (he) {
394 strncpy(hostname, he->h_name, sizeof(hostname) - 1);
395 }
396 }
397
398 /* somethings gone really wrong, just hope its local only */
399 if (!hostname[0]) {
400 strcpy(hostname, "localhost");
401 }
402
403 s->hostname = strdup(hostname);
404 }
405
406 #if defined(_WIN32) || defined(_MSC_VER) || defined(HAVE_GETIFADDRS)
407
408 static int lo_server_set_iface(lo_server s, int fam, const char *iface, const char *ip)
409 {
410 int err = lo_inaddr_find_iface(&s->addr_if, fam, iface, ip);
411 if (err)
412 return err;
413
414 if (s->addr_if.size == sizeof(struct in_addr)) {
415 if (setsockopt(s->sockets[0].fd, IPPROTO_IP, IP_MULTICAST_IF,
416 (const char*)&s->addr_if.a.addr, (socklen_t) s->addr_if.size) < 0)
417 {
418 err = geterror();
419 lo_throw(s, err, strerror(err), "setsockopt(IP_MULTICAST_IF)");
420 return err;
421 }
422 }
423 #ifdef ENABLE_IPV6 // TODO: this setsockopt fails on linux
424 else if (s->addr_if.size == sizeof(struct in6_addr)) {
425 if (setsockopt(s->sockets[0].fd, IPPROTO_IP, IPV6_MULTICAST_IF,
426 &s->addr_if.a.addr6, (socklen_t) s->addr_if.size) < 0) {
427 err = geterror();
428 lo_throw(s, err, strerror(err), "setsockopt(IPV6_MULTICAST_IF)");
429 return err;
430 }
431 }
432 #endif
433 return 0;
434 }
435
436 #endif // HAVE_GETIFADDRS
437
438 lo_server lo_server_new_with_proto_internal(const char *group,
439 const char *port,
440 const char *iface,
441 const char *ip,
442 int proto,
443 lo_err_handler err_h,
444 void *err_h_context)
445 {
446 lo_server s;
447 struct addrinfo *ai = NULL, *it, *used;
448 struct addrinfo hints;
449 int tries = 0;
450 char pnum[16];
451 const char *service;
452 int err = 0;
453
454 #if defined(_WIN32) || defined(_MSC_VER)
455 /* Windows Server 2003 or later (Vista, 7, etc.) must join the
456 * multicast group before bind(), but Windows XP must join
457 * after bind(). */
458 int wins2003_or_later = detect_windows_server_2003_or_later();
459 #endif
460
461 // Set real protocol, if Default is requested
462 if (proto == LO_DEFAULT) {
463 #if !defined(_WIN32) && !defined(_MSC_VER)
464 if (port && *port == '/')
465 proto = LO_UNIX;
466 else
467 #endif
468 proto = LO_UDP;
469 }
470 #if defined(_WIN32) || defined(_MSC_VER)
471 if (!initWSock())
472 return NULL;
473 #endif
474
475 s = (lo_server) calloc(1, sizeof(struct _lo_server));
476 if (!s)
477 return 0;
478
479 s->err_h = err_h;
480 s->error_user_data = err_h_context;
481 s->first = NULL;
482 s->ai = NULL;
483 s->hostname = NULL;
484 s->protocol = proto;
485 s->flags = (lo_server_flags) LO_SERVER_DEFAULT_FLAGS;
486 s->port = 0;
487 s->path = NULL;
488 s->queued = NULL;
489 s->sockets_len = 1;
490 s->sockets_alloc = 2;
491 s->sockets = (lo_server_fd_type *) calloc(2, sizeof(*(s->sockets)));
492 s->contexts = (struct socket_context *) calloc(2, sizeof(*(s->contexts)));
493 s->sources = (lo_address)calloc(2, sizeof(struct _lo_address));
494 s->sources_len = 2;
495 s->bundle_start_handler = NULL;
496 s->bundle_end_handler = NULL;
497 s->bundle_handler_user_data = NULL;
498 s->addr_if.iface = 0;
499 s->addr_if.size = 0;
500
501 if (!(s->sockets && s->contexts && s->sources)) {
502 free(s->sockets);
503 free(s->contexts);
504 free(s->sources);
505 free(s);
506 return 0;
507 }
508
509 s->sockets[0].fd = -1;
510 s->max_msg_size = LO_DEFAULT_MAX_MSG_SIZE;
511
512 memset(&hints, 0, sizeof(hints));
513
514 if (proto == LO_UDP) {
515 hints.ai_socktype = SOCK_DGRAM;
516 } else if (proto == LO_TCP) {
517 hints.ai_socktype = SOCK_STREAM;
518 }
519 #if !defined(_WIN32) && !defined(_MSC_VER)
520 else if (proto == LO_UNIX) {
521
522 struct sockaddr_un sa;
523
524 s->sockets[0].fd = socket(PF_UNIX, SOCK_DGRAM, 0);
525 if (s->sockets[0].fd == -1) {
526 err = geterror();
527 used = NULL;
528 lo_throw(s, err, strerror(err), "socket()");
529 lo_server_free(s);
530
531 return NULL;
532 }
533
534 sa.sun_family = AF_UNIX;
535 strncpy(sa.sun_path, port, sizeof(sa.sun_path) - 1);
536
537 if ((bind(s->sockets[0].fd,
538 (struct sockaddr *) &sa, sizeof(sa))) < 0) {
539 err = geterror();
540 lo_throw(s, err, strerror(err), "bind()");
541
542 lo_server_free(s);
543 return NULL;
544 }
545
546 s->path = strdup(port);
547
548 return s;
549 }
550 #endif
551 else {
552 lo_throw(s, LO_UNKNOWNPROTO, "Unknown protocol", NULL);
553 lo_server_free(s);
554
555 return NULL;
556 }
557
558 #ifdef ENABLE_IPV6
559 /* Determine the address family based on provided IP string or
560 multicast group, if available, otherwise let the operating
561 system decide. */
562 hints.ai_family = PF_INET6;
563 if (ip)
564 hints.ai_family = get_family_PF(ip, port);
565 else if (group)
566 hints.ai_family = get_family_PF(group, port);
567 #else
568 hints.ai_family = PF_INET;
569 #endif
570 hints.ai_flags = AI_PASSIVE;
571
572 if (!port) {
573 service = pnum;
574 } else {
575 service = port;
576 }
577 do {
578 int ret;
579 if (!port) {
580 /* not a good way to get random numbers, but its not critical */
581 snprintf(pnum, 15, "%ld", 10000 + ((unsigned int) rand() +
582 (long int)time(NULL)) % 10000);
583 }
584
585 if (ai)
586 freeaddrinfo(ai);
587
588 ret = getaddrinfo(NULL, service, &hints, &ai);
589
590 s->ai = ai;
591 s->sockets[0].fd = -1;
592 s->port = 0;
593
594 if (ret != 0) {
595 lo_throw(s, ret, gai_strerror(ret), NULL);
596 lo_server_free(s);
597 return NULL;
598 }
599
600 used = NULL;
601
602 for (it = ai; it && s->sockets[0].fd == -1; it = it->ai_next) {
603 used = it;
604 s->sockets[0].fd = socket(it->ai_family, hints.ai_socktype, 0);
605
606 if (s->sockets[0].fd != -1
607 && it->ai_family == AF_INET
608 && hints.ai_socktype == SOCK_DGRAM)
609 {
610 int opt = 1;
611 setsockopt(s->sockets[0].fd, SOL_SOCKET, SO_BROADCAST,
612 (char*)&opt, sizeof(int));
613 setsockopt(s->sockets[0].fd, IPPROTO_IP, IP_MULTICAST_LOOP,
614 (char*)&opt, sizeof(int));
615 }
616 }
617 if (s->sockets[0].fd == -1) {
618 err = geterror();
619 used = NULL;
620 lo_throw(s, err, strerror(err), "socket()");
621
622 lo_server_free(s);
623 return NULL;
624 }
625
626 #ifdef ENABLE_IPV6
627 unsigned int v6only_off = 0;
628 if (setsockopt(s->sockets[0].fd, IPPROTO_IPV6, IPV6_V6ONLY,
629 &v6only_off, sizeof(v6only_off)) < 0) {
630 err = geterror();
631 /* Ignore the error if the option is simply not supported. */
632 if (err!=ENOPROTOOPT) {
633 lo_throw(s, err, strerror(err), "setsockopt(IPV6_V6ONLY)");
634 lo_server_free(s);
635 return NULL;
636 }
637 }
638 #endif
639
640 if (group != NULL
641 || proto == LO_TCP)
642 {
643 err = lo_server_setsock_reuseaddr(s, 1);
644 if (err) {
645 lo_server_free(s);
646 return NULL;
647 }
648 }
649
650 if (group != NULL && reuseport_supported)
651 {
652 /* Ignore the error if SO_REUSEPORT wasn't successful. */
653 if (lo_server_setsock_reuseport(s, 0))
654 reuseport_supported = 0;
655 }
656
657 #if defined(_WIN32) || defined(_MSC_VER)
658 if (wins2003_or_later)
659 #endif
660 {
661 /* Join multicast group if specified. */
662 if (group != NULL) {
663 if (lo_server_join_multicast_group(s, group, used->ai_family,
664 iface, ip))
665 return NULL;
666 } else {
667 #if defined(_WIN32) || defined(_MSC_VER) || defined(HAVE_GETIFADDRS)
668 if ((iface || ip)
669 && lo_inaddr_find_iface(&s->addr_if, used->ai_family, iface, ip))
670 {
671 used = NULL;
672 continue;
673 }
674 #endif
675 }}
676
677 if ((used != NULL) &&
678 (bind(s->sockets[0].fd, used->ai_addr, used->ai_addrlen) <
679 0)) {
680 err = geterror();
681 #ifdef _WIN32
682 if (err == WSAEINVAL || err == WSAEADDRINUSE) {
683 #else
684 if (err == EINVAL || err == EADDRINUSE) {
685 #endif
686 used = NULL;
687 continue;
688 }
689
690 lo_throw(s, err, strerror(err), "bind()");
691 lo_server_free(s);
692
693 return NULL;
694 }
695 } while (!used && tries++ < 16);
696
697 if (!used) {
698 lo_throw(s, LO_NOPORT, "cannot find free port", NULL);
699
700 lo_server_free(s);
701 return NULL;
702 }
703
704 #if defined(_WIN32) || defined(_MSC_VER)
705 if (!wins2003_or_later)
706 /* Join multicast group if specified. */
707 if (group != NULL)
708 if (lo_server_join_multicast_group(s, group, used->ai_family,
709 iface, ip))
710 return NULL;
711 #endif
712
713 if (proto == LO_TCP) {
714 listen(s->sockets[0].fd, 8);
715 }
716
717 if (proto == LO_UDP) {
718 lo_client_sockets.udp = s->sockets[0].fd;
719 } else if (proto == LO_TCP) {
720 lo_client_sockets.tcp = s->sockets[0].fd;
721 }
722
723 if (used->ai_family == PF_INET6) {
724 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) used->ai_addr;
725 s->port = ntohs(addr->sin6_port);
726 } else if (used->ai_family == PF_INET) {
727 struct sockaddr_in *addr = (struct sockaddr_in *) used->ai_addr;
728 s->port = ntohs(addr->sin_port);
729 } else {
730 lo_throw(s, LO_UNKNOWNPROTO, "unknown protocol family", NULL);
731 s->port = atoi(port);
732 }
733
734 return s;
735 }
736
737 int lo_server_join_multicast_group(lo_server s, const char *group,
738 int fam, const char *iface, const char *ip)
739 {
740 struct ip_mreq mreq;
741 memset(&mreq, 0, sizeof(mreq));
742
743 // TODO ipv6 support here
744
745 if (fam==AF_INET) {
746 #ifdef HAVE_INET_PTON
747 if (inet_pton(AF_INET, group, &mreq.imr_multiaddr) == 0) {
748 int err = geterror();
749 lo_throw(s, err, strerror(err), "inet_aton()");
750 lo_server_free(s);
751 return err ? err : 1;
752 }
753 #else
754 mreq.imr_multiaddr.s_addr = inet_addr(group);
755 if (mreq.imr_multiaddr.s_addr == INADDR_ANY
756 || mreq.imr_multiaddr.s_addr == INADDR_NONE) {
757 int err = geterror();
758 lo_throw(s, err, strerror(err), "inet_addr()");
759 lo_server_free(s);
760 return err ? err : 1;
761 }
762 #endif
763 }
764 #if defined(_WIN32) || defined(_MSC_VER) || defined(HAVE_GETIFADDRS)
765 if (iface || ip) {
766 int err = lo_server_set_iface(s, fam, iface, ip);
767 if (err) {
768 lo_server_free(s);
769 return err;
770 }
771
772 mreq.imr_interface = s->addr_if.a.addr;
773 // TODO: the above assignment is for an in_addr, which assumes IPv4
774 // how to specify group membership interface with IPv6?
775 }
776 else
777 #endif // HAVE_GETIFADDRS
778 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
779
780 if (setsockopt(s->sockets[0].fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
781 (char*)&mreq, sizeof(mreq)) < 0) {
782 int err = geterror();
783 lo_throw(s, err, strerror(err), "setsockopt(IP_ADD_MEMBERSHIP)");
784 lo_server_free(s);
785 return err ? err : 1;
786 }
787
788 return 0;
789 }
790
791 int lo_server_enable_coercion(lo_server s, int enable)
792 {
793 int r = (s->flags & LO_SERVER_COERCE) != 0;
794 s->flags = (lo_server_flags)
795 ((s->flags & ~LO_SERVER_COERCE)
796 | (enable ? LO_SERVER_COERCE : 0));
797 return r;
798 }
799
800 int lo_server_should_coerce_args(lo_server s)
801 {
802 return (s->flags & LO_SERVER_COERCE) != 0;
803 }
804
805 void lo_server_free(lo_server s)
806 {
807 if (s) {
808 lo_method it;
809 lo_method next;
810 int i;
811
812 for (i = s->sockets_len - 1; i >= 0; i--) {
813 if (s->sockets[i].fd != -1) {
814 if (s->protocol == LO_UDP
815 && s->sockets[i].fd == lo_client_sockets.udp) {
816 lo_client_sockets.udp = -1;
817 } else if (s->protocol == LO_TCP
818 && s->sockets[i].fd == lo_client_sockets.tcp) {
819 lo_client_sockets.tcp = -1;
820 }
821
822 closesocket(s->sockets[i].fd);
823 s->sockets[i].fd = -1;
824 }
825 }
826 if (s->ai) {
827 freeaddrinfo(s->ai);
828 s->ai = NULL;
829 }
830 if (s->hostname) {
831 free(s->hostname);
832 s->hostname = NULL;
833 }
834 if (s->path) {
835 if (s->protocol == LO_UNIX)
836 unlink(s->path);
837 free(s->path);
838 s->path = NULL;
839 }
840 while (s->queued) {
841 queued_msg_list *q = (queued_msg_list *) s->queued;
842 free(q->path);
843 lo_message_free(q->msg);
844 s->queued = q->next;
845 free(q);
846 }
847 for (it = s->first; it; it = next) {
848 next = it->next;
849 free((char*) it->path);
850 free((char*) it->typespec);
851 free(it);
852 }
853 if (s->addr_if.iface)
854 free(s->addr_if.iface);
855
856 for (i=0; i < s->sockets_len; i++) {
857 if (s->sockets[i].fd > -1) {
858 #ifdef SHUT_WR
859 shutdown(s->sockets[i].fd, SHUT_WR);
860 #endif
861 closesocket(s->sockets[i].fd);
862 }
863 if (s->contexts[i].buffer)
864 free(s->contexts[i].buffer);
865 }
866 free(s->sockets);
867 free(s->contexts);
868
869 for (i=0; i < s->sources_len; i++) {
870 if (s->sources[i].host)
871 lo_address_free_mem(&s->sources[i]);
872 }
873 free(s->sources);
874
875 free(s);
876 }
877 }
878
879 int lo_server_enable_queue(lo_server s, int enable,
880 int dispatch_remaining)
881 {
882 int prev = (s->flags & LO_SERVER_ENQUEUE) != 0;
883 s->flags = (lo_server_flags)
884 ((s->flags & ~LO_SERVER_ENQUEUE)
885 | (enable ? LO_SERVER_ENQUEUE : 0));
886
887 if (!enable && dispatch_remaining && s->queued)
888 dispatch_queued(s, 1);
889
890 return prev;
891 }
892
893 void *lo_server_recv_raw(lo_server s, size_t * size)
894 {
895 char *buffer = NULL;
896 int ret, heap_buffer = 0;
897 void *data = NULL;
898
899 if (s->max_msg_size > 4096) {
900 buffer = (char*) malloc(s->max_msg_size);
901 heap_buffer = 1;
902 }
903 else {
904 buffer = (char*) alloca(s->max_msg_size);
905 }
906
907 if (!buffer)
908 return NULL;
909
910 if (s->max_msg_size<=0) {
911 if (heap_buffer) free(buffer);
912 return NULL;
913 }
914
915 #if defined(_WIN32) || defined(_MSC_VER)
916 if (!initWSock()) {
917 if (heap_buffer) free(buffer);
918 return NULL;
919 }
920 #endif
921
922 s->addr_len = sizeof(s->addr);
923
924 ret = (int) recvfrom(s->sockets[0].fd, buffer, s->max_msg_size, 0,
925 (struct sockaddr *) &s->addr, &s->addr_len);
926 if (ret <= 0) {
927 if (heap_buffer) free(buffer);
928 return NULL;
929 }
930 data = malloc(ret);
931 memcpy(data, buffer, ret);
932
933 if (size)
934 *size = ret;
935
936 if (heap_buffer) free(buffer);
937 return data;
938 }
939
940 // From http://tools.ietf.org/html/rfc1055
941 #define SLIP_END 0300 /* indicates end of packet */
942 #define SLIP_ESC 0333 /* indicates byte stuffing */
943 #define SLIP_ESC_END 0334 /* ESC ESC_END means END data byte */
944 #define SLIP_ESC_ESC 0335 /* ESC ESC_ESC means ESC data byte */
945
946 // buffer to write to
947 // buffer to read from
948 // size of buffer to read from
949 // state variable needed to maintain between calls broken on ESC boundary
950 // location to store count of bytes read from input buffer
951 static int slip_decode(unsigned char **buffer, unsigned char *from,
952 size_t size, int *state, size_t *bytesread)
953 {
954 assert(from != NULL);
955 *bytesread = 0;
956 while (size--) {
957 (*bytesread)++;
958 switch (*state) {
959 case 0:
960 switch (*from) {
961 case SLIP_END:
962 return 0;
963 case SLIP_ESC:
964 *state = 1;
965 from++;
966 continue;
967 default:
968 *(*buffer)++ = *from++;
969 }
970 break;
971
972 case 1:
973 switch (*from) {
974 case SLIP_ESC_END:
975 *(*buffer)++ = SLIP_END;
976 from++;
977 break;
978 case SLIP_ESC_ESC:
979 *(*buffer)++ = SLIP_ESC;
980 from++;
981 break;
982 }
983 *state = 0;
984 break;
985 }
986 };
987 return 1;
988 }
989
990 static int detect_slip(unsigned char *bytes)
991 {
992 // If stream starts with SLIP_END or with a '/', assume we are
993 // looking at a SLIP stream, otherwise, first four bytes probably
994 // represent a message length and we are looking at a count-prefix
995 // stream. Note that several SLIP_ENDs in a row are supposed to
996 // be ignored by the SLIP protocol, but here we only handle one
997 // extra one, since it may exist e.g. at the beginning of a
998 // stream.
999 if (bytes[0]==SLIP_END && bytes[1]=='/'
1000 && (isprint(bytes[2])||bytes[2]==0)
1001 && (isprint(bytes[3])||bytes[3]==0))
1002 return 1;
1003 if (bytes[0]=='/'
1004 && (isprint(bytes[1])||bytes[1]==0)
1005 && (isprint(bytes[2])||bytes[2]==0)
1006 && (isprint(bytes[3])||bytes[3]==0))
1007 return 1;
1008 if (memcmp(bytes, "#bun", 4)==0)
1009 return 1;
1010 return 0;
1011 }
1012
1013 static
1014 void init_context(struct socket_context *sc)
1015 {
1016 sc->is_slip = -1;
1017 sc->buffer = 0;
1018 sc->buffer_size = 0;
1019 sc->buffer_msg_offset = 0;
1020 sc->buffer_read_offset = 0;
1021 }
1022
1023 static
1024 void cleanup_context(struct socket_context *sc)
1025 {
1026 if (sc->buffer)
1027 free(sc->buffer);
1028 memset(sc, 0, sizeof(struct socket_context));
1029 }
1030
1031 /*! \internal Return message length if a whole message is waiting in
1032 * the socket's buffer, or 0 otherwise. */
1033 static
1034 uint32_t lo_server_buffer_contains_msg(lo_server s, int isock)
1035 {
1036 struct socket_context *sc = &s->contexts[isock];
1037 if (sc->buffer_read_offset <= sizeof(uint32_t))
1038 return 0;
1039
1040 uint32_t msg_len = ntohl(*(uint32_t*)sc->buffer);
1041 char *str = (char*)(sc->buffer + sizeof(uint32_t));
1042 if (str[0] != '/' && str[0] != '#')
1043 {
1044 // invalid message
1045 goto clear_buffer;
1046 }
1047 if (msg_len + sizeof(uint32_t) > sc->buffer_read_offset)
1048 {
1049 // still waiting for the rest of message
1050 return 0;
1051 }
1052 if (msg_len && lo_validate_string(str, msg_len) < 0)
1053 goto clear_buffer;
1054 return msg_len;
1055
1056 clear_buffer:
1057 sc->buffer_read_offset = sc->buffer_msg_offset = 0;
1058 return 0;
1059 }
1060
1061 static
1062 void *lo_server_buffer_copy_for_dispatch(lo_server s, int isock, size_t *psize)
1063 {
1064 void *data;
1065 struct socket_context *sc = &s->contexts[isock];
1066 uint32_t msg_len = lo_server_buffer_contains_msg(s, isock);
1067 if (msg_len == 0)
1068 return NULL;
1069
1070 data = malloc(msg_len);
1071 memcpy(data, sc->buffer + sizeof(uint32_t), msg_len);
1072 *psize = msg_len;
1073
1074 sc->buffer_read_offset -= msg_len + sizeof(uint32_t);
1075 sc->buffer_msg_offset -= msg_len + sizeof(uint32_t);
1076
1077 // Move any left-over data to the beginning of the buffer to
1078 // make room for the next read.
1079 if (sc->buffer_read_offset > 0)
1080 memmove(sc->buffer,
1081 sc->buffer + msg_len + sizeof(uint32_t),
1082 sc->buffer_read_offset);
1083
1084 return data;
1085 }
1086
1087 /*! \internal This is called when a socket in the list is ready for
1088 * recv'ing, previously checked by poll() or select(). */
1089 static
1090 int lo_server_recv_raw_stream_socket(lo_server s, int isock,
1091 size_t *psize, void **pdata)
1092 {
1093 struct socket_context *sc = &s->contexts[isock];
1094 char *stack_buffer = 0, *read_into;
1095 uint32_t msg_len;
1096 int buffer_bytes_left, bytes_recv;
1097 ssize_t bytes_written, size;
1098 *pdata = 0;
1099
1100 again:
1101
1102 // Check if there is already a message waiting in the buffer.
1103 if ((*pdata = lo_server_buffer_copy_for_dispatch(s, isock, psize))) {
1104 // There could be more data, so return true.
1105 return 1;
1106 }
1107
1108 buffer_bytes_left = (int) (sc->buffer_size - sc->buffer_read_offset);
1109
1110 // If we need more than half the buffer, double the buffer size.
1111 size = sc->buffer_size;
1112 if (size < 64)
1113 size = 64;
1114 while (buffer_bytes_left < size/2)
1115 {
1116 size *= 2;
1117
1118 // Strictly speaking this is an arbitrary limit and could be
1119 // removed for TCP, since there is no upper limit on packet
1120 // size as in UDP, however we leave it for security
1121 // reasons--an unterminated SLIP stream would consume memory
1122 // indefinitely.
1123 if (s->max_msg_size != -1 && size > s->max_msg_size) {
1124 size = s->max_msg_size;
1125 break;
1126 }
1127
1128 buffer_bytes_left = (int) (size - sc->buffer_read_offset);
1129 }
1130
1131 if ((size_t)size > sc->buffer_size)
1132 {
1133 sc->buffer_size = size;
1134 sc->buffer = (char*) realloc(sc->buffer, sc->buffer_size);
1135 if (!sc->buffer) {
1136 // Out of memory
1137 return 0;
1138 }
1139 }
1140
1141 // Read as much as we can into the remaining buffer memory.
1142 buffer_bytes_left = (int) (sc->buffer_size - sc->buffer_read_offset);
1143
1144 read_into = sc->buffer + sc->buffer_read_offset;
1145
1146 // In SLIP mode, we instead read into the local stack buffer
1147 if (sc->is_slip == 1)
1148 {
1149 stack_buffer = (char*) alloca(buffer_bytes_left - sizeof(uint32_t));
1150 read_into = stack_buffer;
1151 }
1152
1153 bytes_recv = (int) recv(s->sockets[isock].fd,
1154 read_into,
1155 buffer_bytes_left, 0);
1156
1157 if (bytes_recv <= 0)
1158 {
1159 if (errno == EAGAIN)
1160 return 0;
1161
1162 // Error, or socket was closed.
1163 // Either way, we remove it from the server.
1164 closesocket(s->sockets[isock].fd);
1165 lo_server_del_socket(s, isock, s->sockets[isock].fd);
1166 return 0;
1167 }
1168
1169 // If unknown, check whether we are in a SLIP stream.
1170 if (sc->is_slip == -1 && (sc->buffer_read_offset + bytes_recv) >= 4) {
1171 sc->is_slip = detect_slip((unsigned char*)(sc->buffer
1172 + sc->buffer_msg_offset));
1173 sc->slip_state = 0;
1174
1175 // Copy to stack if we just discovered we are in SLIP mode
1176 if (sc->is_slip)
1177 {
1178 stack_buffer = (char*) alloca(bytes_recv);
1179 memcpy(stack_buffer, read_into, bytes_recv);
1180
1181 // Make room for size header
1182 *(uint32_t*)(sc->buffer + sc->buffer_read_offset) = 0;
1183 sc->buffer_read_offset += sizeof(uint32_t);
1184 }
1185 }
1186
1187 if (sc->is_slip == 1)
1188 {
1189 // For SLIP, copy the read data into stack memory and decode
1190 // it back to the buffer. We will leave enough room to
1191 // prepend a count prefix, and let the count-prefix code
1192 // handle it below.
1193
1194 // Note for future: Actually we could dispatch it right here
1195 // instead of allocating and copying it to a buffer, but the
1196 // lo_server_recv() semantics require that we handle only 1
1197 // message at a time, so we are forced to leave undispatched
1198 // messages in the buffer for later.
1199
1200 size_t bytes_read = 0;
1201
1202 // Need to provide a mutable pointer to track how much memory
1203 // was written to the buffer by the SLIP decoder.
1204 char *buffer_after = sc->buffer + sc->buffer_read_offset;
1205
1206 // As long as we find whole messages, dispatch them.
1207 while (slip_decode((unsigned char**)&buffer_after,
1208 (unsigned char*)stack_buffer, bytes_recv,
1209 &sc->slip_state, &bytes_read) == 0)
1210 {
1211 // We have a whole message in the buffer.
1212 size_t bytes_written = buffer_after - sc->buffer - sc->buffer_read_offset;
1213
1214 sc->buffer_read_offset += bytes_written;
1215
1216 msg_len = sc->buffer_read_offset - sc->buffer_msg_offset - sizeof(uint32_t);
1217
1218 // Skip empty messages, for instance for when sender is double-ENDing SLIP
1219 if (msg_len)
1220 {
1221 // Store message length header
1222 *(uint32_t*)(sc->buffer + sc->buffer_msg_offset) = htonl(msg_len);
1223
1224 // Advance to next message and zero the message length header
1225 sc->buffer_msg_offset += msg_len + sizeof(uint32_t);
1226 sc->buffer_read_offset += sizeof(uint32_t);
1227 buffer_after += sizeof(uint32_t);
1228 *(uint32_t*)(sc->buffer + sc->buffer_msg_offset) = 0;
1229 }
1230
1231 // Update how much memory still needs decoding.
1232 bytes_recv -= bytes_read;
1233 stack_buffer += bytes_read;
1234
1235 // We could exceed buffer due to prepending the count
1236 // prefix, so if we need more buffer room, allocate it.
1237 if (bytes_recv + sizeof(uint32_t) > sc->buffer_size - sc->buffer_read_offset)
1238 {
1239 sc->buffer_size *= 2;
1240 sc->buffer = (char*) realloc(sc->buffer, sc->buffer_size);
1241 buffer_after = sc->buffer + sc->buffer_read_offset;
1242 }
1243 }
1244
1245 // Any data left over is left in the buffer, so update the
1246 // read offset to indicate the end of it.
1247 bytes_written = buffer_after - sc->buffer - sc->buffer_read_offset;
1248 sc->buffer_read_offset += bytes_written;
1249 }
1250 else
1251 {
1252 sc->buffer_read_offset += bytes_recv;
1253 }
1254
1255 *pdata = lo_server_buffer_copy_for_dispatch(s, isock, psize);
1256
1257 if (!*pdata && bytes_recv == buffer_bytes_left)
1258 {
1259 // There could be more data, try recv() again. This is okay
1260 // because we set the O_NONBLOCK flag.
1261 goto again;
1262 }
1263
1264 // We need to inform the caller whether there may be data left
1265 // to read, which is true if we read exactly as much as we
1266 // asked for.
1267 return bytes_recv == buffer_bytes_left;
1268 }
1269
1270 static
1271 void *lo_server_recv_raw_stream(lo_server s, size_t * size, int *psock)
1272 {
1273 struct sockaddr_storage addr;
1274 socklen_t addr_len = sizeof(addr);
1275 int i;
1276 void *data = NULL;
1277 int sock = -1;
1278 #ifdef HAVE_SELECT
1279 #ifndef HAVE_POLL
1280 fd_set ps;
1281 int nfds = 0;
1282 #endif
1283 #endif
1284
1285 assert(psock != NULL);
1286
1287 again:
1288
1289 /* check sockets in reverse order so that already-open sockets
1290 * have priority. this allows checking for closed sockets even
1291 * when new connections are being requested. it also allows to
1292 * continue looping through the list of sockets after closing and
1293 * deleting a socket, since deleting sockets doesn't affect the
1294 * order of the array to the left of the index. */
1295
1296 #ifdef HAVE_POLL
1297 for (i = 0; i < s->sockets_len; i++) {
1298 s->sockets[i].events = POLLIN | POLLPRI;
1299 s->sockets[i].revents = 0;
1300
1301 if ((data = lo_server_buffer_copy_for_dispatch(s, i, size))) {
1302 *psock = s->sockets[i].fd;
1303 return data;
1304 }
1305 }
1306
1307 poll(s->sockets, s->sockets_len, -1);
1308
1309 for (i = s->sockets_len - 1; i >= 0 && !data; --i) {
1310 if (s->sockets[i].revents & (POLLERR | POLLHUP)) {
1311 if (i > 0) {
1312 closesocket(s->sockets[i].fd);
1313 lo_server_del_socket(s, i, s->sockets[i].fd);
1314 continue;
1315 } else
1316 return NULL;
1317 }
1318 if (s->sockets[i].revents) {
1319 sock = s->sockets[i].fd;
1320
1321 #else
1322 #ifdef HAVE_SELECT
1323 #if defined(_WIN32) || defined(_MSC_VER)
1324 if (!initWSock())
1325 return NULL;
1326 #endif
1327
1328 nfds = 0;
1329 FD_ZERO(&ps);
1330 for (i = (s->sockets_len - 1); i >= 0; --i) {
1331 FD_SET(s->sockets[i].fd, &ps);
1332 #ifndef _WIN32
1333 if (s->sockets[i].fd > nfds)
1334 nfds = s->sockets[i].fd;
1335 #endif
1336 if ((data = lo_server_buffer_copy_for_dispatch(s, i, size))) {
1337 *psock = s->sockets[i].fd;
1338 return data;
1339 }
1340 }
1341
1342 if (select(nfds + 1, &ps, NULL, NULL, NULL) == SOCKET_ERROR)
1343 return NULL;
1344
1345 for (i = 0; i < s->sockets_len && !data; i++) {
1346 if (FD_ISSET(s->sockets[i].fd, &ps)) {
1347 sock = s->sockets[i].fd;
1348
1349 #endif
1350 #endif
1351
1352 if (sock == -1)
1353 return NULL;
1354
1355 /* zeroeth socket is listening for new connections */
1356 if (sock == s->sockets[0].fd) {
1357 sock = accept(sock, (struct sockaddr *) &addr, &addr_len);
1358
1359 i = lo_server_add_socket(s, sock, 0, &addr, addr_len);
1360
1361 /* after adding a new socket, call select()/poll()
1362 * again, since we are supposed to block until a
1363 * message is received. */
1364 goto again;
1365 }
1366
1367 if (i < 0) {
1368 closesocket(sock);
1369 return NULL;
1370 }
1371
1372 /* Handle incoming socket data */
1373 if (lo_server_recv_raw_stream_socket(s, i, size, &data)
1374 && !data)
1375 {
1376 // There could be more data waiting
1377 //*more = 1;
1378 }
1379 if (data)
1380 *psock = s->sockets[i].fd;
1381 }
1382 }
1383
1384 *psock = sock;
1385 return data;
1386 }
1387
1388 int lo_server_wait(lo_server s, int timeout)
1389 {
1390 return lo_servers_wait(&s, 0, 1, timeout);
1391 }
1392
1393 int lo_servers_wait(lo_server *s, int *status, int num_servers, int timeout)
1394 {
1395 int i, j, k, sched_timeout;
1396
1397 if (!status)
1398 status = alloca(sizeof(int) * num_servers);
1399 for (i = 0; i < num_servers; i++)
1400 status[i] = 0;
1401
1402 lo_timetag now, then;
1403 #ifdef HAVE_SELECT
1404 #ifndef HAVE_POLL
1405 fd_set ps;
1406 struct timeval stimeout;
1407 struct sockaddr_storage addr;
1408 socklen_t addr_len = sizeof(addr);
1409 #endif
1410 #endif
1411
1412 #ifdef HAVE_POLL
1413 socklen_t addr_len = sizeof(struct sockaddr_storage);
1414 struct sockaddr_storage *addr = alloca (addr_len * num_servers);
1415 int num_sockets;
1416
1417 again:
1418 num_sockets = 0;
1419 for (j = 0, k = 0; j < num_servers; j++) {
1420 for (i = 0; i < s[j]->sockets_len; i++) {
1421 if (lo_server_buffer_contains_msg(s[j], i)) {
1422 status[j] = 1;
1423 ++k;
1424 }
1425 ++num_sockets;
1426 }
1427 }
1428
1429 // Return immediately if one or more servers already have messages waiting.
1430 if (k > 0)
1431 return k;
1432
1433 struct pollfd *sockets = alloca(sizeof(struct pollfd) * num_sockets);
1434
1435 sched_timeout = timeout;
1436 for (j = 0, k = 0; j < num_servers; j++) {
1437 for (i = 0; i < s[j]->sockets_len; i++) {
1438 sockets[k].fd = s[j]->sockets[i].fd;
1439 sockets[k].events = POLLIN | POLLPRI | POLLERR | POLLHUP;
1440 sockets[k].revents = 0;
1441 ++k;
1442 }
1443 int server_timeout = lo_server_next_event_delay(s[j]) * 1000;
1444 if (server_timeout < sched_timeout)
1445 sched_timeout = server_timeout;
1446 }
1447
1448 lo_timetag_now(&then);
1449
1450 poll(sockets, num_sockets, timeout > sched_timeout ? sched_timeout : timeout);
1451
1452 // If poll() was reporting a new connection on the listening
1453 // socket rather than a ready message, accept it and check again.
1454 for (j = 0, k = 0; j < num_servers; j++) {
1455 if (sockets[k].revents) {
1456 if (sockets[k].revents & (POLLIN | POLLPRI)) {
1457 if (s[j]->protocol == LO_TCP) {
1458 int sock = accept(sockets[k].fd, (struct sockaddr *) &addr[j],
1459 &addr_len);
1460
1461 i = lo_server_add_socket(s[j], sock, 0, &addr[j], addr_len);
1462 if (i < 0)
1463 closesocket(sock);
1464
1465 lo_timetag_now(&now);
1466
1467 double diff = lo_timetag_diff(now, then);
1468
1469 timeout -= (int)(diff*1000);
1470 if (timeout < 0)
1471 timeout = 0;
1472
1473 goto again;
1474 }
1475 else {
1476 status[j] = 1;
1477 }
1478 }
1479 }
1480 k += s[j]->sockets_len;
1481 }
1482
1483 for (j = num_servers - 1, k = num_sockets - 1; j >= 0; j--, k--) {
1484 for (i = s[j]->sockets_len - 1; i > 0; i--, k--) {
1485 if (!sockets[k].revents)
1486 continue;
1487 if (sockets[k].revents & (POLLERR | POLLHUP)) {
1488 closesocket(sockets[k].fd);
1489 lo_server_del_socket(s[j], i, sockets[k].fd);
1490 }
1491 else
1492 status[j] = 1;
1493 }
1494 }
1495
1496 for (j = 0; j < num_servers; j++) {
1497 if (lo_server_next_event_delay(s[j]) < 0.01)
1498 status[j] = 1;
1499 }
1500 #else
1501 #ifdef HAVE_SELECT
1502 int res, to, nfds = 0;
1503
1504 #if defined(_WIN32) || defined(_MSC_VER)
1505 if (!initWSock())
1506 return 0;
1507 #endif
1508
1509 again:
1510
1511 sched_timeout = timeout;
1512 for (j = 0; j < num_servers; j++) {
1513 int server_timeout = lo_server_next_event_delay(s[j]) * 1000;
1514 if (server_timeout < sched_timeout)
1515 sched_timeout = server_timeout;
1516 }
1517
1518 to = timeout > sched_timeout ? sched_timeout : timeout;
1519 stimeout.tv_sec = to / 1000;
1520 stimeout.tv_usec = (to % 1000) * 1000;
1521
1522 FD_ZERO(&ps);
1523 for (j = 0; j < num_servers; j++) {
1524 for (i = 0; i < s[j]->sockets_len; i++) {
1525 FD_SET(s[j]->sockets[i].fd, &ps);
1526 #ifndef _WIN32
1527 if (s[j]->sockets[i].fd > nfds)
1528 nfds = s[j]->sockets[i].fd;
1529 #endif
1530 if (lo_server_buffer_contains_msg(s[j], i)) {
1531 status[j] = 1;
1532 }
1533 }
1534 }
1535
1536 lo_timetag_now(&then);
1537 res = select(nfds + 1, &ps, NULL, NULL, &stimeout);
1538
1539 if (res == SOCKET_ERROR)
1540 return 0;
1541 else if (res) {
1542 for (j = 0; j < num_servers; j++) {
1543 if (FD_ISSET(s[j]->sockets[0].fd, &ps)) {
1544 // If select() was reporting a new connection on the listening
1545 // socket rather than a ready message, accept it and check again.
1546 if (s[j]->protocol == LO_TCP) {
1547 int sock = accept(s[j]->sockets[0].fd,
1548 (struct sockaddr *) &addr, &addr_len);
1549 double diff;
1550 struct timeval tvdiff;
1551
1552 i = lo_server_add_socket(s[j], sock, 0, &addr, addr_len);
1553 if (i < 0)
1554 closesocket(sock);
1555
1556 lo_timetag_now(&now);
1557
1558 // Subtract time waited from total timeout
1559 diff = lo_timetag_diff(now, then);
1560 tvdiff.tv_sec = stimeout.tv_sec - (int)diff;
1561 tvdiff.tv_usec = stimeout.tv_usec - (diff * 1000000
1562 - (int)diff * 1000000);
1563
1564 // Handle underflow
1565 if (tvdiff.tv_usec < 0) {
1566 tvdiff.tv_sec -= 1;
1567 tvdiff.tv_usec = 1000000 + tvdiff.tv_usec;
1568 }
1569 if (tvdiff.tv_sec < 0) {
1570 stimeout.tv_sec = 0;
1571 stimeout.tv_usec = 0;
1572 }
1573 else
1574 stimeout = tvdiff;
1575
1576 timeout -= (int)(diff*1000);
1577 if (timeout < 0)
1578 timeout = 0;
1579
1580 goto again;
1581 }
1582 else {
1583 status[j] = 1;
1584 }
1585 }
1586 for (i = 1; i < s[j]->sockets_len; i++) {
1587 if (FD_ISSET(s[j]->sockets[i].fd, &ps))
1588 status[j] = 1;
1589 }
1590 }
1591 }
1592
1593 for (j = 0; j < num_servers; j++) {
1594 if (lo_server_next_event_delay(s[j]) < 0.01) {
1595 status[j] = 1;
1596 }
1597 }
1598 #endif
1599 #endif
1600
1601 for (i = 0, j = 0; i < num_servers; i++)
1602 j += status[i];
1603
1604 return j;
1605 }
1606
1607 int lo_servers_recv_noblock(lo_server *s, int *recvd, int num_servers,
1608 int timeout)
1609 {
1610 int i, total_bytes = 0;
1611 if (!lo_servers_wait(s, recvd, num_servers, timeout)) {
1612 return 0;
1613 }
1614 for (i = 0; i < num_servers; i++) {
1615 if (recvd[i]) {
1616 recvd[i] = lo_server_recv(s[i]);
1617 total_bytes += recvd[i];
1618 }
1619 }
1620 return total_bytes;
1621 }
1622
1623 int lo_server_recv_noblock(lo_server s, int timeout)
1624 {
1625 int status;
1626 return lo_servers_recv_noblock(&s, &status, 1, timeout);
1627 }
1628
1629 int lo_server_recv(lo_server s)
1630 {
1631 void *data;
1632 size_t size;
1633 double sched_time = lo_server_next_event_delay(s);
1634 int sock = -1;
1635 int i;
1636 #ifdef HAVE_SELECT
1637 #ifndef HAVE_POLL
1638 fd_set ps;
1639 struct timeval stimeout;
1640 int res, nfds = 0;
1641 #endif
1642 #endif
1643
1644 again:
1645 if (sched_time > 0.01) {
1646 if (sched_time > 10.0) {
1647 sched_time = 10.0;
1648 }
1649 #ifdef HAVE_POLL
1650 for (i = 0; i < s->sockets_len; i++) {
1651 s->sockets[i].events = POLLIN | POLLPRI | POLLERR | POLLHUP;
1652 s->sockets[i].revents = 0;
1653
1654 if (s->protocol == LO_TCP
1655 && (data = lo_server_buffer_copy_for_dispatch(s, i, &size)))
1656 {
1657 sock = s->sockets[i].fd;
1658 goto got_data;
1659 }
1660 }
1661
1662 poll(s->sockets, s->sockets_len, (int) (sched_time * 1000.0));
1663
1664 for (i = 0; i < s->sockets_len; i++) {
1665 if (!s->sockets[i].revents)
1666 continue;
1667 if (s->sockets[i].revents & (POLLERR | POLLHUP)) {
1668 if (i > 0) {
1669 closesocket(s->sockets[i].fd);
1670 lo_server_del_socket(s, i, s->sockets[i].fd);
1671 continue;
1672 } else
1673 return 0;
1674 }
1675 break;
1676 }
1677
1678 if (i >= s->sockets_len) {
1679 sched_time = lo_server_next_event_delay(s);
1680
1681 if (sched_time > 0.01)
1682 goto again;
1683
1684 return dispatch_queued(s, 0);
1685 }
1686 #else
1687 #ifdef HAVE_SELECT
1688 #if defined(_WIN32) || defined(_MSC_VER)
1689 if (!initWSock())
1690 return 0;
1691 #endif
1692
1693 FD_ZERO(&ps);
1694 for (i = 0; i < s->sockets_len; i++) {
1695 FD_SET(s->sockets[i].fd, &ps);
1696 #ifndef _WIN32
1697 if (s->sockets[i].fd > nfds)
1698 nfds = s->sockets[i].fd;
1699 #endif
1700 if (s->protocol == LO_TCP
1701 && (data = lo_server_buffer_copy_for_dispatch(s, i, &size)))
1702 {
1703 sock = s->sockets[i].fd;
1704 goto got_data;
1705 }
1706 }
1707
1708 stimeout.tv_sec = sched_time;
1709 stimeout.tv_usec = (sched_time - stimeout.tv_sec) * 1.e6;
1710 res = select(nfds + 1, &ps, NULL, NULL, &stimeout);
1711 if (res == SOCKET_ERROR) {
1712 return 0;
1713 }
1714
1715 if (!res) {
1716 sched_time = lo_server_next_event_delay(s);
1717
1718 if (sched_time > 0.01)
1719 goto again;
1720
1721 return dispatch_queued(s, 0);
1722 }
1723 #endif
1724 #endif
1725 } else {
1726 return dispatch_queued(s, 0);
1727 }
1728 if (s->protocol == LO_TCP) {
1729 data = lo_server_recv_raw_stream(s, &size, &sock);
1730 } else {
1731 data = lo_server_recv_raw(s, &size);
1732 }
1733
1734 if (!data) {
1735 return 0;
1736 }
1737 got_data:
1738 if (dispatch_data(s, data, size, sock) < 0) {
1739 free(data);
1740 return -1;
1741 }
1742 free(data);
1743 return (int) size;
1744 }
1745
1746 int lo_server_add_socket(lo_server s, int socket, lo_address a,
1747 struct sockaddr_storage *addr,
1748 socklen_t addr_len)
1749 {
1750 /* We must ensure all stream sockets are non-blocking on recv()
1751 * since we are doing our blocking via select()/poll(). */
1752 #ifdef _WIN32
1753 unsigned long on=1;
1754 ioctlsocket(socket, FIONBIO, &on);
1755 #else
1756 fcntl(socket, F_SETFL, O_NONBLOCK, 1);
1757 #endif
1758
1759 /* Update array of open sockets */
1760 if ((s->sockets_len + 1) > s->sockets_alloc) {
1761 void *sc;
1762 void *sp = realloc(s->sockets,
1763 sizeof(*(s->sockets)) * (s->sockets_alloc * 2));
1764 if (!sp)
1765 return -1;
1766 s->sockets = (lo_server_fd_type *) sp;
1767 memset((char*)sp + s->sockets_alloc*sizeof(*s->sockets),
1768 0, s->sockets_alloc*sizeof(*s->sockets));
1769
1770 sc = realloc(s->contexts,
1771 sizeof(*(s->contexts))
1772 * (s->sockets_alloc * 2));
1773 if (!sc)
1774 return -1;
1775 s->contexts = (struct socket_context *) sc;
1776
1777 s->sockets_alloc *= 2;
1778 }
1779
1780 /* Initialize new socket and context */
1781 s->sockets[s->sockets_len].fd = socket;
1782 init_context(&s->contexts[s->sockets_len]);
1783
1784 s->sockets_len++;
1785
1786 /* Update socket-indexed array of sources */
1787 if (socket >= s->sources_len) {
1788 int L = socket * 2;
1789 s->sources = (lo_address)
1790 realloc(s->sources,
1791 sizeof(struct _lo_address) * L);
1792 memset(s->sources + s->sources_len, 0,
1793 sizeof(struct _lo_address) * (L - s->sources_len));
1794 s->sources_len = L;
1795 }
1796
1797 if (a)
1798 lo_address_copy(&s->sources[socket], a);
1799 else
1800 lo_address_init_with_sockaddr(&s->sources[socket],
1801 addr, addr_len,
1802 socket, LO_TCP);
1803
1804 return s->sockets_len - 1;
1805 }
1806
1807 void lo_server_del_socket(lo_server s, int index, int socket)
1808 {
1809 int i;
1810
1811 if (index < 0 && socket != -1) {
1812 for (index = 0; index < s->sockets_len; index++)
1813 if (s->sockets[index].fd == socket)
1814 break;
1815 }
1816
1817 if (index < 0 || index >= s->sockets_len)
1818 return;
1819
1820 lo_address_free_mem(&s->sources[s->sockets[index].fd]);
1821 cleanup_context(&s->contexts[index]);
1822
1823 for (i = index + 1; i < s->sockets_len; i++) {
1824 s->sockets[i - 1] = s->sockets[i];
1825 s->contexts[i - 1] = s->contexts[i];
1826 }
1827 s->sockets_len--;
1828 }
1829
1830 static int dispatch_data(lo_server s, void *data,
1831 size_t size, int sock)
1832 {
1833 int result = 0;
1834 char *path = (char*) data;
1835 ssize_t len = lo_validate_string(data, size);
1836 if (len < 0) {
1837 lo_throw(s, (int) -len, "Invalid message path", NULL);
1838 return (int) len;
1839 }
1840
1841 if (!strcmp((const char *) data, "#bundle")) {
1842 char *pos;
1843 int remain;
1844 uint32_t elem_len;
1845 lo_timetag ts, now;
1846
1847 ssize_t bundle_result = lo_validate_bundle(data, size);
1848 if (bundle_result < 0) {
1849 lo_throw(s, (int) -bundle_result, "Invalid bundle", NULL);
1850 return (int) bundle_result;
1851 }
1852 pos = (char*) data + len;
1853 remain = (int) (size - len);
1854
1855 lo_timetag_now(&now);
1856 ts.sec = lo_otoh32(*((uint32_t *) pos));
1857 pos += 4;
1858 ts.frac = lo_otoh32(*((uint32_t *) pos));
1859 pos += 4;
1860 remain -= 8;
1861
1862 if (s->bundle_start_handler)
1863 s->bundle_start_handler(ts, s->bundle_handler_user_data);
1864
1865 while (remain >= 4) {
1866 lo_message msg;
1867 elem_len = lo_otoh32(*((uint32_t *) pos));
1868 pos += 4;
1869 remain -= 4;
1870
1871 if (!strcmp(pos, "#bundle")) {
1872 dispatch_data(s, pos, elem_len, sock);
1873 } else {
1874 msg = lo_message_deserialise(pos, elem_len, &result);
1875 if (!msg) {
1876 lo_throw(s, result, "Invalid bundle element received",
1877 path);
1878 return -result;
1879 }
1880 // set timetag from bundle
1881 msg->ts = ts;
1882
1883 // bump the reference count so that it isn't
1884 // automatically released
1885 lo_message_incref(msg);
1886
1887 // test for immediate dispatch
1888 if ((ts.sec == LO_TT_IMMEDIATE.sec
1889 && ts.frac == LO_TT_IMMEDIATE.frac)
1890 || lo_timetag_diff(ts, now) <= 0.0
1891 || (s->flags & LO_SERVER_ENQUEUE) == 0)
1892 {
1893 dispatch_method(s, pos, msg, sock);
1894 lo_message_free(msg);
1895 } else {
1896 queue_data(s, ts, pos, msg, sock);
1897 }
1898 }
1899
1900 pos += elem_len;
1901 remain -= elem_len;
1902 }
1903
1904 if (s->bundle_end_handler)
1905 s->bundle_end_handler(s->bundle_handler_user_data);
1906
1907 } else {
1908 lo_message msg = lo_message_deserialise(data, size, &result);
1909 if (NULL == msg) {
1910 lo_throw(s, result, "Invalid message received", path);
1911 return -result;
1912 }
1913 lo_message_incref(msg);
1914 dispatch_method(s, (const char *)data, msg, sock);
1915 lo_message_free(msg);
1916 }
1917 return (int) size;
1918 }
1919
1920 int lo_server_dispatch_data(lo_server s, void *data, size_t size)
1921 {
1922 return dispatch_data(s, data, size, -1);
1923 }
1924
1925 /* returns the time in seconds until the next scheduled event */
1926 double lo_server_next_event_delay(lo_server s)
1927 {
1928 if (s->queued) {
1929 lo_timetag now;
1930 double delay;
1931
1932 lo_timetag_now(&now);
1933 delay = lo_timetag_diff(((queued_msg_list *) s->queued)->ts, now);
1934
1935 delay = delay > 100.0 ? 100.0 : delay;
1936 delay = delay < 0.0 ? 0.0 : delay;
1937
1938 return delay;
1939 }
1940
1941 return 100.0;
1942 }
1943
1944 static void dispatch_method(lo_server s, const char *path,
1945 lo_message msg, int sock)
1946 {
1947 char *types = msg->types + 1;
1948 int argc = (int) strlen(types);
1949 lo_method it;
1950 int ret = 1;
1951 int pattern = lo_string_contains_pattern(path);
1952 lo_address src = 0;
1953 const char *pptr;
1954
1955 // Store the source information in the lo_address
1956 if (s->protocol == LO_TCP && sock >= 0) {
1957 msg->source = &s->sources[sock];
1958 }
1959 else {
1960 src = lo_address_new(NULL, NULL);
1961
1962 // free up default host/port strings so they can be resolved
1963 // properly if requested
1964 if (src->host) {
1965 free(src->host);
1966 src->host = 0;
1967 }
1968 if (src->port) {
1969 free(src->port);
1970 src->port = 0;
1971 }
1972 src->source_server = s;
1973 src->source_path = path;
1974 src->protocol = s->protocol;
1975 msg->source = src;
1976 }
1977
1978 for (it = s->first; it; it = it->next) {
1979 /* If paths match or handler is wildcard */
1980 if (!it->path || !strcmp(path, it->path) ||
1981 (pattern && lo_pattern_match(it->path, path)) ||
1982 (it->has_pattern && lo_pattern_match(path, it->path))) {
1983 /* If types match or handler is wildcard */
1984 if (!it->typespec || !strcmp(types, it->typespec)) {
1985 /* Send wildcard path to generic handler, expanded path
1986 to others.
1987 */
1988 pptr = path;
1989 if (it->path && !it->has_pattern)
1990 pptr = it->path;
1991 ret = it->handler(pptr, types, msg->argv, argc, msg,
1992 it->user_data);
1993
1994 } else if (lo_server_should_coerce_args(s) && lo_can_coerce_spec(types, it->typespec)) {
1995 lo_arg **argv = NULL;
1996 char *data_co = NULL;
1997
1998 if (argc > 0) {
1999 int i;
2000 int opsize = 0;
2001 char *ptr = (char*) msg->data, *data_co_ptr = NULL;
2002
2003 argv = (lo_arg **) calloc(argc, sizeof(lo_arg *));
2004 for (i = 0; i < argc; i++) {
2005 opsize += lo_arg_size((lo_type)it->typespec[i], ptr);
2006 ptr += lo_arg_size((lo_type)types[i], ptr);
2007 }
2008
2009 data_co = (char*) malloc(opsize);
2010 data_co_ptr = data_co;
2011 ptr = (char*) msg->data;
2012 for (i = 0; i < argc; i++) {
2013 argv[i] = (lo_arg *) data_co_ptr;
2014 lo_coerce((lo_type)it->typespec[i], (lo_arg *) data_co_ptr,
2015 (lo_type)types[i], (lo_arg *) ptr);
2016 data_co_ptr +=
2017 lo_arg_size((lo_type)it->typespec[i], data_co_ptr);
2018 ptr += lo_arg_size((lo_type)types[i], ptr);
2019 }
2020 }
2021
2022 /* Send wildcard path to generic handler, expanded path
2023 to others.
2024 */
2025 pptr = path;
2026 if (it->path)
2027 pptr = it->path;
2028 ret = it->handler(pptr, it->typespec, argv, argc, msg,
2029 it->user_data);
2030 free(argv);
2031 free(data_co);
2032 argv = NULL;
2033 }
2034
2035 if (ret == 0 && !pattern) {
2036 break;
2037 }
2038 }
2039 }
2040
2041 /* If we find no matching methods, check for protocol level stuff */
2042 if (ret == 1 && s->protocol == LO_UDP) {
2043 char *pos = (char*) strrchr(path, '/');
2044
2045 /* if its a method enumeration call */
2046 if (pos && *(pos + 1) == '\0') {
2047 lo_message reply = lo_message_new();
2048 int len = (int) strlen(path);
2049 lo_strlist *sl = NULL, *slit, *slnew, *slend;
2050
2051 lo_arg **argv = msg->argv;
2052 if (!strcmp(types, "i") && argv != NULL) {
2053 lo_message_add_int32(reply, argv[0]->i);
2054 }
2055 lo_message_add_string(reply, path);
2056
2057 for (it = s->first; it; it = it->next) {
2058 /* If paths match */
2059 if (it->path && !strncmp(path, it->path, len)) {
2060 char *tmp;
2061 char *sec;
2062
2063 int tmplen = (int) strlen(it->path + len) + 1;
2064 tmp = (char*) malloc(strlen(it->path + len) + 1);
2065 strncpy(tmp, it->path + len, tmplen);
2066 tmp[tmplen-1]=0;
2067 sec = strchr(tmp, '/');
2068 if (sec)
2069 *sec = '\0';
2070 slend = sl;
2071 for (slit = sl; slit; slend = slit, slit = slit->next) {
2072 if (!strcmp(slit->str, tmp)) {
2073 free(tmp);
2074 tmp = NULL;
2075 break;
2076 }
2077 }
2078 if (tmp) {
2079 slnew = (lo_strlist *) calloc(1, sizeof(lo_strlist));
2080 slnew->str = tmp;
2081 slnew->next = NULL;
2082 if (!slend) {
2083 sl = slnew;
2084 } else {
2085 slend->next = slnew;
2086 }
2087 }
2088 }
2089 }
2090
2091 slit = sl;
2092 while (slit) {
2093 lo_message_add_string(reply, slit->str);
2094 slnew = slit;
2095 slit = slit->next;
2096 free(slnew->str);
2097 free(slnew);
2098 }
2099 lo_send_message(src, "#reply", reply);
2100 lo_message_free(reply);
2101 }
2102 }
2103
2104 if (src) lo_address_free(src);
2105 msg->source = NULL;
2106 }
2107
2108 int lo_server_events_pending(lo_server s)
2109 {
2110 return s->queued != 0;
2111 }
2112
2113 static void queue_data(lo_server s, lo_timetag ts, const char *path,
2114 lo_message msg, int sock)
2115 {
2116 /* insert blob into future dispatch queue */
2117 queued_msg_list *it = (queued_msg_list *) s->queued;
2118 queued_msg_list *prev = NULL;
2119 queued_msg_list *ins = (queued_msg_list *)
2120 calloc(1, sizeof(queued_msg_list));
2121
2122 ins->ts = ts;
2123 ins->path = strdup(path);
2124 ins->msg = msg;
2125 ins->sock = sock;
2126
2127 while (it) {
2128 if (lo_timetag_diff(it->ts, ts) > 0.0) {
2129 if (prev) {
2130 prev->next = ins;
2131 } else {
2132 s->queued = ins;
2133 ins->next = NULL;
2134 }
2135 ins->next = it;
2136
2137 return;
2138 }
2139 prev = it;
2140 it = (queued_msg_list *) it->next;
2141 }
2142
2143 /* fell through, so this event is last */
2144 if (prev) {
2145 prev->next = ins;
2146 } else {
2147 s->queued = ins;
2148 }
2149 ins->next = NULL;
2150 }
2151
2152 static int dispatch_queued(lo_server s, int dispatch_all)
2153 {
2154 queued_msg_list *head = (queued_msg_list *) s->queued;
2155 queued_msg_list *tailhead;
2156 lo_timetag disp_time;
2157
2158 if (!head) {
2159 lo_throw(s, LO_INT_ERR, "attempted to dispatch with empty queue",
2160 "timeout");
2161 return 1;
2162 }
2163
2164 disp_time = head->ts;
2165
2166 do {
2167 char *path;
2168 lo_message msg;
2169 int sock;
2170 tailhead = (queued_msg_list *) head->next;
2171 path = ((queued_msg_list *) s->queued)->path;
2172 msg = ((queued_msg_list *) s->queued)->msg;
2173 sock = ((queued_msg_list *) s->queued)->sock;
2174 dispatch_method(s, path, msg, sock);
2175 free(path);
2176 lo_message_free(msg);
2177 free((queued_msg_list *) s->queued);
2178
2179 s->queued = tailhead;
2180 head = tailhead;
2181 } while (head &&
2182 (lo_timetag_diff(head->ts, disp_time) < FLT_EPSILON || dispatch_all));
2183
2184 return 0;
2185 }
2186
2187 lo_method lo_server_add_method(lo_server s, const char *path,
2188 const char *typespec, lo_method_handler h,
2189 const void *user_data)
2190 {
2191 lo_method m = (lo_method) calloc(1, sizeof(struct _lo_method));
2192 lo_method it;
2193
2194 m->has_pattern = lo_string_contains_pattern(path);
2195
2196 if (path) {
2197 m->path = strdup(path);
2198 } else {
2199 m->path = NULL;
2200 }
2201
2202 if (typespec) {
2203 m->typespec = strdup(typespec);
2204 } else {
2205 m->typespec = NULL;
2206 }
2207
2208 m->handler = h;
2209 m->user_data = (char*) user_data;
2210 m->next = NULL;
2211
2212 /* append the new method to the list */
2213 if (!s->first) {
2214 s->first = m;
2215 } else {
2216 /* get to the last member of the list */
2217 for (it = s->first; it->next; it = it->next);
2218 it->next = m;
2219 }
2220
2221 return m;
2222 }
2223
2224 void lo_server_del_method(lo_server s, const char *path,
2225 const char *typespec)
2226 {
2227 lo_method it, prev, next;
2228 int pattern = 0;
2229
2230 if (!s->first)
2231 return;
2232 if (path)
2233 pattern = lo_string_contains_pattern(path);
2234
2235 it = s->first;
2236 prev = it;
2237 while (it) {
2238 /* incase we free it */
2239 next = it->next;
2240
2241 /* If paths match or handler is wildcard */
2242 if ((it->path == path) ||
2243 (path && it->path && !strcmp(path, it->path)) ||
2244 (pattern && it->path && lo_pattern_match(it->path, path))) {
2245 /* If types match or handler is wildcard */
2246 if ((it->typespec == typespec) ||
2247 (typespec && it->typespec
2248 && !strcmp(typespec, it->typespec))
2249 ) {
2250 /* Take care when removing the head. */
2251 if (it == s->first) {
2252 s->first = it->next;
2253 } else {
2254 prev->next = it->next;
2255 }
2256 next = it->next;
2257 free((void *) it->path);
2258 free((void *) it->typespec);
2259 free(it);
2260 it = prev;
2261 }
2262 }
2263 prev = it;
2264 if (it)
2265 it = next;
2266 }
2267 }
2268
2269 int lo_server_del_lo_method(lo_server s, lo_method m)
2270 {
2271 lo_method it, prev, next;
2272
2273 if (!s->first)
2274 return 1;
2275
2276 it = s->first;
2277 prev = it;
2278 while (it) {
2279 /* incase we free it */
2280 next = it->next;
2281
2282 if (it == m) {
2283 /* Take care when removing the head. */
2284 if (it == s->first) {
2285 s->first = it->next;
2286 } else {
2287 prev->next = it->next;
2288 }
2289 free((void *) it->path);
2290 free((void *) it->typespec);
2291 free(it);
2292 return 0;
2293 }
2294 prev = it;
2295 if (it)
2296 it = next;
2297 }
2298 return 1;
2299 }
2300
2301 int lo_server_add_bundle_handlers(lo_server s,
2302 lo_bundle_start_handler sh,
2303 lo_bundle_end_handler eh,
2304 void *user_data)
2305 {
2306 s->bundle_start_handler = sh;
2307 s->bundle_end_handler = eh;
2308 s->bundle_handler_user_data = user_data;
2309 return 0;
2310 }
2311
2312 int lo_server_get_socket_fd(lo_server s)
2313 {
2314 if (s->protocol != LO_UDP && s->protocol != LO_TCP
2315 #if !defined(_WIN32) && !defined(_MSC_VER)
2316 && s->protocol != LO_UNIX
2317 #endif
2318 ) {
2319 return -1; /* assume it is not supported */
2320 }
2321 return s->sockets[0].fd;
2322 }
2323
2324 int lo_server_get_port(lo_server s)
2325 {
2326 if (!s) {
2327 return 0;
2328 }
2329
2330 return s->port;
2331 }
2332
2333 int lo_server_get_protocol(lo_server s)
2334 {
2335 if (!s) {
2336 return -1;
2337 }
2338
2339 return s->protocol;
2340 }
2341
2342
2343 char *lo_server_get_url(lo_server s)
2344 {
2345 int ret = 0;
2346 char *buf;
2347
2348 if (!s) {
2349 return NULL;
2350 }
2351
2352 if (s->protocol == LO_UDP || s->protocol == LO_TCP) {
2353 const char *proto = s->protocol == LO_UDP ? "udp" : "tcp";
2354
2355 if (!s->hostname)
2356 lo_server_resolve_hostname(s);
2357
2358 #ifndef _MSC_VER
2359 ret =
2360 snprintf(NULL, 0, "osc.%s://%s:%d/", proto, s->hostname,
2361 s->port);
2362 #endif
2363 if (ret <= 0) {
2364 /* this libc is not C99 compliant, guess a size */
2365 ret = 1023;
2366 }
2367 buf = (char*) malloc((ret + 2) * sizeof(char));
2368 snprintf(buf, ret + 1, "osc.%s://%s:%d/", proto, s->hostname,
2369 s->port);
2370
2371 return buf;
2372 }
2373 #if !defined(_WIN32) && !defined(_MSC_VER)
2374 else if (s->protocol == LO_UNIX) {
2375 ret = snprintf(NULL, 0, "osc.unix:///%s", s->path);
2376 if (ret <= 0) {
2377 /* this libc is not C99 compliant, guess a size */
2378 ret = 1023;
2379 }
2380 buf = (char*) malloc((ret + 2) * sizeof(char));
2381 snprintf(buf, ret + 1, "osc.unix:///%s", s->path);
2382
2383 return buf;
2384 }
2385 #endif
2386 return NULL;
2387 }
2388
2389 void lo_server_pp(lo_server s)
2390 {
2391 lo_method it;
2392
2393 printf("socket: %d\n\n", s->sockets[0].fd);
2394 printf("Methods\n");
2395 for (it = s->first; it; it = it->next) {
2396 printf("\n");
2397 lo_method_pp_prefix(it, " ");
2398 }
2399 }
2400
2401 static int lo_can_coerce_spec(const char *a, const char *b)
2402 {
2403 unsigned int i;
2404
2405 if (strlen(a) != strlen(b)) {
2406 return 0;
2407 }
2408
2409 for (i = 0; a[i]; i++) {
2410 if (!lo_can_coerce(a[i], b[i])) {
2411 return 0;
2412 }
2413 }
2414
2415 return 1;
2416 }
2417
2418 static int lo_can_coerce(char a, char b)
2419 {
2420 return
2421 ((a == b) ||
2422 (lo_is_numerical_type((lo_type) a) &&
2423 lo_is_numerical_type((lo_type) b)) ||
2424 (lo_is_string_type((lo_type) a) &&
2425 lo_is_string_type((lo_type) b)));
2426 }
2427
2428 // Context for error handler
2429 void *lo_error_context;
2430 #ifdef ENABLE_THREADS
2431 #ifdef HAVE_LIBPTHREAD
2432 pthread_mutex_t lo_error_context_mutex = PTHREAD_MUTEX_INITIALIZER;
2433 #else
2434 #ifdef HAVE_WIN32_THREADS
2435 CRITICAL_SECTION lo_error_context_mutex = {(void*)-1,-1,0,0,0,0};
2436 #endif
2437 #endif
2438 #endif
2439
2440 void lo_throw(lo_server s, int errnum, const char *message,
2441 const char *path)
2442 {
2443 if (s->err_h) {
2444 #ifdef ENABLE_THREADS
2445 #ifdef HAVE_LIBPTHREAD
2446 pthread_mutex_lock(&lo_error_context_mutex);
2447 #else
2448 #ifdef HAVE_WIN32_THREADS
2449 EnterCriticalSection (&lo_error_context_mutex);
2450 #endif
2451 #endif
2452 #endif
2453 lo_error_context = s->error_user_data;
2454 (*s->err_h) (errnum, message, path);
2455 #ifdef ENABLE_THREADS
2456 #ifdef HAVE_LIBPTHREAD
2457 pthread_mutex_unlock (&lo_error_context_mutex);
2458 #else
2459 #ifdef HAVE_WIN32_THREADS
2460 LeaveCriticalSection (&lo_error_context_mutex);
2461 #endif
2462 #endif
2463 #endif
2464 }
2465 }
2466
2467 void *lo_error_get_context()
2468 {
2469 return lo_error_context;
2470 }
2471
2472 void lo_server_set_error_context(lo_server s, void *user_data)
2473 {
2474 s->error_user_data = user_data;
2475 }
2476
2477 int lo_server_max_msg_size(lo_server s, int req_size)
2478 {
2479 if (req_size == 0)
2480 return s->max_msg_size;
2481
2482 if (s->protocol == LO_UDP) {
2483 if (req_size > 65535)
2484 req_size = 65535;
2485
2486 if (req_size < 0)
2487 return s->max_msg_size;
2488 }
2489 else if (s->protocol == LO_TCP)
2490 {
2491 // TODO: We could potentially shrink the TCP buffers here
2492 // if req_size < buffer_size for any open sockets, but
2493 // care must be taken to clean up any data already in the
2494 // buffers.
2495 }
2496
2497 s->max_msg_size = req_size;
2498
2499 return s->max_msg_size;
2500 }
2501
2502 /* vi:set ts=8 sts=4 sw=4: */