x_net.c 16 KB
Newer Older
Miller Puckette's avatar
Miller Puckette committed
1 2 3 4 5 6 7 8 9 10 11
/* Copyright (c) 1997-1999 Miller Puckette.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.  */

/* network */

#include "m_pd.h"
#include "s_stuff.h"

#include <sys/types.h>
#include <string.h>
12
#ifdef _WIN32
Miller Puckette's avatar
Miller Puckette committed
13 14 15 16 17 18 19 20 21 22
#include <winsock.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <stdio.h>
#define SOCKET_ERROR -1
#endif

23 24 25 26 27 28 29 30
#ifdef _WIN32
# include <malloc.h> /* MSVC or mingw on windows */
#elif defined(__linux__) || defined(__APPLE__)
# include <alloca.h> /* linux, mac, mingw, cygwin */
#else
# include <stdlib.h> /* BSDs for example */
#endif

Miller Puckette's avatar
Miller Puckette committed
31 32 33 34 35
static t_class *netsend_class;

typedef struct _netsend
{
    t_object x_obj;
36 37 38
    t_outlet *x_msgout;
    t_outlet *x_connectout;
    int x_sockfd;
Miller Puckette's avatar
Miller Puckette committed
39
    int x_protocol;
40
    int x_bin;
Miller Puckette's avatar
Miller Puckette committed
41 42
} t_netsend;

43 44 45 46 47 48 49 50 51 52 53 54 55 56
static t_class *netreceive_class;

typedef struct _netreceive
{
    t_netsend x_ns;
    int x_nconnections;
    int x_sockfd;
    int *x_connections;
    int x_old;
} t_netreceive;

static void netreceive_notify(t_netreceive *x, int fd);

static void *netsend_new(t_symbol *s, int argc, t_atom *argv)
Miller Puckette's avatar
Miller Puckette committed
57 58 59
{
    t_netsend *x = (t_netsend *)pd_new(netsend_class);
    outlet_new(&x->x_obj, &s_float);
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    x->x_protocol = SOCK_STREAM;
    x->x_bin = 0;
    if (argc && argv->a_type == A_FLOAT)
    {
        x->x_protocol = (argv->a_w.w_float != 0 ? SOCK_DGRAM : SOCK_STREAM);
        argc = 0;
    }
    else while (argc && argv->a_type == A_SYMBOL &&
        *argv->a_w.w_symbol->s_name == '-')
    {
        if (!strcmp(argv->a_w.w_symbol->s_name, "-b"))
            x->x_bin = 1;
        else if (!strcmp(argv->a_w.w_symbol->s_name, "-u"))
            x->x_protocol = SOCK_DGRAM;
        else
        {
            pd_error(x, "netsend: unknown flag ...");
            postatom(argc, argv); endpost();
        }
        argc--; argv++;
    }
    if (argc)
    {
        pd_error(x, "netsend: extra arguments ignored:");
        postatom(argc, argv); endpost();
    }
    x->x_sockfd = -1;
    x->x_msgout = outlet_new(&x->x_obj, &s_anything);
Miller Puckette's avatar
Miller Puckette committed
88 89 90
    return (x);
}

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
static void netsend_readbin(t_netsend *x, int fd)
{
    unsigned char inbuf[MAXPDSTRING];
    int ret = recv(fd, inbuf, MAXPDSTRING, 0), i;
    if (!x->x_msgout)
    {
        bug("netsend_readbin");
        return;
    }
    if (ret <= 0)
    {
        if (ret < 0)
            sys_sockerror("recv");
        sys_rmpollfn(fd);
        sys_closesocket(fd);
        if (x->x_obj.ob_pd == netreceive_class)
            netreceive_notify((t_netreceive *)x, fd);
    }
    else if (x->x_protocol == SOCK_DGRAM)
    {
        t_atom *ap = (t_atom *)alloca(ret * sizeof(t_atom));
        for (i = 0; i < ret; i++)
            SETFLOAT(ap+i, inbuf[i]);
        outlet_list(x->x_msgout, 0, ret, ap);
    }
    else
    {
        for (i = 0; i < ret; i++)
            outlet_float(x->x_msgout, inbuf[i]);
    }
}

