Statistics
| Branch: | Revision:

root / slirp / slirp.c @ ad0d8c4c

History | View | Annotate | Download (29.7 kB)

1
/*
2
 * libslirp glue
3
 *
4
 * Copyright (c) 2004-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 "qemu-common.h"
25
#include "qemu-char.h"
26
#include "slirp.h"
27
#include "hw/hw.h"
28

    
29
/* host address */
30
struct in_addr our_addr;
31
/* host dns address */
32
struct in_addr dns_addr;
33
/* host loopback address */
34
struct in_addr loopback_addr;
35

    
36
/* emulated hosts use the MAC addr 52:55:IP:IP:IP:IP */
37
static const uint8_t special_ethaddr[6] = {
38
    0x52, 0x55, 0x00, 0x00, 0x00, 0x00
39
};
40

    
41
static const uint8_t zero_ethaddr[6] = { 0, 0, 0, 0, 0, 0 };
42

    
43
/* XXX: suppress those select globals */
44
fd_set *global_readfds, *global_writefds, *global_xfds;
45

    
46
u_int curtime;
47
static u_int time_fasttimo, last_slowtimo;
48
static int do_slowtimo;
49

    
50
Slirp *slirp_instance;
51

    
52
#ifdef _WIN32
53

    
54
static int get_dns_addr(struct in_addr *pdns_addr)
55
{
56
    FIXED_INFO *FixedInfo=NULL;
57
    ULONG    BufLen;
58
    DWORD    ret;
59
    IP_ADDR_STRING *pIPAddr;
60
    struct in_addr tmp_addr;
61

    
62
    FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));
63
    BufLen = sizeof(FIXED_INFO);
64

    
65
    if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen)) {
66
        if (FixedInfo) {
67
            GlobalFree(FixedInfo);
68
            FixedInfo = NULL;
69
        }
70
        FixedInfo = GlobalAlloc(GPTR, BufLen);
71
    }
72

    
73
    if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS) {
74
        printf("GetNetworkParams failed. ret = %08x\n", (u_int)ret );
75
        if (FixedInfo) {
76
            GlobalFree(FixedInfo);
77
            FixedInfo = NULL;
78
        }
79
        return -1;
80
    }
81

    
82
    pIPAddr = &(FixedInfo->DnsServerList);
83
    inet_aton(pIPAddr->IpAddress.String, &tmp_addr);
84
    *pdns_addr = tmp_addr;
85
    if (FixedInfo) {
86
        GlobalFree(FixedInfo);
87
        FixedInfo = NULL;
88
    }
89
    return 0;
90
}
91

    
92
static void winsock_cleanup(void)
93
{
94
    WSACleanup();
95
}
96

    
97
#else
98

    
99
static int get_dns_addr(struct in_addr *pdns_addr)
100
{
101
    char buff[512];
102
    char buff2[257];
103
    FILE *f;
104
    int found = 0;
105
    struct in_addr tmp_addr;
106

    
107
    f = fopen("/etc/resolv.conf", "r");
108
    if (!f)
109
        return -1;
110

    
111
#ifdef DEBUG
112
    lprint("IP address of your DNS(s): ");
113
#endif
114
    while (fgets(buff, 512, f) != NULL) {
115
        if (sscanf(buff, "nameserver%*[ \t]%256s", buff2) == 1) {
116
            if (!inet_aton(buff2, &tmp_addr))
117
                continue;
118
            if (tmp_addr.s_addr == loopback_addr.s_addr)
119
                tmp_addr = our_addr;
120
            /* If it's the first one, set it to dns_addr */
121
            if (!found)
122
                *pdns_addr = tmp_addr;
123
#ifdef DEBUG
124
            else
125
                lprint(", ");
126
#endif
127
            if (++found > 3) {
128
#ifdef DEBUG
129
                lprint("(more)");
130
#endif
131
                break;
132
            }
133
#ifdef DEBUG
134
            else
135
                lprint("%s", inet_ntoa(tmp_addr));
136
#endif
137
        }
138
    }
139
    fclose(f);
140
    if (!found)
141
        return -1;
142
    return 0;
143
}
144

    
145
#endif
146

    
147
static void slirp_init_once(void)
148
{
149
    static int initialized;
150
    struct hostent *he;
151
    char our_name[256];
152
#ifdef _WIN32
153
    WSADATA Data;
154
#endif
155

    
156
    if (initialized) {
157
        return;
158
    }
159
    initialized = 1;
160

    
161
#ifdef _WIN32
162
    WSAStartup(MAKEWORD(2,0), &Data);
163
    atexit(winsock_cleanup);
164
#endif
165

    
166
    loopback_addr.s_addr = htonl(INADDR_LOOPBACK);
167

    
168
    /* FIXME: This address may change during runtime */
169
    if (gethostname(our_name, sizeof(our_name)) == 0) {
170
        he = gethostbyname(our_name);
171
        if (he) {
172
            our_addr = *(struct in_addr *)he->h_addr;
173
        }
174
    }
175
    if (our_addr.s_addr == 0) {
176
        our_addr = loopback_addr;
177
    }
178

    
179
    /* FIXME: This address may change during runtime */
180
    if (get_dns_addr(&dns_addr) < 0) {
181
        dns_addr = loopback_addr;
182
    }
183
}
184

    
185
static void slirp_state_save(QEMUFile *f, void *opaque);
186
static int slirp_state_load(QEMUFile *f, void *opaque, int version_id);
187

    
188
Slirp *slirp_init(int restricted, struct in_addr vnetwork,
189
                  struct in_addr vnetmask, struct in_addr vhost,
190
                  const char *vhostname, const char *tftp_path,
191
                  const char *bootfile, struct in_addr vdhcp_start,
192
                  struct in_addr vnameserver, void *opaque)
