Statistics
| Branch: | Revision:

root / net / socket.c @ a96ed02f

History | View | Annotate | Download (18.9 kB)

1
/*
2
 * QEMU System Emulator
3
 *
4
 * Copyright (c) 2003-2008 Fabrice Bellard
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include "net/socket.h"
25

    
26
#include "config-host.h"
27

    
28
#include "net.h"
29
#include "monitor.h"
30
#include "qemu-char.h"
31
#include "qemu-common.h"
32
#include "qemu-error.h"
33
#include "qemu-option.h"
34
#include "qemu_socket.h"
35

    
36
typedef struct NetSocketState {
37
    NetClientState nc;
38
    int listen_fd;
39
    int fd;
40
    int state; /* 0 = getting length, 1 = getting data */
41
    unsigned int index;
42
    unsigned int packet_len;
43
    uint8_t buf[4096];
44
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
45
} NetSocketState;
46

    
47
static void net_socket_accept(void *opaque);
48

    
49
/* XXX: we consider we can send the whole packet without blocking */
50
static ssize_t net_socket_receive(NetClientState *nc, const uint8_t *buf, size_t size)
51
{
52
    NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
53
    uint32_t len;
54
    len = htonl(size);
55

    
56
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
57
    return send_all(s->fd, buf, size);
58
}
59

    
60
static ssize_t net_socket_receive_dgram(NetClientState *nc, const uint8_t *buf, size_t size)
61
{
62
    NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
63

    
64
    return sendto(s->fd, (const void *)buf, size, 0,
65
                  (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
66
}
67

    
68
static void net_socket_send(void *opaque)
69
{
70
    NetSocketState *s = opaque;
71
    int size, err;
72
    unsigned l;
73
    uint8_t buf1[4096];
74
    const uint8_t *buf;
75

    
76
    size = qemu_recv(s->fd, buf1, sizeof(buf1), 0);
77
    if (size < 0) {
78
        err = socket_error();
79
        if (err != EWOULDBLOCK)
80
            goto eoc;
81
    } else if (size == 0) {
82
        /* end of connection */
83
    eoc:
84
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
85
        if (s->listen_fd != -1) {
86
            qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
87
        }
88
        closesocket(s->fd);
89

    
90
        s->fd = -1;
91
        s->state = 0;
92
        s->index = 0;
93
        s->packet_len = 0;
94
        s->nc.link_down = true;
95
        memset(s->buf, 0, sizeof(s->buf));
96
        memset(s->nc.info_str, 0, sizeof(s->nc.info_str));
97

    
98
        return;
99
    }
100
    buf = buf1;
101
    while (size > 0) {
102
        /* reassemble a packet from the network */
103
        switch(s->state) {
104
        case 0:
105
            l = 4 - s->index;
106
            if (l > size)
107
                l = size;
108
            memcpy(s->buf + s->index, buf, l);
109
            buf += l;
110
            size -= l;
111
            s->index += l;
112
            if (s->index == 4) {
113
                /* got length */
114
                s->packet_len = ntohl(*(uint32_t *)s->buf);
115
                s->index = 0;
116
                s->state = 1;
117
            }
118
            break;
119
        case 1:
120
            l = s->packet_len - s->index;
121
            if (l > size)
122
                l = size;
123
            if (s->index + l <= sizeof(s->buf)) {
124
                memcpy(s->buf + s->index, buf, l);
125
            } else {
126
                fprintf(stderr, "serious error: oversized packet received,"
127
                    "connection terminated.\n");
128
                s->state = 0;
129
                goto eoc;
130
            }
131

    
132
            s->index += l;
133
            buf += l;
134
            size -= l;
135
            if (s->index >= s->packet_len) {
136
                qemu_send_packet(&s->nc, s->buf, s->packet_len);
137
                s->index = 0;
138
                s->state = 0;
139
            }
140
            break;
141
        }
142
    }
143
}
144

    
145
static void net_socket_send_dgram(void *opaque)
146
{
147
    NetSocketState *s = opaque;
148
    int size;
149

    
150
    size = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
151
    if (size < 0)
152
        return;
153
    if (size == 0) {
154
        /* end of connection */
155
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
156
        return;
157
    }
158
    qemu_send_packet(&s->nc, s->buf, size);
159
}
160

    
161
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr, struct in_addr *localaddr)
162
{
163
    struct ip_mreq imr;
164
    int fd;
165
    int val, ret;
166
#ifdef __OpenBSD__
167
    unsigned char loop;
168
#else
169
    int loop;
170
#endif
171

    
172
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
173
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) "
174
                "does not contain a multicast address\n",
175
                inet_ntoa(mcastaddr->sin_addr),
176
                (int)ntohl(mcastaddr->sin_addr.s_addr));
177
        return -1;
178

    
179
    }
180
    fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
