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