aboutsummaryrefslogtreecommitdiff
path: root/test/pingtest.c
blob: 15249f0d21cdd477daa310a60c3b0234cbd23b68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
88
89
90
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/* SPDX-License-Identifier: BSD-3-Clause */
/*
 * Copyright (c) 2021 Samuel Thibault
 */

/*
 * This simple test configures slirp and tries to ping it
 *
 * Note: to make this example actually be able to use the outside world, you
 * need to either
 * - run as root
 * - set /proc/sys/net/ipv4/ping_group_range to allow sending ICMP echo requests
 * - run a UDP echo server on the target
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>

#include "libslirp.h"

//#define _WIN32
#ifdef _WIN32
//#include <sys/select.h>
#include <winsock2.h>
int slirp_inet_aton(const char *cp, struct in_addr *ia)
{
    uint32_t addr = inet_addr(cp);
    if (addr == 0xffffffff) {
        return 0;
    }
    ia->s_addr = addr;
    return 1;
}
#define inet_aton slirp_inet_aton
#else
#include <poll.h>
#endif

/* Dumb simulation tick: 100ms */
#define TICK 100

static Slirp *slirp;
static bool done;
static int64_t mytime;

/* Print a frame for debugging */
static void print_frame(const uint8_t *data, size_t len) {
    int i;

    printf("\ngot packet size %zd:\n", len);
    for (i = 0; i < len; i++) {
        if (i && i % 16 == 0)
            printf("\n");
        printf("%s%02x", i % 16 ? " " : "", data[i]);
    }
    if (len % 16 != 0)
        printf("\n");
    printf("\n");
}

/* Classical 16bit checksum */
static void checksum(uint8_t *data, size_t size, uint8_t *cksum) {
    uint32_t sum = 0;
    int i;

    cksum[0] = 0;
    cksum[1] = 0;

    for (i = 0; i+1 < size; i += 2)
        sum += (((uint16_t) data[i]) << 8) + data[i+1];
    if (i < size) /* Odd number of bytes */
        sum += ((uint16_t) data[i]) << 8;

    sum = (sum & 0xffff) + (sum >> 16);
    sum = (sum & 0xffff) + (sum >> 16);
    sum = ~sum;

    cksum[0] = sum >> 8;
    cksum[1] = sum;
}

/* This is called when receiving a packet from the virtual network, for the
 * guest */
static ssize_t send_packet(const void *buf, size_t len, void *opaque) {
    const uint8_t *data = buf;

    assert(len >= 14);

    if (data[12] == 0x86 &&
        data[13] == 0xdd) {
        /* Ignore IPv6 */
        return len;
    }

    print_frame(data, len);

    if (data[12] == 0x08 &&
        data[13] == 0x06) {
        /* ARP */
        /* We expect receiving an ARP request for our address */

        /* Ethernet address type */
        assert(data[14] == 0x00);
        assert(data[15] == 0x01);

        /* IPv4 address type */
        assert(data[16] == 0x08);
        assert(data[17] == 0x00);

        /* Ethernet addresses are 6 bytes long */
        assert(data[18] == 0x06);

        /* IPv4 addresses are 4 bytes long */
        assert(data[19] == 0x04);

        /* Opcode: ARP request */
        assert(data[20] == 0x00);
        assert(data[21] == 0x01);

        /* Ok, reply! */
        uint8_t myframe[] = {
            /*** Ethernet ***/
            /* dst */
            0x52, 0x55, 0x0a, 0x00, 0x02, 0x02,
            /* src */
            0x52, 0x55, 0x0a, 0x00, 0x02, 0x0e,
            /* Type: ARP */
            0x08, 0x06,

            /* ether,   IPv4,       */
            0x00, 0x01, 0x08, 0x00,
            /* elen, IPlen */
            0x06, 0x04,
            /* ARP reply */
            0x00, 0x02,

            /* Our ethernet address */
            0x52, 0x55, 0x0a, 0x00, 0x02, 0x0e,
            /* Our IP address */
            0x0a, 0x00, 0x02, 0x0e,

            /* Host ethernet address */
            0x52, 0x55, 0x0a, 0x00, 0x02, 0x02,
            /* Host IP address */
            0x0a, 0x00, 0x02, 0x02,
        };

        slirp_input(slirp, myframe, sizeof(myframe));
    }

    if (data[12] == 0x08 &&
        data[13] == 0x00) {
        /* IPv4 */
        assert(len >= 14 + 20);

        /* We expect receiving the ICMP echo reply for our echo request */

        /* IPv + hlen */
        assert(data[14] == 0x45);

        /* proto: ICMP */
        assert(data[23] == 0x01);

        /* ICMP */
        assert(len >= 14 + 20 + 8 + 4);

        /* ICMP type: reply */
        assert(data[34] == 0x00);

        /* Check the data */
        assert(data[42] == 0xde);
        assert(data[43] == 0xad);
        assert(data[44] == 0xbe);
        assert(data[45] == 0xef);

        /* Got the answer! */
        printf("got it!\n");
        done = 1;
    }

    return len;
}