181
    if (fd < 0) {
182
        perror("socket(PF_INET, SOCK_DGRAM)");
183
        return -1;
184
    }
185

    
186
    val = 1;
187
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
188
                   (const char *)&val, sizeof(val));
189
    if (ret < 0) {
190
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
191
        goto fail;
192
    }
193

    
194
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
195
    if (ret < 0) {
196
        perror("bind");
197
        goto fail;
198
    }
199

    
200
    /* Add host to multicast group */
201
    imr.imr_multiaddr = mcastaddr->sin_addr;
202
    if (localaddr) {
203
        imr.imr_interface = *localaddr;
204
    } else {
205
        imr.imr_interface.s_addr = htonl(INADDR_ANY);
206
    }
207

    
208
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
209
                     (const char *)&imr, sizeof(struct ip_mreq));
210
    if (ret < 0) {
211
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
212
        goto fail;
213
    }
214

    
215
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
216
    loop = 1;
217
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
218
                   (const char *)&loop, sizeof(loop));
219
    if (ret < 0) {
220
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
221
        goto fail;
222
    }
223

    
224
    /* If a bind address is given, only send packets from that address */
225
    if (localaddr != NULL) {
226
        ret = setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF,
227
                         (const char *)localaddr, sizeof(*localaddr));
228
        if (ret < 0) {
229
            perror("setsockopt(IP_MULTICAST_IF)");
230
            goto fail;
231
        }
232
    }
233

    
234
    socket_set_nonblock(fd);
235
    return fd;
236
fail:
237
    if (fd >= 0)
238
        closesocket(fd);
239
    return -1;
240
}
241

    
242
static void net_socket_cleanup(NetClientState *nc)
243
{
244
    NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
245
    if (s->fd != -1) {
246
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
247
        close(s->fd);
248
        s->fd = -1;
249
    }
250
    if (s->listen_fd != -1) {
251
        qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
252
        closesocket(s->listen_fd);
253
        s->listen_fd = -1;
254
    }
255
}
256

    
257
static NetClientInfo net_dgram_socket_info = {
258
    .type = NET_CLIENT_OPTIONS_KIND_SOCKET,
259
    .size = sizeof(NetSocketState),
260
    .receive = net_socket_receive_dgram,
261
    .cleanup = net_socket_cleanup,
262
};
263

    
264
static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,
265
                                                const char *model,
266
                                                const char *name,
267
                                                int fd, int is_connected)
268
{
269
    struct sockaddr_in saddr;
270
    int newfd;
271
    socklen_t saddr_len;
272
    NetClientState *nc;
273
    NetSocketState *s;
274

    
275
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
276
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
277
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
278
     */
279

    
280
    if (is_connected) {
281
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
282
            /* must be bound */
283
            if (saddr.sin_addr.s_addr == 0) {
284
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, "
285
                        "cannot setup multicast dst addr\n", fd);
286
                goto err;
287
            }
288
            /* clone dgram socket */
289
            newfd = net_socket_mcast_create(&saddr, NULL);
290
            if (newfd < 0) {
291
                /* error already reported by net_socket_mcast_create() */
292
                goto err;
293
            }
294
            /* clone newfd to fd, close newfd */
295
            dup2(newfd, fd);
296
            close(newfd);
297

    
298
        } else {
299
            fprintf(stderr,
300
                    "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
301
                    fd, strerror(errno));
302
            goto err;
303
        }
304
    }
305

    
306
    nc = qemu_new_net_client(&net_dgram_socket_info, peer, model, name);
307

    
308
    snprintf(nc->info_str, sizeof(nc->info_str),
309
            "socket: fd=%d (%s mcast=%s:%d)",
310
            fd, is_connected ? "cloned" : "",
311
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
312

    
313
    s = DO_UPCAST(NetSocketState, nc, nc);
314

    
315
    s->fd = fd;
316
    s->listen_fd = -1;
317

    
318
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
319

    
320
    /* mcast: save bound address as dst */
321
    if (is_connected) {
322
        s->dgram_dst = saddr;
323
    }
324

    
325
    return s;
326

    
327
err:
328
    closesocket(fd);
329
    return NULL;
330
}
331

    
332
static void net_socket_connect(void *opaque)
333
{
334
    NetSocketState *s = opaque;
335
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
336
}
337

    
338
static NetClientInfo net_socket_info = {
339
    .type = NET_CLIENT_OPTIONS_KIND_SOCKET,
340
    .size = sizeof(NetSocketState),
341
    .receive = net_socket_receive,
342
    .cleanup = net_socket_cleanup,
343
};
344

    
345
static NetSocketState *net_socket_fd_init_stream(NetClientState *peer,
346
                                                 const char *model,
347
                                                 const char *name,
348
                                                 int fd, int is_connected)