static void netsend_doit(void *z, t_binbuf *b)
{
    t_netsend *x = (t_netsend *)z;
    int msg, natom = binbuf_getnatom(b);
    t_atom *at = binbuf_getvec(b);
    for (msg = 0; msg < natom;)
    {
        int emsg;
        for (emsg = msg; emsg < natom && at[emsg].a_type != A_COMMA
            && at[emsg].a_type != A_SEMI; emsg++)
                ;
        if (emsg > msg)
        {
            int i;
            for (i = msg; i < emsg; i++)
                if (at[i].a_type == A_DOLLAR || at[i].a_type == A_DOLLSYM)
            {
                pd_error(x, "netreceive: got dollar sign in message");
                goto nodice;
            }
            if (at[msg].a_type == A_FLOAT)
            {
                if (emsg > msg + 1)
                    outlet_list(x->x_msgout, 0, emsg-msg, at + msg);
                else outlet_float(x->x_msgout, at[msg].a_w.w_float);
            }
            else if (at[msg].a_type == A_SYMBOL)
                outlet_anything(x->x_msgout, at[msg].a_w.w_symbol,
                    emsg-msg-1, at + msg + 1);
        }
    nodice:
        msg = emsg + 1;
    }
}


Miller Puckette's avatar
Miller Puckette committed
159 160 161
static void netsend_connect(t_netsend *x, t_symbol *hostname,
    t_floatarg fportno)
{
162
    struct sockaddr_in server = {0};
Miller Puckette's avatar
Miller Puckette committed
163 164 165 166
    struct hostent *hp;
    int sockfd;
    int portno = fportno;
    int intarg;
167
    if (x->x_sockfd >= 0)
Miller Puckette's avatar
Miller Puckette committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    {
        error("netsend_connect: already connected");
        return;
    }

        /* create a socket */
    sockfd = socket(AF_INET, x->x_protocol, 0);
#if 0
    fprintf(stderr, "send socket %d\n", sockfd);
#endif
    if (sockfd < 0)
    {
        sys_sockerror("socket");
        return;
    }
    /* connect socket using hostname provided in command line */
    server.sin_family = AF_INET;
    hp = gethostbyname(hostname->s_name);
    if (hp == 0)
    {
        post("bad host?\n");
189
        sys_closesocket(sockfd);
Miller Puckette's avatar
Miller Puckette committed
190 191 192 193 194 195 196 197
        return;
    }
#if 0
    intarg = 0;
    if (setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF,
        &intarg, sizeof(intarg)) < 0)
            post("setsockopt (SO_RCVBUF) failed\n");
#endif
198 199 200 201
    intarg = 1;
    if(setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST,
                  (const void *)&intarg, sizeof(intarg)) < 0)
        post("setting SO_BROADCAST");
Miller Puckette's avatar
Miller Puckette committed
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        /* for stream (TCP) sockets, specify "nodelay" */
    if (x->x_protocol == SOCK_STREAM)
    {
        intarg = 1;
        if (setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
            (char *)&intarg, sizeof(intarg)) < 0)
                post("setsockopt (TCP_NODELAY) failed\n");
    }
    memcpy((char *)&server.sin_addr, (char *)hp->h_addr, hp->h_length);

    /* assign client port number */
    server.sin_port = htons((u_short)portno);

    post("connecting to port %d", portno);
        /* try to connect.  LATER make a separate thread to do this
        because it might block */
    if (connect(sockfd, (struct sockaddr *) &server, sizeof (server)) < 0)
    {
        sys_sockerror("connecting stream socket");
        sys_closesocket(sockfd);
        return;
    }