static void guest_error(const char *msg, void *opaque) {
    printf("guest error %s\n",  msg);
}


/*
 * Dumb timer implementation
 */
static int64_t clock_get_ns(void *opaque) {
    return mytime;
}

struct timer {
    SlirpTimerCb cb;
    void *cb_opaque;
    int64_t expire;
    struct timer *next;
};

static struct timer *timer_queue;

static void *timer_new(SlirpTimerCb cb, void *cb_opaque, void *opaque) {
    struct timer *new_timer = malloc(sizeof(*new_timer));
    new_timer->cb = cb;
    new_timer->cb_opaque = cb_opaque;
    new_timer->next = NULL;
    return new_timer;
}

static void timer_free(void *_timer, void *opaque) {
    struct timer *timer = _timer;
    struct timer **t;

    for (t = &timer_queue; *t != NULL; *t = (*t)->next) {
        if (*t == timer) {
            /* Not expired yet, drop it */
            *t = timer->next;
            break;
        }
    }

    free(timer);
}

static void timer_mod(void *_timer, int64_t expire_time, void *opaque) {
    struct timer *timer = _timer;
    struct timer **t;

    timer->expire = expire_time * 1000 * 1000;

    for (t = &timer_queue; *t != NULL; *t = (*t)->next) {
        if (expire_time < (*t)->expire)
            break;
    }

    timer->next = *t;
    *t = timer;
}

static void timer_check(void) {
    while (timer_queue && timer_queue->expire <= mytime)
    {
        struct timer *t = timer_queue;
        printf("handling %p at time %lu\n",
               t, (unsigned long) timer_queue->expire);
        timer_queue = t->next;
        t->cb(t->cb_opaque);
    }
}

static uint32_t timer_timeout(void) {
    if (timer_queue)
    {
        uint32_t timeout = (timer_queue->expire - mytime) / (1000 * 1000);
        if (timeout < TICK)
            return timeout;
    }

    return TICK;
}


/*
 * Dumb polling implementation
 */
static int npoll;
static void register_poll_fd(int fd, void *opaque) {
    /* We might want to prepare for polling on fd */
    npoll++;
}

static void unregister_poll_fd(int fd, void *opaque) {
    /* We might want to clear polling on fd */
    npoll--;
}

static void notify(void *opaque) {
    /* No need for this in single-thread case */
}

#ifdef _WIN32
/* select() variant */
static fd_set readfds, writefds, exceptfds;
static int maxfd;
static int add_poll_cb(int fd, int events, void *opaque)
{
    if (events & SLIRP_POLL_IN)
        FD_SET(fd, &readfds);
    if (events & SLIRP_POLL_OUT)
        FD_SET(fd, &writefds);
    if (events & SLIRP_POLL_PRI)
        FD_SET(fd, &exceptfds);
    if (maxfd < fd)
        maxfd = fd;
    return fd;
}

static int get_revents_cb(int idx, void *opaque)
{
    int event = 0;
    if (FD_ISSET(idx, &readfds))
        event |= SLIRP_POLL_IN;
    if (FD_ISSET(idx, &writefds))
        event |= SLIRP_POLL_OUT;
    if (FD_ISSET(idx, &exceptfds))
        event |= SLIRP_POLL_PRI;
    return event;
}

static void dopoll(uint32_t timeout) {
    int err;
    FD_ZERO(&readfds);
    FD_ZERO(&writefds);
    FD_ZERO(&exceptfds);
    maxfd = 0;

    slirp_pollfds_fill(slirp, &timeout, add_poll_cb, NULL);
    printf("we will use timeout %u\n", (unsigned) timeout);

    struct timeval tv = {
        .tv_sec = timeout / 1000,
        .tv_usec = (timeout % 1000) * 1000,
    };
    err = select(maxfd+1, &readfds, &writefds, &exceptfds, &tv);

    slirp_pollfds_poll(slirp, err < 0, get_revents_cb, NULL);
}
#else
/* poll() variant */
static struct pollfd *fds;
static int cur_poll;
static int add_poll_cb(int fd, int events, void *opaque)
{
    short poll_events = 0;

    assert(cur_poll < npoll);
    fds[cur_poll].fd = fd;

    if (events & SLIRP_POLL_IN)
        poll_events |= POLLIN;
    if (events & SLIRP_POLL_OUT)
        poll_events |= POLLOUT;
    if (events & SLIRP_POLL_PRI)
        poll_events |= POLLPRI;
    fds[cur_poll].events = poll_events;

    return cur_poll++;
}