193
{
194
    Slirp *slirp = qemu_mallocz(sizeof(Slirp));
195

    
196
    slirp_init_once();
197

    
198
    slirp->restricted = restricted;
199

    
200
    if_init(slirp);
201
    ip_init(slirp);
202

    
203
    /* Initialise mbufs *after* setting the MTU */
204
    m_init(slirp);
205

    
206
    slirp->vnetwork_addr = vnetwork;
207
    slirp->vnetwork_mask = vnetmask;
208
    slirp->vhost_addr = vhost;
209
    if (vhostname) {
210
        pstrcpy(slirp->client_hostname, sizeof(slirp->client_hostname),
211
                vhostname);
212
    }
213
    if (tftp_path) {
214
        slirp->tftp_prefix = qemu_strdup(tftp_path);
215
    }
216
    if (bootfile) {
217
        slirp->bootp_filename = qemu_strdup(bootfile);
218
    }
219
    slirp->vdhcp_startaddr = vdhcp_start;
220
    slirp->vnameserver_addr = vnameserver;
221

    
222
    slirp->opaque = opaque;
223

    
224
    register_savevm("slirp", 0, 2, slirp_state_save, slirp_state_load, slirp);
225

    
226
    slirp_instance = slirp;
227

    
228
    return slirp;
229
}
230

    
231
void slirp_cleanup(Slirp *slirp)
232
{
233
    unregister_savevm("slirp", slirp);
234

    
235
    qemu_free(slirp->tftp_prefix);
236
    qemu_free(slirp->bootp_filename);
237
    qemu_free(slirp);
238

    
239
    slirp_instance = NULL;
240
}
241

    
242
#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
243
#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
244
#define UPD_NFDS(x) if (nfds < (x)) nfds = (x)
245

    
246
/*
247
 * curtime kept to an accuracy of 1ms
248
 */
249
#ifdef _WIN32
250
static void updtime(void)
251
{
252
    struct _timeb tb;
253

    
254
    _ftime(&tb);
255

    
256
    curtime = tb.time * 1000 + tb.millitm;
257
}
258
#else
259
static void updtime(void)
260
{
261
    struct timeval tv;
262

    
263
    gettimeofday(&tv, NULL);
264

    
265
    curtime = tv.tv_sec * 1000 + tv.tv_usec / 1000;
266
}
267
#endif
268

    
269
void slirp_select_fill(int *pnfds,
270
                       fd_set *readfds, fd_set *writefds, fd_set *xfds)
271
{
272
    Slirp *slirp = slirp_instance;
273
    struct socket *so, *so_next;
274
    int nfds;
275

    
276
    if (!slirp_instance) {
277
        return;
278
    }
279

    
280
    /* fail safe */
281
    global_readfds = NULL;
282
    global_writefds = NULL;
283
    global_xfds = NULL;
284

    
285
    nfds = *pnfds;
286
        /*
287
         * First, TCP sockets
288
         */
289
        do_slowtimo = 0;
290

    
291
                /*
292
                 * *_slowtimo needs calling if there are IP fragments
293
                 * in the fragment queue, or there are TCP connections active
294
                 */
295
                do_slowtimo = ((slirp->tcb.so_next != &slirp->tcb) ||
296
                    (&slirp->ipq.ip_link != slirp->ipq.ip_link.next));
297

    
298
                for (so = slirp->tcb.so_next; so != &slirp->tcb;
299
                     so = so_next) {
300
                        so_next = so->so_next;
301

    
302
                        /*
303
                         * See if we need a tcp_fasttimo
304
                         */
305
                        if (time_fasttimo == 0 && so->so_tcpcb->t_flags & TF_DELACK)
306
                           time_fasttimo = curtime; /* Flag when we want a fasttimo */
307

    
308
                        /*
309
                         * NOFDREF can include still connecting to local-host,
310
                         * newly socreated() sockets etc. Don't want to select these.
311
                          */
312
                        if (so->so_state & SS_NOFDREF || so->s == -1)
313
                           continue;
314

    
315
                        /*
316
                         * Set for reading sockets which are accepting
317
                         */
318
                        if (so->so_state & SS_FACCEPTCONN) {
319
                                FD_SET(so->s, readfds);
320
                                UPD_NFDS(so->s);
321
                                continue;
322
                        }
323

    
324
                        /*
325
                         * Set for writing sockets which are connecting
326
                         */
327
                        if (so->so_state & SS_ISFCONNECTING) {
328
                                FD_SET(so->s, writefds);
329
                                UPD_NFDS(so->s);
330
                                continue;
331
                        }
332

    
333
                        /*
334
                         * Set for writing if we are connected, can send more, and
335
                         * we have something to send
336
                         */
337
                        if (CONN_CANFSEND(so) && so->so_rcv.sb_cc) {
338
                                FD_SET(so->s, writefds);
339
                                UPD_NFDS(so->s);
340
                        }
341

    
342
                        /*
343
                         * Set for reading (and urgent data) if we are connected, can
344
                         * receive more, and we have room for it XXX /2 ?
345
                         */
346
                        if (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2))) {
347
                                FD_SET(so->s, readfds);
348
                                FD_SET(so->s, xfds);
349
                                UPD_NFDS(so->s);
350
                        }