224 225 226 227 228 229 230 231 232 233 234 235 236
    x->x_sockfd = sockfd;
    if (x->x_msgout)    /* add polling function for return messages */
    {
        if (x->x_bin)
            sys_addpollfn(sockfd, (t_fdpollfn)netsend_readbin, x);
        else
        {
            t_socketreceiver *y =
                socketreceiver_new((void *)x, 0, netsend_doit,
                    x->x_protocol == SOCK_DGRAM);
            sys_addpollfn(sockfd, (t_fdpollfn)socketreceiver_read, y);
        }
    }
Miller Puckette's avatar
Miller Puckette committed
237 238 239 240 241
    outlet_float(x->x_obj.ob_outlet, 1);
}

static void netsend_disconnect(t_netsend *x)
{
242
    if (x->x_sockfd >= 0)
Miller Puckette's avatar
Miller Puckette committed
243
    {
244 245 246
        sys_rmpollfn(x->x_sockfd);
        sys_closesocket(x->x_sockfd);
        x->x_sockfd = -1;
Miller Puckette's avatar
Miller Puckette committed
247 248 249 250
        outlet_float(x->x_obj.ob_outlet, 0);
    }
}

251 252
static int netsend_dosend(t_netsend *x, int sockfd,
    t_symbol *s, int argc, t_atom *argv)
Miller Puckette's avatar
Miller Puckette committed
253
{
254 255 256 257 258 259 260 261 262 263 264 265
    char *buf, *bp;
    int length, sent, fail = 0;
    t_binbuf *b = 0;
    if (x->x_bin)
    {
        int i;
        buf = alloca(argc);
        for (i = 0; i < argc; i++)
            ((unsigned char *)buf)[i] = atom_getfloatarg(i, argc, argv);
        length = argc;
    }
    else
Miller Puckette's avatar
Miller Puckette committed
266 267
    {
        t_atom at;
268
        b = binbuf_new();
Miller Puckette's avatar
Miller Puckette committed
269 270 271 272
        binbuf_add(b, argc, argv);
        SETSEMI(&at);
        binbuf_add(b, 1, &at);
        binbuf_gettext(b, &buf, &length);
273 274 275 276 277 278 279 280 281 282
    }
    for (bp = buf, sent = 0; sent < length;)
    {
        static double lastwarntime;
        static double pleasewarn;
        double timebefore = sys_getrealtime();
        int res = send(sockfd, bp, length-sent, 0);
        double timeafter = sys_getrealtime();
        int late = (timeafter - timebefore > 0.005);
        if (late || pleasewarn)
Miller Puckette's avatar
Miller Puckette committed
283
        {
284
            if (timeafter > lastwarntime + 2)
Miller Puckette's avatar
Miller Puckette committed
285
            {
286 287 288 289 290
                 post("netsend/netreceive blocked %d msec",
                    (int)(1000 * ((timeafter - timebefore) +
                        pleasewarn)));
                 pleasewarn = 0;
                 lastwarntime = timeafter;
Miller Puckette's avatar
Miller Puckette committed
291
            }
292 293 294 295 296 297 298
            else if (late) pleasewarn += timeafter - timebefore;
        }
        if (res <= 0)
        {
            sys_sockerror("netsend");
            fail = 1;
            break;
Miller Puckette's avatar
Miller Puckette committed
299
        }
300 301 302 303 304 305
        else
        {
            sent += res;
            bp += res;
        }
    }
306
    /* done: */
307 308
    if (!x->x_bin)
    {
Miller Puckette's avatar
Miller Puckette committed
309 310 311
        t_freebytes(buf, length);
        binbuf_free(b);
    }
312 313 314 315 316 317 318 319 320 321 322
    return (fail);
}


static void netsend_send(t_netsend *x, t_symbol *s, int argc, t_atom *argv)
{
    if (x->x_sockfd >= 0)
    {
        if (netsend_dosend(x, x->x_sockfd, s, argc, argv))
            netsend_disconnect(x);
    }
Miller Puckette's avatar
Miller Puckette committed
323 324 325 326 327 328 329 330 331 332 333
}

static void netsend_free(t_netsend *x)
{
    netsend_disconnect(x);
}