static int get_revents_cb(int idx, void *opaque)
{
    return fds[idx].revents;
}

static void dopoll(uint32_t timeout) {
    int err;
    fds = malloc(sizeof(*fds) * npoll);
    cur_poll = 0;

    slirp_pollfds_fill(slirp, &timeout, add_poll_cb, NULL);
    printf("we will use timeout %u\n", (unsigned) timeout);

    err = poll(fds, cur_poll, timeout);

    slirp_pollfds_poll(slirp, err < 0, get_revents_cb, NULL);

    free(fds);
}
#endif


static struct SlirpCb callbacks = {
    .send_packet = send_packet,
    .guest_error = guest_error,
    .clock_get_ns = clock_get_ns,
    .timer_new = timer_new,
    .timer_free = timer_free,
    .timer_mod = timer_mod,
    .register_poll_fd = register_poll_fd,
    .unregister_poll_fd = unregister_poll_fd,
    .notify = notify,
};


int main(int argc, char *argv[]) {
    SlirpConfig config = {
        .version = 3,
        .restricted = false,
        .in_enabled = true,
        .vnetwork.s_addr = htonl(0x0a000200),
        .vnetmask.s_addr = htonl(0xffffff00),
        .vhost.s_addr = htonl(0x0a000202),
        .vdhcp_start.s_addr = htonl(0x0a00020f),
        .vnameserver.s_addr = htonl(0x0a000203),
        .disable_host_loopback = false,
        .enable_emu = false,
        .disable_dns = false,
    };
    uint32_t timeout = 0;

    printf("Slirp version %s\n", slirp_version_string());

#if !defined(_WIN32)
    inet_pton(AF_INET6, "fec0::", &config.vprefix_addr6);
    config.vprefix_len = 64;
    config.vhost6 = config.vprefix_addr6;
    config.vhost6.s6_addr[15] = 2;
    config.vnameserver6 = config.vprefix_addr6;
    config.vnameserver6.s6_addr[15] = 2;
    config.in6_enabled = true,
#endif

    slirp = slirp_new(&config, &callbacks, NULL);

    /* Send echo request */
    uint8_t myframe[] = {
        /*** Ethernet ***/
        /* dst */
        0x52, 0x55, 0x0a, 0x00, 0x02, 0x02,
        /* src */
        0x52, 0x55, 0x0a, 0x00, 0x02, 0x0e,
        /* Type: IPv4 */
        0x08, 0x00,

        /*** IPv4 ***/
        /* vhl,tos, len         */
        0x45, 0x00, 0x00, 0x20,
        /* id,      off (DF)    */
        0x68, 0xd7, 0x40, 0x00,
        /* ttl,pro, cksum      */
        0x40, 0x01, 0x00, 0x00,
        /* src                  */
        0x0a, 0x00, 0x02, 0x0e,
        /* dst                  */
        0x00, 0x00, 0x00, 0x00,

        /*** ICMPv4 ***/
        /* type, code, cksum    */
        0x08, 0x00, 0x00, 0x00,
        /* id,     seq          */
        0x01, 0xec, 0x00, 0x01,
        /* data                 */
        0xde, 0xad, 0xbe, 0xef,
    };

    struct in_addr in_addr = { .s_addr = htonl(0x0a000202) };
    if (argc > 1) {
        if (inet_aton(argv[1], &in_addr) == 0) {
            printf("usage: %s [destination IPv4 address]\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }
    uint32_t addr = ntohl(in_addr.s_addr);
    myframe[30] = addr >> 24;
    myframe[31] = addr >> 16;
    myframe[32] = addr >> 8;
    myframe[33] = addr >> 0;

    /* IPv4 header checksum */
    checksum(&myframe[14], 20, &myframe[24]);
    /* ICMP header checksum */
    checksum(&myframe[34], 12, &myframe[36]);

    slirp_input(slirp, myframe, sizeof(myframe));

    /* Wait for echo reply */
    while (!done) {
        printf("time %lu\n", (unsigned long) mytime);

        timer_check();
        /* Here we make the virtual time wait like the real time, but we could
         * make it wait differently */
        timeout = timer_timeout();
        printf("we wish timeout %u\n", (unsigned) timeout);

        dopoll(timeout);

        /* Fake that the tick elapsed */
        mytime += TICK * 1000 * 1000;
    }

    slirp_cleanup(slirp);
}