351
                }
352

    
353
                /*
354
                 * UDP sockets
355
                 */
356
                for (so = slirp->udb.so_next; so != &slirp->udb;
357
                     so = so_next) {
358
                        so_next = so->so_next;
359

    
360
                        /*
361
                         * See if it's timed out
362
                         */
363
                        if (so->so_expire) {
364
                                if (so->so_expire <= curtime) {
365
                                        udp_detach(so);
366
                                        continue;
367
                                } else
368
                                        do_slowtimo = 1; /* Let socket expire */
369
                        }
370

    
371
                        /*
372
                         * When UDP packets are received from over the
373
                         * link, they're sendto()'d straight away, so
374
                         * no need for setting for writing
375
                         * Limit the number of packets queued by this session
376
                         * to 4.  Note that even though we try and limit this
377
                         * to 4 packets, the session could have more queued
378
                         * if the packets needed to be fragmented
379
                         * (XXX <= 4 ?)
380
                         */
381
                        if ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4) {
382
                                FD_SET(so->s, readfds);
383
                                UPD_NFDS(so->s);
384
                        }
385
                }
386

    
387
        *pnfds = nfds;
388
}
389

    
390
void slirp_select_poll(fd_set *readfds, fd_set *writefds, fd_set *xfds,
391
                       int select_error)
392
{
393
    Slirp *slirp = slirp_instance;
394
    struct socket *so, *so_next;
395
    int ret;
396

    
397
    if (!slirp_instance) {
398
        return;
399
    }
400

    
401
    global_readfds = readfds;
402
    global_writefds = writefds;
403
    global_xfds = xfds;
404

    
405
        /* Update time */
406
        updtime();
407

    
408
        /*
409
         * See if anything has timed out
410
         */
411
                if (time_fasttimo && ((curtime - time_fasttimo) >= 2)) {
412
                        tcp_fasttimo(slirp);
413
                        time_fasttimo = 0;
414
                }
415
                if (do_slowtimo && ((curtime - last_slowtimo) >= 499)) {
416
                        ip_slowtimo(slirp);
417
                        tcp_slowtimo(slirp);
418
                        last_slowtimo = curtime;
419
                }
420

    
421
        /*
422
         * Check sockets
423
         */
424
        if (!select_error) {
425
                /*
426
                 * Check TCP sockets
427
                 */
428
                for (so = slirp->tcb.so_next; so != &slirp->tcb;
429
                     so = so_next) {
430
                        so_next = so->so_next;
431

    
432
                        /*
433
                         * FD_ISSET is meaningless on these sockets
434
                         * (and they can crash the program)
435
                         */
436
                        if (so->so_state & SS_NOFDREF || so->s == -1)
437
                           continue;
438

    
439
                        /*
440
                         * Check for URG data
441
                         * This will soread as well, so no need to
442
                         * test for readfds below if this succeeds
443
                         */
444
                        if (FD_ISSET(so->s, xfds))
445
                           sorecvoob(so);
446
                        /*
447
                         * Check sockets for reading
448
                         */
449
                        else if (FD_ISSET(so->s, readfds)) {
450
                                /*
451
                                 * Check for incoming connections
452
                                 */
453
                                if (so->so_state & SS_FACCEPTCONN) {
454
                                        tcp_connect(so);
455
                                        continue;
456
                                } /* else */
457
                                ret = soread(so);
458

    
459
                                /* Output it if we read something */
460
                                if (ret > 0)
461
                                   tcp_output(sototcpcb(so));
462
                        }
463

    
464
                        /*
465
                         * Check sockets for writing
466
                         */
467
                        if (FD_ISSET(so->s, writefds)) {
468
                          /*
469
                           * Check for non-blocking, still-connecting sockets
470
                           */
471
                          if (so->so_state & SS_ISFCONNECTING) {
472
                            /* Connected */
473
                            so->so_state &= ~SS_ISFCONNECTING;
474

    
475
                            ret = send(so->s, (const void *) &ret, 0, 0);
476
                            if (ret < 0) {
477
                              /* XXXXX Must fix, zero bytes is a NOP */
478
                              if (errno == EAGAIN || errno == EWOULDBLOCK ||
479
                                  errno == EINPROGRESS || errno == ENOTCONN)
480
                                continue;
481

    
482
                              /* else failed */
483
                              so->so_state &= SS_PERSISTENT_MASK;
484
                              so->so_state |= SS_NOFDREF;
485
                            }
486
                            /* else so->so_state &= ~SS_ISFCONNECTING; */
487

    
488
                            /*
489
                             * Continue tcp_input
490
                             */
491
                            tcp_input((struct mbuf *)NULL, sizeof(struct ip), so);
492
                            /* continue; */
493
                          } else
494
                            ret = sowrite(so);
495
                          /*
496
                           * XXXXX If we wrote something (a lot), there
497
                           * could be a need for a window update.
498
                           * In the worst case, the remote will send
499
                           * a window probe to get things going again
500
                           */
501
                        }
502

    
503
                        /*
504
                         * Probe a still-connecting, non-blocking socket
505
                         * to check if it's still alive
506
                           */
507
#ifdef PROBE_CONN
508
                        if (so->so_state & SS_ISFCONNECTING) {
509
                          ret = recv(so->s, (char *)&ret, 0,0);
510

    
511
                          if (ret < 0) {
512
                            /* XXX */
513
                            if (errno == EAGAIN || errno == EWOULDBLOCK ||
514
                                errno == EINPROGRESS || errno == ENOTCONN)
515
                              continue; /* Still connecting, continue */
516

    
517
                            /* else failed */
518
                            so->so_state &= SS_PERSISTENT_MASK;
519
                            so->so_state |= SS_NOFDREF;
520

    
521
                            /* tcp_input will take care of it */
522
                          } else {
523
                            ret = send(so->s, &ret, 0,0);
524
                            if (ret < 0) {
525
                              /* XXX */
526
                              if (errno == EAGAIN || errno == EWOULDBLOCK ||
527
                                  errno == EINPROGRESS || errno == ENOTCONN)
528
                                continue;
529
                              /* else failed */
530
                              so->so_state &= SS_PERSISTENT_MASK;
531
                              so->so_state |= SS_NOFDREF;
532
                            } else
533
                              so->so_state &= ~SS_ISFCONNECTING;
534

    
535
                          }
536
                          tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);
537
                        } /* SS_ISFCONNECTING */
538
#endif
539
                }
540

    
541
                /*
542
                 * Now UDP sockets.
543
                 * Incoming packets are sent straight away, they're not buffered.
544
                 * Incoming UDP data isn't buffered either.
545
                 */
546
                for (so = slirp->udb.so_next; so != &slirp->udb;
547
                     so = so_next) {
548
                        so_next = so->so_next;
549

    
550
                        if (so->s != -1 && FD_ISSET(so->s, readfds)) {
551
                            sorecvfrom(so);
552
                        }
553
                }
554
        }