static void netsend_setup(void)
{
    netsend_class = class_new(gensym("netsend"), (t_newmethod)netsend_new,
        (t_method)netsend_free,
334
        sizeof(t_netsend), 0, A_GIMME, 0);
Miller Puckette's avatar
Miller Puckette committed
335 336 337 338 339 340 341 342 343
    class_addmethod(netsend_class, (t_method)netsend_connect,
        gensym("connect"), A_SYMBOL, A_FLOAT, 0);
    class_addmethod(netsend_class, (t_method)netsend_disconnect,
        gensym("disconnect"), 0);
    class_addmethod(netsend_class, (t_method)netsend_send, gensym("send"),
        A_GIMME, 0);
}

/* ----------------------------- netreceive ------------------------- */
344
static void netreceive_notify(t_netreceive *x, int fd)
Miller Puckette's avatar
Miller Puckette committed
345
{
346 347
    int i;
    for (i = 0; i < x->x_nconnections; i++)
Miller Puckette's avatar
Miller Puckette committed
348
    {
349
        if (x->x_connections[i] == fd)
Miller Puckette's avatar
Miller Puckette committed
350
        {
351 352 353 354 355 356
            memmove(x->x_connections+i, x->x_connections+(i+1),
                sizeof(int) * (x->x_nconnections - (i+1)));
            x->x_connections = (int *)t_resizebytes(x->x_connections,
                x->x_nconnections * sizeof(int),
                    (x->x_nconnections-1) * sizeof(int));
            x->x_nconnections--;
Miller Puckette's avatar
Miller Puckette committed
357 358
        }
    }
359
    outlet_float(x->x_ns.x_connectout, x->x_nconnections);
Miller Puckette's avatar
Miller Puckette committed
360 361 362 363
}

static void netreceive_connectpoll(t_netreceive *x)
{
364
    int fd = accept(x->x_ns.x_sockfd, 0, 0);
Miller Puckette's avatar
Miller Puckette committed
365 366 367
    if (fd < 0) post("netreceive: accept failed");
    else
    {
368 369 370 371 372 373 374 375 376 377
        int nconnections = x->x_nconnections+1;

        x->x_connections = (int *)t_resizebytes(x->x_connections,
            x->x_nconnections * sizeof(int), nconnections * sizeof(int));
        x->x_connections[x->x_nconnections] = fd;
        if (x->x_ns.x_bin)
            sys_addpollfn(fd, (t_fdpollfn)netsend_readbin, x);
        else
        {
            t_socketreceiver *y = socketreceiver_new((void *)x,
Miller Puckette's avatar
Miller Puckette committed
378
            (t_socketnotifier)netreceive_notify,
379 380 381 382
                (x->x_ns.x_msgout ? netsend_doit : 0), 0);
            sys_addpollfn(fd, (t_fdpollfn)socketreceiver_read, y);
        }
        outlet_float(x->x_ns.x_connectout, (x->x_nconnections = nconnections));
Miller Puckette's avatar
Miller Puckette committed
383 384 385
    }
}

386
static void netreceive_closeall(t_netreceive *x)
Miller Puckette's avatar
Miller Puckette committed
387
{
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
    int i;
    for (i = 0; i < x->x_nconnections; i++)
    {
        sys_rmpollfn(x->x_connections[i]);
        sys_closesocket(x->x_connections[i]);
    }
    x->x_connections = (int *)t_resizebytes(x->x_connections,
        x->x_nconnections * sizeof(int), 0);
    x->x_nconnections = 0;
    if (x->x_ns.x_sockfd >= 0)
    {
        sys_rmpollfn(x->x_ns.x_sockfd);
        sys_closesocket(x->x_ns.x_sockfd);
    }
    x->x_ns.x_sockfd = -1;
}