349
{
350
    NetClientState *nc;
351
    NetSocketState *s;
352

    
353
    nc = qemu_new_net_client(&net_socket_info, peer, model, name);
354

    
355
    snprintf(nc->info_str, sizeof(nc->info_str), "socket: fd=%d", fd);
356

    
357
    s = DO_UPCAST(NetSocketState, nc, nc);
358

    
359
    s->fd = fd;
360
    s->listen_fd = -1;
361

    
362
    if (is_connected) {
363
        net_socket_connect(s);
364
    } else {
365
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
366
    }
367
    return s;
368
}
369

    
370
static NetSocketState *net_socket_fd_init(NetClientState *peer,
371
                                          const char *model, const char *name,
372
                                          int fd, int is_connected)
373
{
374
    int so_type = -1, optlen=sizeof(so_type);
375

    
376
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
377
        (socklen_t *)&optlen)< 0) {
378
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n",
379
                fd);
380
        closesocket(fd);
381
        return NULL;
382
    }
383
    switch(so_type) {
384
    case SOCK_DGRAM:
385
        return net_socket_fd_init_dgram(peer, model, name, fd, is_connected);
386
    case SOCK_STREAM:
387
        return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
388
    default:
389
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
390
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
391
        return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
392
    }
393
    return NULL;