555

    
556
        /*
557
         * See if we can start outputting
558
         */
559
        if (slirp->if_queued) {
560
            if_start(slirp);
561
        }
562

    
563
        /* clear global file descriptor sets.
564
         * these reside on the stack in vl.c
565
         * so they're unusable if we're not in
566
         * slirp_select_fill or slirp_select_poll.
567
         */
568
         global_readfds = NULL;
569
         global_writefds = NULL;
570
         global_xfds = NULL;
571
}
572

    
573
#define ETH_ALEN 6
574
#define ETH_HLEN 14
575

    
576
#define ETH_P_IP        0x0800                /* Internet Protocol packet        */
577
#define ETH_P_ARP        0x0806                /* Address Resolution packet        */
578

    
579
#define        ARPOP_REQUEST        1                /* ARP request                        */
580
#define        ARPOP_REPLY        2                /* ARP reply                        */
581

    
582
struct ethhdr
583
{
584
        unsigned char        h_dest[ETH_ALEN];        /* destination eth addr        */
585
        unsigned char        h_source[ETH_ALEN];        /* source ether addr        */
586
        unsigned short        h_proto;                /* packet type ID field        */
587
};
588

    
589
struct arphdr
590
{
591
        unsigned short        ar_hrd;                /* format of hardware address        */
592
        unsigned short        ar_pro;                /* format of protocol address        */
593
        unsigned char        ar_hln;                /* length of hardware address        */
594
        unsigned char        ar_pln;                /* length of protocol address        */
595
        unsigned short        ar_op;                /* ARP opcode (command)                */
596

    
597
         /*
598
          *         Ethernet looks like this : This bit is variable sized however...
599
          */
600
        unsigned char                ar_sha[ETH_ALEN];        /* sender hardware address        */
601
        uint32_t                ar_sip;                        /* sender IP address                */
602
        unsigned char                ar_tha[ETH_ALEN];        /* target hardware address        */
603
        uint32_t                ar_tip        ;                /* target IP address                */
604
} __attribute__((packed));
605

    
606
static void arp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)
607
{
608
    struct ethhdr *eh = (struct ethhdr *)pkt;
609
    struct arphdr *ah = (struct arphdr *)(pkt + ETH_HLEN);
610
    uint8_t arp_reply[ETH_HLEN + sizeof(struct arphdr)];
611
    struct ethhdr *reh = (struct ethhdr *)arp_reply;
612
    struct arphdr *rah = (struct arphdr *)(arp_reply + ETH_HLEN);
613
    int ar_op;
614
    struct ex_list *ex_ptr;
615

    
616
    ar_op = ntohs(ah->ar_op);
617
    switch(ar_op) {
618
    case ARPOP_REQUEST:
619
        if ((ah->ar_tip & slirp->vnetwork_mask.s_addr) ==
620
            slirp->vnetwork_addr.s_addr) {
621
            if (ah->ar_tip == slirp->vnameserver_addr.s_addr ||
622
                ah->ar_tip == slirp->vhost_addr.s_addr)
623
                goto arp_ok;
624
            for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {
625
                if (ex_ptr->ex_addr.s_addr == ah->ar_tip)
626
                    goto arp_ok;
627
            }
628
            return;
629
        arp_ok:
630
            /* XXX: make an ARP request to have the client address */
631
            memcpy(slirp->client_ethaddr, eh->h_source, ETH_ALEN);
632

    
633
            /* ARP request for alias/dns mac address */
634
            memcpy(reh->h_dest, pkt + ETH_ALEN, ETH_ALEN);
635
            memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);
636
            memcpy(&reh->h_source[2], &ah->ar_tip, 4);
637
            reh->h_proto = htons(ETH_P_ARP);
638

    
639
            rah->ar_hrd = htons(1);
640
            rah->ar_pro = htons(ETH_P_IP);
641
            rah->ar_hln = ETH_ALEN;
642
            rah->ar_pln = 4;
643
            rah->ar_op = htons(ARPOP_REPLY);
644
            memcpy(rah->ar_sha, reh->h_source, ETH_ALEN);
645
            rah->ar_sip = ah->ar_tip;
646
            memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);
647
            rah->ar_tip = ah->ar_sip;
648
            slirp_output(slirp->opaque, arp_reply, sizeof(arp_reply));
649
        }