static void netreceive_listen(t_netreceive *x, t_floatarg fportno)
{
    int portno = fportno, intarg;
    struct sockaddr_in server = {0};
    netreceive_closeall(x);
    if (portno <= 0)
        return;
    x->x_ns.x_sockfd = socket(AF_INET, x->x_ns.x_protocol, 0);
    if (x->x_ns.x_sockfd < 0)
Miller Puckette's avatar
Miller Puckette committed
414 415
    {
        sys_sockerror("socket");
416
        return;
Miller Puckette's avatar
Miller Puckette committed
417
    }
418 419 420
#if 0
    fprintf(stderr, "receive socket %d\n", x->x_ sockfd);
#endif
Miller Puckette's avatar
Miller Puckette committed
421 422 423 424

#if 1
        /* ask OS to allow another Pd to repoen this port after we close it. */
    intarg = 1;
425
    if (setsockopt(x->x_ns.x_sockfd, SOL_SOCKET, SO_REUSEADDR,
Miller Puckette's avatar
Miller Puckette committed
426
        (char *)&intarg, sizeof(intarg)) < 0)
427
            post("netreceive: setsockopt (SO_REUSEADDR) failed\n");
Miller Puckette's avatar
Miller Puckette committed
428 429 430
#endif
#if 0
    intarg = 0;
431
    if (setsockopt(x->x_ns.x_sockfd, SOL_SOCKET, SO_RCVBUF,
Miller Puckette's avatar
Miller Puckette committed
432 433 434
        &intarg, sizeof(intarg)) < 0)
            post("setsockopt (SO_RCVBUF) failed\n");
#endif
435 436 437 438
    intarg = 1;
    if (setsockopt(x->x_ns.x_sockfd, SOL_SOCKET, SO_BROADCAST,
        (const void *)&intarg, sizeof(intarg)) < 0)
            post("netreceive: failed to sett SO_BROADCAST");
Miller Puckette's avatar
Miller Puckette committed
439
        /* Stream (TCP) sockets are set NODELAY */
440
    if (x->x_ns.x_protocol == SOCK_STREAM)
Miller Puckette's avatar
Miller Puckette committed
441 442
    {
        intarg = 1;
443
        if (setsockopt(x->x_ns.x_sockfd, IPPROTO_TCP, TCP_NODELAY,
Miller Puckette's avatar
Miller Puckette committed
444 445 446
            (char *)&intarg, sizeof(intarg)) < 0)
                post("setsockopt (TCP_NODELAY) failed\n");
    }
447 448 449
        /* assign server port number etc */
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
Miller Puckette's avatar
Miller Puckette committed
450 451 452
    server.sin_port = htons((u_short)portno);

        /* name the socket */
453
    if (bind(x->x_ns.x_sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
Miller Puckette's avatar
Miller Puckette committed
454 455
    {
        sys_sockerror("bind");
456 457 458
        sys_closesocket(x->x_ns.x_sockfd);
        x->x_ns.x_sockfd = -1;
        return;
Miller Puckette's avatar
Miller Puckette committed
459
    }
460

461
    if (x->x_ns.x_protocol == SOCK_DGRAM)        /* datagram protocol */
Miller Puckette's avatar
Miller Puckette committed
462
    {
463 464 465 466 467 468 469 470 471 472
        if (x->x_ns.x_bin)
            sys_addpollfn(x->x_ns.x_sockfd, (t_fdpollfn)netsend_readbin, x);
        else
        {
            t_socketreceiver *y = socketreceiver_new((void *)x,
                (t_socketnotifier)netreceive_notify,
                    (x->x_ns.x_msgout ? netsend_doit : 0), 1);
            sys_addpollfn(x->x_ns.x_sockfd, (t_fdpollfn)socketreceiver_read, y);
            x->x_ns.x_connectout = 0;
        }
Miller Puckette's avatar
Miller Puckette committed
473 474 475
    }
    else        /* streaming protocol */
    {
476
        if (listen(x->x_ns.x_sockfd, 5) < 0)
Miller Puckette's avatar
Miller Puckette committed
477 478
        {
            sys_sockerror("listen");
479 480
            sys_closesocket(x->x_ns.x_sockfd);
            x->x_ns.x_sockfd = -1;
Miller Puckette's avatar
Miller Puckette committed
481 482 483
        }
        else
        {
484 485
            sys_addpollfn(x->x_ns.x_sockfd, (t_fdpollfn)netreceive_connectpoll, x);
            x->x_ns.x_connectout = outlet_new(&x->x_ns.x_obj, &s_float);
Miller Puckette's avatar
Miller Puckette committed
486 487
        }
    }
488
}
Miller Puckette's avatar
Miller Puckette committed
489

490 491 492 493 494 495 496 497 498 499 500

static void netreceive_send(t_netreceive *x,
    t_symbol *s, int argc, t_atom *argv)
{
    int i;
    for (i = 0; i < x->x_nconnections; i++)
    {
        if (netsend_dosend(&x->x_ns, x->x_connections[i], s, argc, argv))
            pd_error(x, "netreceive send message failed");
                /* should we now close the connection? */
    }
Miller Puckette's avatar
Miller Puckette committed
501 502
}

503
static void *netreceive_new(t_symbol *s, int argc, t_atom *argv)
Miller Puckette's avatar
Miller Puckette committed
504
{
505 506 507 508 509 510 511 512 513
    t_netreceive *x = (t_netreceive *)pd_new(netreceive_class);
    int portno = 0;
    x->x_ns.x_protocol = SOCK_STREAM;
    x->x_old = 0;
    x->x_ns.x_bin = 0;
    x->x_nconnections = 0;
    x->x_connections = (int *)t_getbytes(0);
    x->x_ns.x_sockfd = -1;
    if (argc && argv->a_type == A_FLOAT)
Miller Puckette's avatar
Miller Puckette committed
514
    {
515 516 517 518 519
        portno = atom_getfloatarg(0, argc, argv);
        x->x_ns.x_protocol = (atom_getfloatarg(1, argc, argv) != 0 ?
            SOCK_DGRAM : SOCK_STREAM);
        x->x_old = (!strcmp(atom_getsymbolarg(2, argc, argv)->s_name, "old"));
        argc = 0;
Miller Puckette's avatar
Miller Puckette committed
520
    }
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    else
    {
        while (argc && argv->a_type == A_SYMBOL &&
            *argv->a_w.w_symbol->s_name == '-')
        {
            if (!strcmp(argv->a_w.w_symbol->s_name, "-b"))
                x->x_ns.x_bin = 1;
            else if (!strcmp(argv->a_w.w_symbol->s_name, "-u"))
                x->x_ns.x_protocol = SOCK_DGRAM;
            else
            {
                pd_error(x, "netreceive: unknown flag ...");
                postatom(argc, argv); endpost();
            }
            argc--; argv++;
        }
    }
    if (argc && argv->a_type == A_FLOAT)
        portno = argv->a_w.w_float, argc--, argv++;
    if (argc)
    {
        pd_error(x, "netreceive: extra arguments ignored:");
        postatom(argc, argv); endpost();
    }
    if (x->x_old)
    {
        /* old style, nonsecure version */
        x->x_ns.x_msgout = 0;
    }
    else x->x_ns.x_msgout = outlet_new(&x->x_ns.x_obj, &s_anything);
        /* create a socket */
    if (portno > 0)
        netreceive_listen(x, portno);

    return (x);
Miller Puckette's avatar
Miller Puckette committed
556 557 558 559 560
}

static void netreceive_setup(void)
{
    netreceive_class = class_new(gensym("netreceive"),
561 562 563 564 565 566
        (t_newmethod)netreceive_new, (t_method)netreceive_closeall,
        sizeof(t_netreceive), 0, A_GIMME, 0);
    class_addmethod(netreceive_class, (t_method)netreceive_listen,
        gensym("listen"), A_FLOAT, 0);
    class_addmethod(netreceive_class, (t_method)netreceive_send,
        gensym("send"), A_GIMME, 0);
Miller Puckette's avatar
Miller Puckette committed
567 568 569 570 571 572 573 574
}

void x_net_setup(void)
{
    netsend_setup();
    netreceive_setup();
}