394
}
395

    
396
static void net_socket_accept(void *opaque)
397
{
398
    NetSocketState *s = opaque;
399
    struct sockaddr_in saddr;
400
    socklen_t len;
401
    int fd;
402

    
403
    for(;;) {
404
        len = sizeof(saddr);
405
        fd = qemu_accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
406
        if (fd < 0 && errno != EINTR) {
407
            return;
408
        } else if (fd >= 0) {
409
            qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
410
            break;
411
        }
412
    }
413

    
414
    s->fd = fd;
415
    s->nc.link_down = false;
416
    net_socket_connect(s);
417
    snprintf(s->nc.info_str, sizeof(s->nc.info_str),
418
             "socket: connection from %s:%d",
419
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
420
}
421

    
422
static int net_socket_listen_init(NetClientState *peer,
423
                                  const char *model,
424
                                  const char *name,
425
                                  const char *host_str)
426
{
427
    NetClientState *nc;
428
    NetSocketState *s;
429
    struct sockaddr_in saddr;
430
    int fd, val, ret;
431

    
432
    if (parse_host_port(&saddr, host_str) < 0)
433
        return -1;
434

    
435
    fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
436
    if (fd < 0) {
437
        perror("socket");
438
        return -1;
439
    }
440
    socket_set_nonblock(fd);
441

    
442
    /* allow fast reuse */
443
    val = 1;
444
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
445

    
446
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
447
    if (ret < 0) {
448
        perror("bind");
449
        closesocket(fd);
450
        return -1;
451
    }
452
    ret = listen(fd, 0);
453
    if (ret < 0) {
454
        perror("listen");
455
        closesocket(fd);
456
        return -1;
457
    }
458

    
459
    nc = qemu_new_net_client(&net_socket_info, peer, model, name);
460
    s = DO_UPCAST(NetSocketState, nc, nc);
461
    s->fd = -1;
462
    s->listen_fd = fd;
463
    s->nc.link_down = true;
464

    
465
    qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
466
    return 0;
467
}
468

    
469
static int net_socket_connect_init(NetClientState *peer,
470
                                   const char *model,
471
                                   const char *name,
472
                                   const char *host_str)
473
{
474
    NetSocketState *s;
475
    int fd, connected, ret, err;
476
    struct sockaddr_in saddr;
477

    
478
    if (parse_host_port(&saddr, host_str) < 0)
479
        return -1;
480

    
481
    fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
482
    if (fd < 0) {
483
        perror("socket");
484
        return -1;
485
    }
486
    socket_set_nonblock(fd);
487

    
488
    connected = 0;
489
    for(;;) {
490
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
491
        if (ret < 0) {
492
            err = socket_error();
493
            if (err == EINTR || err == EWOULDBLOCK) {
494
            } else if (err == EINPROGRESS) {
495
                break;
496
#ifdef _WIN32
497
            } else if (err == WSAEALREADY || err == WSAEINVAL) {
498
                break;
499
#endif
500
            } else {
501
                perror("connect");
502
                closesocket(fd);
503
                return -1;
504
            }
505
        } else {
506
            connected = 1;
507
            break;
508
        }
509
    }
510
    s = net_socket_fd_init(peer, model, name, fd, connected);
511
    if (!s)
512
        return -1;
513
    snprintf(s->nc.info_str, sizeof(s->nc.info_str),
514
             "socket: connect to %s:%d",
515
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
516
    return 0;
517
}
518

    
519
static int net_socket_mcast_init(NetClientState *peer,
520
                                 const char *model,
521
                                 const char *name,
522
                                 const char *host_str,
523
                                 const char *localaddr_str)
524
{
525
    NetSocketState *s;
526
    int fd;
527
    struct sockaddr_in saddr;
528
    struct in_addr localaddr, *param_localaddr;
529

    
530
    if (parse_host_port(&saddr, host_str) < 0)
531
        return -1;
532

    
533
    if (localaddr_str != NULL) {
534
        if (inet_aton(localaddr_str, &localaddr) == 0)
535
            return -1;
536
        param_localaddr = &localaddr;
537
    } else {
538
        param_localaddr = NULL;
539
    }
540

    
541
    fd = net_socket_mcast_create(&saddr, param_localaddr);
542
    if (fd < 0)
543
        return -1;
544

    
545
    s = net_socket_fd_init(peer, model, name, fd, 0);
546
    if (!s)
547
        return -1;
548

    
549
    s->dgram_dst = saddr;
550

    
551
    snprintf(s->nc.info_str, sizeof(s->nc.info_str),
552
             "socket: mcast=%s:%d",
553
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
554
    return 0;
555

    
556
}
557

    
558
static int net_socket_udp_init(NetClientState *peer,
559
                                 const char *model,
560
                                 const char *name,
561
                                 const char *rhost,
562
                                 const char *lhost)
563
{
564
    NetSocketState *s;
565
    int fd, val, ret;
566
    struct sockaddr_in laddr, raddr;
567

    
568
    if (parse_host_port(&laddr, lhost) < 0) {
569
        return -1;
570
    }
571

    
572
    if (parse_host_port(&raddr, rhost) < 0) {
573
        return -1;
574
    }
575

    
576
    fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
577
    if (fd < 0) {
578
        perror("socket(PF_INET, SOCK_DGRAM)");
579
        return -1;
580
    }
581
    val = 1;
582
    ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
583
                   (const char *)&val, sizeof(val));
584
    if (ret < 0) {
585
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
586
        closesocket(fd);
587
        return -1;
588
    }
589
    ret = bind(fd, (struct sockaddr *)&laddr, sizeof(laddr));
590
    if (ret < 0) {
591
        perror("bind");
592
        closesocket(fd);
593
        return -1;
594
    }
595

    
596
    s = net_socket_fd_init(peer, model, name, fd, 0);
597
    if (!s) {
598
        return -1;
599
    }
600

    
601
    s->dgram_dst = raddr;
602

    
603
    snprintf(s->nc.info_str, sizeof(s->nc.info_str),
604
             "socket: udp=%s:%d",
605
             inet_ntoa(raddr.sin_addr), ntohs(raddr.sin_port));
606
    return 0;
607
}
608

    
609
int net_init_socket(const NetClientOptions *opts, const char *name,
610
                    NetClientState *peer)
611
{
612
    const NetdevSocketOptions *sock;
613

    
614
    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_SOCKET);
615
    sock = opts->socket;
616

    
617
    if (sock->has_fd + sock->has_listen + sock->has_connect + sock->has_mcast +
618
        sock->has_udp != 1) {
619
        error_report("exactly one of fd=, listen=, connect=, mcast= or udp="
620
                     " is required");
621
        return -1;
622
    }
623

    
624
    if (sock->has_localaddr && !sock->has_mcast && !sock->has_udp) {
625
        error_report("localaddr= is only valid with mcast= or udp=");
626
        return -1;
627
    }
628

    
629
    if (sock->has_fd) {
630
        int fd;
631

    
632
        fd = monitor_handle_fd_param(cur_mon, sock->fd);
633
        if (fd == -1 || !net_socket_fd_init(peer, "socket", name, fd, 1)) {
634
            return -1;
635
        }
636
        return 0;
637
    }
638

    
639
    if (sock->has_listen) {
640
        if (net_socket_listen_init(peer, "socket", name, sock->listen) == -1) {
641
            return -1;
642
        }
643
        return 0;
644
    }
645

    
646
    if (sock->has_connect) {
647
        if (net_socket_connect_init(peer, "socket", name, sock->connect) ==
648
            -1) {
649
            return -1;
650
        }
651
        return 0;
652
    }
653

    
654
    if (sock->has_mcast) {
655
        /* if sock->localaddr is missing, it has been initialized to "all bits
656
         * zero" */
657
        if (net_socket_mcast_init(peer, "socket", name, sock->mcast,
658
            sock->localaddr) == -1) {
659
            return -1;
660
        }
661
        return 0;
662
    }
663

    
664
    assert(sock->has_udp);
665
    if (!sock->has_localaddr) {
666
        error_report("localaddr= is mandatory with udp=");
667
        return -1;
668
    }
669
    if (net_socket_udp_init(peer, "udp", name, sock->udp, sock->localaddr) ==
670
        -1) {
671
        return -1;
672
    }
673
    return 0;
674
}