650
        break;
651
    case ARPOP_REPLY:
652
        /* reply to request of client mac address ? */
653
        if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN) &&
654
            ah->ar_sip == slirp->client_ipaddr.s_addr) {
655
            memcpy(slirp->client_ethaddr, ah->ar_sha, ETH_ALEN);
656
        }
657
        break;
658
    default:
659
        break;
660
    }
661
}
662

    
663
void slirp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)
664
{
665
    struct mbuf *m;
666
    int proto;
667

    
668
    if (pkt_len < ETH_HLEN)
669
        return;
670

    
671
    proto = ntohs(*(uint16_t *)(pkt + 12));
672
    switch(proto) {
673
    case ETH_P_ARP:
674
        arp_input(slirp, pkt, pkt_len);
675
        break;
676
    case ETH_P_IP:
677
        m = m_get(slirp);
678
        if (!m)
679
            return;
680
        /* Note: we add to align the IP header */
681
        if (M_FREEROOM(m) < pkt_len + 2) {
682
            m_inc(m, pkt_len + 2);
683
        }
684
        m->m_len = pkt_len + 2;
685
        memcpy(m->m_data + 2, pkt, pkt_len);
686

    
687
        m->m_data += 2 + ETH_HLEN;
688
        m->m_len -= 2 + ETH_HLEN;
689

    
690
        ip_input(m);
691
        break;
692
    default:
693
        break;
694
    }
695
}
696

    
697
/* output the IP packet to the ethernet device */
698
void if_encap(Slirp *slirp, const uint8_t *ip_data, int ip_data_len)
699
{
700
    uint8_t buf[1600];
701
    struct ethhdr *eh = (struct ethhdr *)buf;
702

    
703
    if (ip_data_len + ETH_HLEN > sizeof(buf))
704
        return;
705
    
706
    if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN)) {
707
        uint8_t arp_req[ETH_HLEN + sizeof(struct arphdr)];
708
        struct ethhdr *reh = (struct ethhdr *)arp_req;
709
        struct arphdr *rah = (struct arphdr *)(arp_req + ETH_HLEN);
710
        const struct ip *iph = (const struct ip *)ip_data;
711

    
712
        /* If the client addr is not known, there is no point in
713
           sending the packet to it. Normally the sender should have
714
           done an ARP request to get its MAC address. Here we do it
715
           in place of sending the packet and we hope that the sender
716
           will retry sending its packet. */
717
        memset(reh->h_dest, 0xff, ETH_ALEN);
718
        memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);
719
        memcpy(&reh->h_source[2], &slirp->vhost_addr, 4);
720
        reh->h_proto = htons(ETH_P_ARP);
721
        rah->ar_hrd = htons(1);
722
        rah->ar_pro = htons(ETH_P_IP);
723
        rah->ar_hln = ETH_ALEN;
724
        rah->ar_pln = 4;
725
        rah->ar_op = htons(ARPOP_REQUEST);
726
        /* source hw addr */
727
        memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN - 4);
728
        memcpy(&rah->ar_sha[2], &slirp->vhost_addr, 4);
729
        /* source IP */
730
        rah->ar_sip = slirp->vhost_addr.s_addr;
731
        /* target hw addr (none) */
732
        memset(rah->ar_tha, 0, ETH_ALEN);
733
        /* target IP */
734
        rah->ar_tip = iph->ip_dst.s_addr;
735
        slirp->client_ipaddr = iph->ip_dst;
736
        slirp_output(slirp->opaque, arp_req, sizeof(arp_req));
737
    } else {
738
        memcpy(eh->h_dest, slirp->client_ethaddr, ETH_ALEN);
739
        memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 4);
740
        /* XXX: not correct */
741
        memcpy(&eh->h_source[2], &slirp->vhost_addr, 4);
742
        eh->h_proto = htons(ETH_P_IP);
743
        memcpy(buf + sizeof(struct ethhdr), ip_data, ip_data_len);
744
        slirp_output(slirp->opaque, buf, ip_data_len + ETH_HLEN);
745
    }
746
}
747

    
748
/* Drop host forwarding rule, return 0 if found. */
749
int slirp_remove_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,
750
                         int host_port)
751
{
752
    struct socket *so;
753
    struct socket *head = (is_udp ? &slirp->udb : &slirp->tcb);
754
    struct sockaddr_in addr;
755
    int port = htons(host_port);
756
    socklen_t addr_len;
757

    
758
    for (so = head->so_next; so != head; so = so->so_next) {
759
        addr_len = sizeof(addr);
760
        if ((so->so_state & SS_HOSTFWD) &&
761
            getsockname(so->s, (struct sockaddr *)&addr, &addr_len) == 0 &&
762
            addr.sin_addr.s_addr == host_addr.s_addr &&
763
            addr.sin_port == port) {
764
            close(so->s);
765
            sofree(so);
766
            return 0;
767
        }
768
    }
769

    
770
    return -1;
771
}
772

    
773
int slirp_add_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,
774
                      int host_port, struct in_addr guest_addr, int guest_port)
775
{
776
    if (!guest_addr.s_addr) {
777
        guest_addr = slirp->vdhcp_startaddr;
778
    }
779
    if (is_udp) {
780
        if (!udp_listen(slirp, host_addr.s_addr, htons(host_port),
781
                        guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))
782
            return -1;
783
    } else {
784
        if (!tcp_listen(slirp, host_addr.s_addr, htons(host_port),
785
                        guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))
786
            return -1;
787
    }
788
    return 0;
789
}
790

    
791
int slirp_add_exec(Slirp *slirp, int do_pty, const void *args,
792
                   struct in_addr guest_addr, int guest_port)
793
{
794
    if (!guest_addr.s_addr) {
795
        guest_addr.s_addr = slirp->vnetwork_addr.s_addr |
796
            (htonl(0x0204) & ~slirp->vnetwork_mask.s_addr);
797
    }
798
    if ((guest_addr.s_addr & slirp->vnetwork_mask.s_addr) !=
799
        slirp->vnetwork_addr.s_addr ||
800
        guest_addr.s_addr == slirp->vhost_addr.s_addr ||
801
        guest_addr.s_addr == slirp->vnameserver_addr.s_addr) {
802
        return -1;
803
    }
804
    return add_exec(&slirp->exec_list, do_pty, (char *)args, guest_addr,
805
                    htons(guest_port));
806
}
807

    
808
ssize_t slirp_send(struct socket *so, const void *buf, size_t len, int flags)
809
{
810
        if (so->s == -1 && so->extra) {
811
                qemu_chr_write(so->extra, buf, len);
812
                return len;
813
        }
814

    
815
        return send(so->s, buf, len, flags);
816
}
817

    
818
static struct socket *
819
slirp_find_ctl_socket(Slirp *slirp, struct in_addr guest_addr, int guest_port)
820
{
821
    struct socket *so;
822

    
823
    for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {
824
        if (so->so_faddr.s_addr == guest_addr.s_addr &&
825
            htons(so->so_fport) == guest_port) {
826
            return so;
827
        }
828
    }
829
    return NULL;
830
}
831

    
832
size_t slirp_socket_can_recv(Slirp *slirp, struct in_addr guest_addr,
833
                             int guest_port)
834
{
835
        struct iovec iov[2];
836
        struct socket *so;
837

    
838
        so = slirp_find_ctl_socket(slirp, guest_addr, guest_port);
839

    
840
        if (!so || so->so_state & SS_NOFDREF)
841
                return 0;
842

    
843
        if (!CONN_CANFRCV(so) || so->so_snd.sb_cc >= (so->so_snd.sb_datalen/2))
844
                return 0;
845

    
846
        return sopreprbuf(so, iov, NULL);
847
}
848

    
849
void slirp_socket_recv(Slirp *slirp, struct in_addr guest_addr, int guest_port,
850
                       const uint8_t *buf, int size)
851
{
852
    int ret;
853
    struct socket *so = slirp_find_ctl_socket(slirp, guest_addr, guest_port);
854

    
855
    if (!so)
856
        return;
857

    
858
    ret = soreadbuf(so, (const char *)buf, size);
859

    
860
    if (ret > 0)
861
        tcp_output(sototcpcb(so));
862
}
863

    
864
static void slirp_tcp_save(QEMUFile *f, struct tcpcb *tp)
865
{
866
    int i;
867

    
868
    qemu_put_sbe16(f, tp->t_state);
869
    for (i = 0; i < TCPT_NTIMERS; i++)
870
        qemu_put_sbe16(f, tp->t_timer[i]);
871
    qemu_put_sbe16(f, tp->t_rxtshift);
872
    qemu_put_sbe16(f, tp->t_rxtcur);
873
    qemu_put_sbe16(f, tp->t_dupacks);
874
    qemu_put_be16(f, tp->t_maxseg);
875
    qemu_put_sbyte(f, tp->t_force);
876
    qemu_put_be16(f, tp->t_flags);
877
    qemu_put_be32(f, tp->snd_una);
878
    qemu_put_be32(f, tp->snd_nxt);
879
    qemu_put_be32(f, tp->snd_up);
880
    qemu_put_be32(f, tp->snd_wl1);
881
    qemu_put_be32(f, tp->snd_wl2);
882
    qemu_put_be32(f, tp->iss);
883
    qemu_put_be32(f, tp->snd_wnd);
884
    qemu_put_be32(f, tp->rcv_wnd);
885
    qemu_put_be32(f, tp->rcv_nxt);
886
    qemu_put_be32(f, tp->rcv_up);
887
    qemu_put_be32(f, tp->irs);
888
    qemu_put_be32(f, tp->rcv_adv);
889
    qemu_put_be32(f, tp->snd_max);
890
    qemu_put_be32(f, tp->snd_cwnd);
891
    qemu_put_be32(f, tp->snd_ssthresh);
892
    qemu_put_sbe16(f, tp->t_idle);
893
    qemu_put_sbe16(f, tp->t_rtt);
894
    qemu_put_be32(f, tp->t_rtseq);
895
    qemu_put_sbe16(f, tp->t_srtt);
896
    qemu_put_sbe16(f, tp->t_rttvar);
897
    qemu_put_be16(f, tp->t_rttmin);
898
    qemu_put_be32(f, tp->max_sndwnd);
899
    qemu_put_byte(f, tp->t_oobflags);
900
    qemu_put_byte(f, tp->t_iobc);
901
    qemu_put_sbe16(f, tp->t_softerror);
902
    qemu_put_byte(f, tp->snd_scale);
903
    qemu_put_byte(f, tp->rcv_scale);
904
    qemu_put_byte(f, tp->request_r_scale);
905
    qemu_put_byte(f, tp->requested_s_scale);
906
    qemu_put_be32(f, tp->ts_recent);
907
    qemu_put_be32(f, tp->ts_recent_age);
908
    qemu_put_be32(f, tp->last_ack_sent);
909
}
910

    
911
static void slirp_sbuf_save(QEMUFile *f, struct sbuf *sbuf)
912
{
913
    uint32_t off;
914

    
915
    qemu_put_be32(f, sbuf->sb_cc);
916
    qemu_put_be32(f, sbuf->sb_datalen);
917
    off = (uint32_t)(sbuf->sb_wptr - sbuf->sb_data);
918
    qemu_put_sbe32(f, off);
919
    off = (uint32_t)(sbuf->sb_rptr - sbuf->sb_data);
920
    qemu_put_sbe32(f, off);
921
    qemu_put_buffer(f, (unsigned char*)sbuf->sb_data, sbuf->sb_datalen);
922
}
923

    
924
static void slirp_socket_save(QEMUFile *f, struct socket *so)
925
{
926
    qemu_put_be32(f, so->so_urgc);
927
    qemu_put_be32(f, so->so_faddr.s_addr);
928
    qemu_put_be32(f, so->so_laddr.s_addr);
929
    qemu_put_be16(f, so->so_fport);
930
    qemu_put_be16(f, so->so_lport);
931
    qemu_put_byte(f, so->so_iptos);
932
    qemu_put_byte(f, so->so_emu);
933
    qemu_put_byte(f, so->so_type);
934
    qemu_put_be32(f, so->so_state);
935
    slirp_sbuf_save(f, &so->so_rcv);
936
    slirp_sbuf_save(f, &so->so_snd);
937
    slirp_tcp_save(f, so->so_tcpcb);
938
}
939

    
940
static void slirp_state_save(QEMUFile *f, void *opaque)
941
{
942
    Slirp *slirp = opaque;
943
    struct ex_list *ex_ptr;
944

    
945
    for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)
946
        if (ex_ptr->ex_pty == 3) {
947
            struct socket *so;
948
            so = slirp_find_ctl_socket(slirp, ex_ptr->ex_addr,
949
                                       ntohs(ex_ptr->ex_fport));
950
            if (!so)
951
                continue;
952

    
953
            qemu_put_byte(f, 42);
954
            slirp_socket_save(f, so);
955
        }
956
    qemu_put_byte(f, 0);
957

    
958
    qemu_put_be16(f, slirp->ip_id);
959
}
960

    
961
static void slirp_tcp_load(QEMUFile *f, struct tcpcb *tp)
962
{
963
    int i;
964

    
965
    tp->t_state = qemu_get_sbe16(f);
966
    for (i = 0; i < TCPT_NTIMERS; i++)
967
        tp->t_timer[i] = qemu_get_sbe16(f);
968
    tp->t_rxtshift = qemu_get_sbe16(f);
969
    tp->t_rxtcur = qemu_get_sbe16(f);
970
    tp->t_dupacks = qemu_get_sbe16(f);
971
    tp->t_maxseg = qemu_get_be16(f);
972
    tp->t_force = qemu_get_sbyte(f);
973
    tp->t_flags = qemu_get_be16(f);
974
    tp->snd_una = qemu_get_be32(f);
975
    tp->snd_nxt = qemu_get_be32(f);
976
    tp->snd_up = qemu_get_be32(f);
977
    tp->snd_wl1 = qemu_get_be32(f);
978
    tp->snd_wl2 = qemu_get_be32(f);
979
    tp->iss = qemu_get_be32(f);
980
    tp->snd_wnd = qemu_get_be32(f);
981
    tp->rcv_wnd = qemu_get_be32(f);
982
    tp->rcv_nxt = qemu_get_be32(f);
983
    tp->rcv_up = qemu_get_be32(f);
984
    tp->irs = qemu_get_be32(f);
985
    tp->rcv_adv = qemu_get_be32(f);
986
    tp->snd_max = qemu_get_be32(f);
987
    tp->snd_cwnd = qemu_get_be32(f);
988
    tp->snd_ssthresh = qemu_get_be32(f);
989
    tp->t_idle = qemu_get_sbe16(f);
990
    tp->t_rtt = qemu_get_sbe16(f);
991
    tp->t_rtseq = qemu_get_be32(f);
992
    tp->t_srtt = qemu_get_sbe16(f);
993
    tp->t_rttvar = qemu_get_sbe16(f);
994
    tp->t_rttmin = qemu_get_be16(f);
995
    tp->max_sndwnd = qemu_get_be32(f);
996
    tp->t_oobflags = qemu_get_byte(f);
997
    tp->t_iobc = qemu_get_byte(f);
998
    tp->t_softerror = qemu_get_sbe16(f);
999
    tp->snd_scale = qemu_get_byte(f);
1000
    tp->rcv_scale = qemu_get_byte(f);
1001
    tp->request_r_scale = qemu_get_byte(f);
1002
    tp->requested_s_scale = qemu_get_byte(f);
1003
    tp->ts_recent = qemu_get_be32(f);
1004
    tp->ts_recent_age = qemu_get_be32(f);
1005
    tp->last_ack_sent = qemu_get_be32(f);
1006
    tcp_template(tp);
1007
}
1008

    
1009
static int slirp_sbuf_load(QEMUFile *f, struct sbuf *sbuf)
1010
{
1011
    uint32_t off, sb_cc, sb_datalen;
1012

    
1013
    sb_cc = qemu_get_be32(f);
1014
    sb_datalen = qemu_get_be32(f);
1015

    
1016
    sbreserve(sbuf, sb_datalen);
1017

    
1018
    if (sbuf->sb_datalen != sb_datalen)
1019
        return -ENOMEM;
1020

    
1021
    sbuf->sb_cc = sb_cc;
1022

    
1023
    off = qemu_get_sbe32(f);
1024
    sbuf->sb_wptr = sbuf->sb_data + off;
1025
    off = qemu_get_sbe32(f);
1026
    sbuf->sb_rptr = sbuf->sb_data + off;
1027
    qemu_get_buffer(f, (unsigned char*)sbuf->sb_data, sbuf->sb_datalen);
1028

    
1029
    return 0;
1030
}
1031

    
1032
static int slirp_socket_load(QEMUFile *f, struct socket *so)
1033
{
1034
    if (tcp_attach(so) < 0)
1035
        return -ENOMEM;
1036

    
1037
    so->so_urgc = qemu_get_be32(f);
1038
    so->so_faddr.s_addr = qemu_get_be32(f);
1039
    so->so_laddr.s_addr = qemu_get_be32(f);
1040
    so->so_fport = qemu_get_be16(f);
1041
    so->so_lport = qemu_get_be16(f);
1042
    so->so_iptos = qemu_get_byte(f);
1043
    so->so_emu = qemu_get_byte(f);
1044
    so->so_type = qemu_get_byte(f);
1045
    so->so_state = qemu_get_be32(f);
1046
    if (slirp_sbuf_load(f, &so->so_rcv) < 0)
1047
        return -ENOMEM;
1048
    if (slirp_sbuf_load(f, &so->so_snd) < 0)
1049
        return -ENOMEM;
1050
    slirp_tcp_load(f, so->so_tcpcb);
1051

    
1052
    return 0;
1053
}
1054

    
1055
static int slirp_state_load(QEMUFile *f, void *opaque, int version_id)
1056
{
1057
    Slirp *slirp = opaque;
1058
    struct ex_list *ex_ptr;
1059
    int r;
1060

    
1061
    while ((r = qemu_get_byte(f))) {
1062
        int ret;
1063
        struct socket *so = socreate(slirp);
1064

    
1065
        if (!so)
1066
            return -ENOMEM;
1067

    
1068
        ret = slirp_socket_load(f, so);
1069

    
1070
        if (ret < 0)
1071
            return ret;
1072

    
1073
        if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) !=
1074
            slirp->vnetwork_addr.s_addr) {
1075
            return -EINVAL;
1076
        }
1077
        for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {
1078
            if (ex_ptr->ex_pty == 3 &&
1079
                so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr &&
1080
                so->so_fport == ex_ptr->ex_fport) {
1081
                break;
1082
            }
1083
        }
1084
        if (!ex_ptr)
1085
            return -EINVAL;
1086

    
1087
        so->extra = (void *)ex_ptr->ex_exec;
1088
    }
1089

    
1090
    if (version_id >= 2) {
1091
        slirp->ip_id = qemu_get_be16(f);
1092
    }
1093

    
1094
    return 0;
1095
}