]> git.proxmox.com Git - mirror_qemu.git/blob - net.c
net: Add support for capturing VLANs (Jan Kiszka)
[mirror_qemu.git] / net.c
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 <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
31
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
34
35 #ifndef _WIN32
36 #include <sys/times.h>
37 #include <sys/wait.h>
38 #include <termios.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/resource.h>
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <net/if.h>
45 #ifdef __NetBSD__
46 #include <net/if_tap.h>
47 #endif
48 #ifdef __linux__
49 #include <linux/if_tun.h>
50 #endif
51 #include <arpa/inet.h>
52 #include <dirent.h>
53 #include <netdb.h>
54 #include <sys/select.h>
55 #ifdef HOST_BSD
56 #include <sys/stat.h>
57 #if defined(__FreeBSD__) || defined(__DragonFly__)
58 #include <libutil.h>
59 #else
60 #include <util.h>
61 #endif
62 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
63 #include <freebsd/stdlib.h>
64 #else
65 #ifdef __linux__
66 #include <pty.h>
67 #include <malloc.h>
68 #include <linux/rtc.h>
69
70 /* For the benefit of older linux systems which don't supply it,
71 we use a local copy of hpet.h. */
72 /* #include <linux/hpet.h> */
73 #include "hpet.h"
74
75 #include <linux/ppdev.h>
76 #include <linux/parport.h>
77 #endif
78 #ifdef __sun__
79 #include <sys/stat.h>
80 #include <sys/ethernet.h>
81 #include <sys/sockio.h>
82 #include <netinet/arp.h>
83 #include <netinet/in.h>
84 #include <netinet/in_systm.h>
85 #include <netinet/ip.h>
86 #include <netinet/ip_icmp.h> // must come after ip.h
87 #include <netinet/udp.h>
88 #include <netinet/tcp.h>
89 #include <net/if.h>
90 #include <syslog.h>
91 #include <stropts.h>
92 #endif
93 #endif
94 #endif
95
96 #if defined(__OpenBSD__)
97 #include <util.h>
98 #endif
99
100 #if defined(CONFIG_VDE)
101 #include <libvdeplug.h>
102 #endif
103
104 #ifdef _WIN32
105 #include <windows.h>
106 #include <malloc.h>
107 #include <sys/timeb.h>
108 #include <mmsystem.h>
109 #define getopt_long_only getopt_long
110 #define memalign(align, size) malloc(size)
111 #endif
112
113 #include "qemu-common.h"
114 #include "net.h"
115 #include "monitor.h"
116 #include "sysemu.h"
117 #include "qemu-timer.h"
118 #include "qemu-char.h"
119 #include "audio/audio.h"
120 #include "qemu_socket.h"
121 #include "qemu-log.h"
122
123 #if defined(CONFIG_SLIRP)
124 #include "libslirp.h"
125 #endif
126
127
128 static VLANState *first_vlan;
129
130 /***********************************************************/
131 /* network device redirectors */
132
133 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
134 static void hex_dump(FILE *f, const uint8_t *buf, int size)
135 {
136 int len, i, j, c;
137
138 for(i=0;i<size;i+=16) {
139 len = size - i;
140 if (len > 16)
141 len = 16;
142 fprintf(f, "%08x ", i);
143 for(j=0;j<16;j++) {
144 if (j < len)
145 fprintf(f, " %02x", buf[i+j]);
146 else
147 fprintf(f, " ");
148 }
149 fprintf(f, " ");
150 for(j=0;j<len;j++) {
151 c = buf[i+j];
152 if (c < ' ' || c > '~')
153 c = '.';
154 fprintf(f, "%c", c);
155 }
156 fprintf(f, "\n");
157 }
158 }
159 #endif
160
161 static int parse_macaddr(uint8_t *macaddr, const char *p)
162 {
163 int i;
164 char *last_char;
165 long int offset;
166
167 errno = 0;
168 offset = strtol(p, &last_char, 0);
169 if (0 == errno && '\0' == *last_char &&
170 offset >= 0 && offset <= 0xFFFFFF) {
171 macaddr[3] = (offset & 0xFF0000) >> 16;
172 macaddr[4] = (offset & 0xFF00) >> 8;
173 macaddr[5] = offset & 0xFF;
174 return 0;
175 } else {
176 for(i = 0; i < 6; i++) {
177 macaddr[i] = strtol(p, (char **)&p, 16);
178 if (i == 5) {
179 if (*p != '\0')
180 return -1;
181 } else {
182 if (*p != ':' && *p != '-')
183 return -1;
184 p++;
185 }
186 }
187 return 0;
188 }
189
190 return -1;
191 }
192
193 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
194 {
195 const char *p, *p1;
196 int len;
197 p = *pp;
198 p1 = strchr(p, sep);
199 if (!p1)
200 return -1;
201 len = p1 - p;
202 p1++;
203 if (buf_size > 0) {
204 if (len > buf_size - 1)
205 len = buf_size - 1;
206 memcpy(buf, p, len);
207 buf[len] = '\0';
208 }
209 *pp = p1;
210 return 0;
211 }
212
213 int parse_host_src_port(struct sockaddr_in *haddr,
214 struct sockaddr_in *saddr,
215 const char *input_str)
216 {
217 char *str = strdup(input_str);
218 char *host_str = str;
219 char *src_str;
220 const char *src_str2;
221 char *ptr;
222
223 /*
224 * Chop off any extra arguments at the end of the string which
225 * would start with a comma, then fill in the src port information
226 * if it was provided else use the "any address" and "any port".
227 */
228 if ((ptr = strchr(str,',')))
229 *ptr = '\0';
230
231 if ((src_str = strchr(input_str,'@'))) {
232 *src_str = '\0';
233 src_str++;
234 }
235
236 if (parse_host_port(haddr, host_str) < 0)
237 goto fail;
238
239 src_str2 = src_str;
240 if (!src_str || *src_str == '\0')
241 src_str2 = ":0";
242
243 if (parse_host_port(saddr, src_str2) < 0)
244 goto fail;
245
246 free(str);
247 return(0);
248
249 fail:
250 free(str);
251 return -1;
252 }
253
254 int parse_host_port(struct sockaddr_in *saddr, const char *str)
255 {
256 char buf[512];
257 struct hostent *he;
258 const char *p, *r;
259 int port;
260
261 p = str;
262 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
263 return -1;
264 saddr->sin_family = AF_INET;
265 if (buf[0] == '\0') {
266 saddr->sin_addr.s_addr = 0;
267 } else {
268 if (qemu_isdigit(buf[0])) {
269 if (!inet_aton(buf, &saddr->sin_addr))
270 return -1;
271 } else {
272 if ((he = gethostbyname(buf)) == NULL)
273 return - 1;
274 saddr->sin_addr = *(struct in_addr *)he->h_addr;
275 }
276 }
277 port = strtol(p, (char **)&r, 0);
278 if (r == p)
279 return -1;
280 saddr->sin_port = htons(port);
281 return 0;
282 }
283
284 #if !defined(_WIN32) && 0
285 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
286 {
287 const char *p;
288 int len;
289
290 len = MIN(108, strlen(str));
291 p = strchr(str, ',');
292 if (p)
293 len = MIN(len, p - str);
294
295 memset(uaddr, 0, sizeof(*uaddr));
296
297 uaddr->sun_family = AF_UNIX;
298 memcpy(uaddr->sun_path, str, len);
299
300 return 0;
301 }
302 #endif
303
304 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
305 {
306 snprintf(vc->info_str, sizeof(vc->info_str),
307 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
308 vc->model,
309 macaddr[0], macaddr[1], macaddr[2],
310 macaddr[3], macaddr[4], macaddr[5]);
311 }
312
313 static char *assign_name(VLANClientState *vc1, const char *model)
314 {
315 VLANState *vlan;
316 char buf[256];
317 int id = 0;
318
319 for (vlan = first_vlan; vlan; vlan = vlan->next) {
320 VLANClientState *vc;
321
322 for (vc = vlan->first_client; vc; vc = vc->next)
323 if (vc != vc1 && strcmp(vc->model, model) == 0)
324 id++;
325 }
326
327 snprintf(buf, sizeof(buf), "%s.%d", model, id);
328
329 return strdup(buf);
330 }
331
332 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
333 const char *model,
334 const char *name,
335 IOReadHandler *fd_read,
336 IOCanRWHandler *fd_can_read,
337 NetCleanup *cleanup,
338 void *opaque)
339 {
340 VLANClientState *vc, **pvc;
341 vc = qemu_mallocz(sizeof(VLANClientState));
342 vc->model = strdup(model);
343 if (name)
344 vc->name = strdup(name);
345 else
346 vc->name = assign_name(vc, model);
347 vc->fd_read = fd_read;
348 vc->fd_can_read = fd_can_read;
349 vc->cleanup = cleanup;
350 vc->opaque = opaque;
351 vc->vlan = vlan;
352
353 vc->next = NULL;
354 pvc = &vlan->first_client;
355 while (*pvc != NULL)
356 pvc = &(*pvc)->next;
357 *pvc = vc;
358 return vc;
359 }
360
361 void qemu_del_vlan_client(VLANClientState *vc)
362 {
363 VLANClientState **pvc = &vc->vlan->first_client;
364
365 while (*pvc != NULL)
366 if (*pvc == vc) {
367 *pvc = vc->next;
368 if (vc->cleanup) {
369 vc->cleanup(vc);
370 }
371 free(vc->name);
372 free(vc->model);
373 qemu_free(vc);
374 break;
375 } else
376 pvc = &(*pvc)->next;
377 }
378
379 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
380 {
381 VLANClientState **pvc = &vlan->first_client;
382
383 while (*pvc != NULL)
384 if ((*pvc)->opaque == opaque)
385 return *pvc;
386 else
387 pvc = &(*pvc)->next;
388
389 return NULL;
390 }
391
392 int qemu_can_send_packet(VLANClientState *vc1)
393 {
394 VLANState *vlan = vc1->vlan;
395 VLANClientState *vc;
396
397 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
398 if (vc != vc1) {
399 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
400 return 1;
401 }
402 }
403 return 0;
404 }
405
406 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
407 {
408 VLANState *vlan = vc1->vlan;
409 VLANClientState *vc;
410
411 if (vc1->link_down)
412 return;
413
414 #ifdef DEBUG_NET
415 printf("vlan %d send:\n", vlan->id);
416 hex_dump(stdout, buf, size);
417 #endif
418 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
419 if (vc != vc1 && !vc->link_down) {
420 vc->fd_read(vc->opaque, buf, size);
421 }
422 }
423 }
424
425 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
426 int iovcnt)
427 {
428 uint8_t buffer[4096];
429 size_t offset = 0;
430 int i;
431
432 for (i = 0; i < iovcnt; i++) {
433 size_t len;
434
435 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
436 memcpy(buffer + offset, iov[i].iov_base, len);
437 offset += len;
438 }
439
440 vc->fd_read(vc->opaque, buffer, offset);
441
442 return offset;
443 }
444
445 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
446 {
447 size_t offset = 0;
448 int i;
449
450 for (i = 0; i < iovcnt; i++)
451 offset += iov[i].iov_len;
452 return offset;
453 }
454
455 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
456 int iovcnt)
457 {
458 VLANState *vlan = vc1->vlan;
459 VLANClientState *vc;
460 ssize_t max_len = 0;
461
462 if (vc1->link_down)
463 return calc_iov_length(iov, iovcnt);
464
465 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
466 ssize_t len = 0;
467
468 if (vc == vc1)
469 continue;
470
471 if (vc->link_down)
472 len = calc_iov_length(iov, iovcnt);
473 if (vc->fd_readv)
474 len = vc->fd_readv(vc->opaque, iov, iovcnt);
475 else if (vc->fd_read)
476 len = vc_sendv_compat(vc, iov, iovcnt);
477
478 max_len = MAX(max_len, len);
479 }
480
481 return max_len;
482 }
483
484 #if defined(CONFIG_SLIRP)
485
486 /* slirp network adapter */
487
488 static int slirp_inited;
489 static int slirp_restrict;
490 static char *slirp_ip;
491 static VLANClientState *slirp_vc;
492
493 int slirp_can_output(void)
494 {
495 return !slirp_vc || qemu_can_send_packet(slirp_vc);
496 }
497
498 void slirp_output(const uint8_t *pkt, int pkt_len)
499 {
500 #ifdef DEBUG_SLIRP
501 printf("slirp output:\n");
502 hex_dump(stdout, pkt, pkt_len);
503 #endif
504 if (!slirp_vc)
505 return;
506 qemu_send_packet(slirp_vc, pkt, pkt_len);
507 }
508
509 int slirp_is_inited(void)
510 {
511 return slirp_inited;
512 }
513
514 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
515 {
516 #ifdef DEBUG_SLIRP
517 printf("slirp input:\n");
518 hex_dump(stdout, buf, size);
519 #endif
520 slirp_input(buf, size);
521 }
522
523 static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
524 {
525 if (!slirp_inited) {
526 slirp_inited = 1;
527 slirp_init(slirp_restrict, slirp_ip);
528 }
529 slirp_vc = qemu_new_vlan_client(vlan, model, name,
530 slirp_receive, NULL, NULL, NULL);
531 slirp_vc->info_str[0] = '\0';
532 return 0;
533 }
534
535 void net_slirp_redir(const char *redir_str)
536 {
537 int is_udp;
538 char buf[256], *r;
539 const char *p;
540 struct in_addr guest_addr;
541 int host_port, guest_port;
542
543 if (!slirp_inited) {
544 slirp_inited = 1;
545 slirp_init(slirp_restrict, slirp_ip);
546 }
547
548 p = redir_str;
549 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
550 goto fail;
551 if (!strcmp(buf, "tcp")) {
552 is_udp = 0;
553 } else if (!strcmp(buf, "udp")) {
554 is_udp = 1;
555 } else {
556 goto fail;
557 }
558
559 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
560 goto fail;
561 host_port = strtol(buf, &r, 0);
562 if (r == buf)
563 goto fail;
564
565 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
566 goto fail;
567 if (buf[0] == '\0') {
568 pstrcpy(buf, sizeof(buf), "10.0.2.15");
569 }
570 if (!inet_aton(buf, &guest_addr))
571 goto fail;
572
573 guest_port = strtol(p, &r, 0);
574 if (r == p)
575 goto fail;
576
577 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
578 fprintf(stderr, "qemu: could not set up redirection\n");
579 exit(1);
580 }
581 return;
582 fail:
583 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
584 exit(1);
585 }
586
587 #ifndef _WIN32
588
589 static char smb_dir[1024];
590
591 static void erase_dir(char *dir_name)
592 {
593 DIR *d;
594 struct dirent *de;
595 char filename[1024];
596
597 /* erase all the files in the directory */
598 if ((d = opendir(dir_name)) != NULL) {
599 for(;;) {
600 de = readdir(d);
601 if (!de)
602 break;
603 if (strcmp(de->d_name, ".") != 0 &&
604 strcmp(de->d_name, "..") != 0) {
605 snprintf(filename, sizeof(filename), "%s/%s",
606 smb_dir, de->d_name);
607 if (unlink(filename) != 0) /* is it a directory? */
608 erase_dir(filename);
609 }
610 }
611 closedir(d);
612 rmdir(dir_name);
613 }
614 }
615
616 /* automatic user mode samba server configuration */
617 static void smb_exit(void)
618 {
619 erase_dir(smb_dir);
620 }
621
622 /* automatic user mode samba server configuration */
623 void net_slirp_smb(const char *exported_dir)
624 {
625 char smb_conf[1024];
626 char smb_cmdline[1024];
627 FILE *f;
628
629 if (!slirp_inited) {
630 slirp_inited = 1;
631 slirp_init(slirp_restrict, slirp_ip);
632 }
633
634 /* XXX: better tmp dir construction */
635 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
636 if (mkdir(smb_dir, 0700) < 0) {
637 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
638 exit(1);
639 }
640 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
641
642 f = fopen(smb_conf, "w");
643 if (!f) {
644 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
645 exit(1);
646 }
647 fprintf(f,
648 "[global]\n"
649 "private dir=%s\n"
650 "smb ports=0\n"
651 "socket address=127.0.0.1\n"
652 "pid directory=%s\n"
653 "lock directory=%s\n"
654 "log file=%s/log.smbd\n"
655 "smb passwd file=%s/smbpasswd\n"
656 "security = share\n"
657 "[qemu]\n"
658 "path=%s\n"
659 "read only=no\n"
660 "guest ok=yes\n",
661 smb_dir,
662 smb_dir,
663 smb_dir,
664 smb_dir,
665 smb_dir,
666 exported_dir
667 );
668 fclose(f);
669 atexit(smb_exit);
670
671 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
672 SMBD_COMMAND, smb_conf);
673
674 slirp_add_exec(0, smb_cmdline, 4, 139);
675 }
676
677 #endif /* !defined(_WIN32) */
678 void do_info_slirp(Monitor *mon)
679 {
680 slirp_stats();
681 }
682
683 struct VMChannel {
684 CharDriverState *hd;
685 int port;
686 };
687
688 static int vmchannel_can_read(void *opaque)
689 {
690 struct VMChannel *vmc = (struct VMChannel*)opaque;
691 return slirp_socket_can_recv(4, vmc->port);
692 }
693
694 static void vmchannel_read(void *opaque, const uint8_t *buf, int size)
695 {
696 struct VMChannel *vmc = (struct VMChannel*)opaque;
697 slirp_socket_recv(4, vmc->port, buf, size);
698 }
699
700 #endif /* CONFIG_SLIRP */
701
702 #if !defined(_WIN32)
703
704 typedef struct TAPState {
705 VLANClientState *vc;
706 int fd;
707 char down_script[1024];
708 char down_script_arg[128];
709 } TAPState;
710
711 static int launch_script(const char *setup_script, const char *ifname, int fd);
712
713 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
714 int iovcnt)
715 {
716 TAPState *s = opaque;
717 ssize_t len;
718
719 do {
720 len = writev(s->fd, iov, iovcnt);
721 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
722
723 return len;
724 }
725
726 static void tap_receive(void *opaque, const uint8_t *buf, int size)
727 {
728 TAPState *s = opaque;
729 int ret;
730 for(;;) {
731 ret = write(s->fd, buf, size);
732 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
733 } else {
734 break;
735 }
736 }
737 }
738
739 static void tap_send(void *opaque)
740 {
741 TAPState *s = opaque;
742 uint8_t buf[4096];
743 int size;
744
745 #ifdef __sun__
746 struct strbuf sbuf;
747 int f = 0;
748 sbuf.maxlen = sizeof(buf);
749 sbuf.buf = (char *)buf;
750 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
751 #else
752 size = read(s->fd, buf, sizeof(buf));
753 #endif
754 if (size > 0) {
755 qemu_send_packet(s->vc, buf, size);
756 }
757 }
758
759 static void tap_cleanup(VLANClientState *vc)
760 {
761 TAPState *s = vc->opaque;
762
763 if (s->down_script[0])
764 launch_script(s->down_script, s->down_script_arg, s->fd);
765
766 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
767 close(s->fd);
768 qemu_free(s);
769 }
770
771 /* fd support */
772
773 static TAPState *net_tap_fd_init(VLANState *vlan,
774 const char *model,
775 const char *name,
776 int fd)
777 {
778 TAPState *s;
779
780 s = qemu_mallocz(sizeof(TAPState));
781 s->fd = fd;
782 s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive,
783 NULL, tap_cleanup, s);
784 s->vc->fd_readv = tap_receive_iov;
785 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
786 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
787 return s;
788 }
789
790 #if defined (HOST_BSD) || defined (__FreeBSD_kernel__)
791 static int tap_open(char *ifname, int ifname_size)
792 {
793 int fd;
794 char *dev;
795 struct stat s;
796
797 TFR(fd = open("/dev/tap", O_RDWR));
798 if (fd < 0) {
799 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
800 return -1;
801 }
802
803 fstat(fd, &s);
804 dev = devname(s.st_rdev, S_IFCHR);
805 pstrcpy(ifname, ifname_size, dev);
806
807 fcntl(fd, F_SETFL, O_NONBLOCK);
808 return fd;
809 }
810 #elif defined(__sun__)
811 #define TUNNEWPPA (('T'<<16) | 0x0001)
812 /*
813 * Allocate TAP device, returns opened fd.
814 * Stores dev name in the first arg(must be large enough).
815 */
816 static int tap_alloc(char *dev, size_t dev_size)
817 {
818 int tap_fd, if_fd, ppa = -1;
819 static int ip_fd = 0;
820 char *ptr;
821
822 static int arp_fd = 0;
823 int ip_muxid, arp_muxid;
824 struct strioctl strioc_if, strioc_ppa;
825 int link_type = I_PLINK;;
826 struct lifreq ifr;
827 char actual_name[32] = "";
828
829 memset(&ifr, 0x0, sizeof(ifr));
830
831 if( *dev ){
832 ptr = dev;
833 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
834 ppa = atoi(ptr);
835 }
836
837 /* Check if IP device was opened */
838 if( ip_fd )
839 close(ip_fd);
840
841 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
842 if (ip_fd < 0) {
843 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
844 return -1;
845 }
846
847 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
848 if (tap_fd < 0) {
849 syslog(LOG_ERR, "Can't open /dev/tap");
850 return -1;
851 }
852
853 /* Assign a new PPA and get its unit number. */
854 strioc_ppa.ic_cmd = TUNNEWPPA;
855 strioc_ppa.ic_timout = 0;
856 strioc_ppa.ic_len = sizeof(ppa);
857 strioc_ppa.ic_dp = (char *)&ppa;
858 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
859 syslog (LOG_ERR, "Can't assign new interface");
860
861 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
862 if (if_fd < 0) {
863 syslog(LOG_ERR, "Can't open /dev/tap (2)");
864 return -1;
865 }
866 if(ioctl(if_fd, I_PUSH, "ip") < 0){
867 syslog(LOG_ERR, "Can't push IP module");
868 return -1;
869 }
870
871 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
872 syslog(LOG_ERR, "Can't get flags\n");
873
874 snprintf (actual_name, 32, "tap%d", ppa);
875 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
876
877 ifr.lifr_ppa = ppa;
878 /* Assign ppa according to the unit number returned by tun device */
879
880 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
881 syslog (LOG_ERR, "Can't set PPA %d", ppa);
882 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
883 syslog (LOG_ERR, "Can't get flags\n");
884 /* Push arp module to if_fd */
885 if (ioctl (if_fd, I_PUSH, "arp") < 0)
886 syslog (LOG_ERR, "Can't push ARP module (2)");
887
888 /* Push arp module to ip_fd */
889 if (ioctl (ip_fd, I_POP, NULL) < 0)
890 syslog (LOG_ERR, "I_POP failed\n");
891 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
892 syslog (LOG_ERR, "Can't push ARP module (3)\n");
893 /* Open arp_fd */
894 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
895 if (arp_fd < 0)
896 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
897
898 /* Set ifname to arp */
899 strioc_if.ic_cmd = SIOCSLIFNAME;
900 strioc_if.ic_timout = 0;
901 strioc_if.ic_len = sizeof(ifr);
902 strioc_if.ic_dp = (char *)&ifr;
903 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
904 syslog (LOG_ERR, "Can't set ifname to arp\n");
905 }
906
907 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
908 syslog(LOG_ERR, "Can't link TAP device to IP");
909 return -1;
910 }
911
912 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
913 syslog (LOG_ERR, "Can't link TAP device to ARP");
914
915 close (if_fd);
916
917 memset(&ifr, 0x0, sizeof(ifr));
918 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
919 ifr.lifr_ip_muxid = ip_muxid;
920 ifr.lifr_arp_muxid = arp_muxid;
921
922 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
923 {
924 ioctl (ip_fd, I_PUNLINK , arp_muxid);
925 ioctl (ip_fd, I_PUNLINK, ip_muxid);
926 syslog (LOG_ERR, "Can't set multiplexor id");
927 }
928
929 snprintf(dev, dev_size, "tap%d", ppa);
930 return tap_fd;
931 }
932
933 static int tap_open(char *ifname, int ifname_size)
934 {
935 char dev[10]="";
936 int fd;
937 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
938 fprintf(stderr, "Cannot allocate TAP device\n");
939 return -1;
940 }
941 pstrcpy(ifname, ifname_size, dev);
942 fcntl(fd, F_SETFL, O_NONBLOCK);
943 return fd;
944 }
945 #elif defined (_AIX)
946 static int tap_open(char *ifname, int ifname_size)
947 {
948 fprintf (stderr, "no tap on AIX\n");
949 return -1;
950 }
951 #else
952 static int tap_open(char *ifname, int ifname_size)
953 {
954 struct ifreq ifr;
955 int fd, ret;
956
957 TFR(fd = open("/dev/net/tun", O_RDWR));
958 if (fd < 0) {
959 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
960 return -1;
961 }
962 memset(&ifr, 0, sizeof(ifr));
963 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
964 if (ifname[0] != '\0')
965 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
966 else
967 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
968 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
969 if (ret != 0) {
970 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
971 close(fd);
972 return -1;
973 }
974 pstrcpy(ifname, ifname_size, ifr.ifr_name);
975 fcntl(fd, F_SETFL, O_NONBLOCK);
976 return fd;
977 }
978 #endif
979
980 static int launch_script(const char *setup_script, const char *ifname, int fd)
981 {
982 int pid, status;
983 char *args[3];
984 char **parg;
985
986 /* try to launch network script */
987 pid = fork();
988 if (pid >= 0) {
989 if (pid == 0) {
990 int open_max = sysconf (_SC_OPEN_MAX), i;
991 for (i = 0; i < open_max; i++)
992 if (i != STDIN_FILENO &&
993 i != STDOUT_FILENO &&
994 i != STDERR_FILENO &&
995 i != fd)
996 close(i);
997
998 parg = args;
999 *parg++ = (char *)setup_script;
1000 *parg++ = (char *)ifname;
1001 *parg++ = NULL;
1002 execv(setup_script, args);
1003 _exit(1);
1004 }
1005 while (waitpid(pid, &status, 0) != pid);
1006 if (!WIFEXITED(status) ||
1007 WEXITSTATUS(status) != 0) {
1008 fprintf(stderr, "%s: could not launch network script\n",
1009 setup_script);
1010 return -1;
1011 }
1012 }
1013 return 0;
1014 }
1015
1016 static int net_tap_init(VLANState *vlan, const char *model,
1017 const char *name, const char *ifname1,
1018 const char *setup_script, const char *down_script)
1019 {
1020 TAPState *s;
1021 int fd;
1022 char ifname[128];
1023
1024 if (ifname1 != NULL)
1025 pstrcpy(ifname, sizeof(ifname), ifname1);
1026 else
1027 ifname[0] = '\0';
1028 TFR(fd = tap_open(ifname, sizeof(ifname)));
1029 if (fd < 0)
1030 return -1;
1031
1032 if (!setup_script || !strcmp(setup_script, "no"))
1033 setup_script = "";
1034 if (setup_script[0] != '\0') {
1035 if (launch_script(setup_script, ifname, fd))
1036 return -1;
1037 }
1038 s = net_tap_fd_init(vlan, model, name, fd);
1039 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1040 "ifname=%s,script=%s,downscript=%s",
1041 ifname, setup_script, down_script);
1042 if (down_script && strcmp(down_script, "no")) {
1043 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1044 snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1045 }
1046 return 0;
1047 }
1048
1049 #endif /* !_WIN32 */
1050
1051 #if defined(CONFIG_VDE)
1052 typedef struct VDEState {
1053 VLANClientState *vc;
1054 VDECONN *vde;
1055 } VDEState;
1056
1057 static void vde_to_qemu(void *opaque)
1058 {
1059 VDEState *s = opaque;
1060 uint8_t buf[4096];
1061 int size;
1062
1063 size = vde_recv(s->vde, buf, sizeof(buf), 0);
1064 if (size > 0) {
1065 qemu_send_packet(s->vc, buf, size);
1066 }
1067 }
1068
1069 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1070 {
1071 VDEState *s = opaque;
1072 int ret;
1073 for(;;) {
1074 ret = vde_send(s->vde, buf, size, 0);
1075 if (ret < 0 && errno == EINTR) {
1076 } else {
1077 break;
1078 }
1079 }
1080 }
1081
1082 static void vde_cleanup(VLANClientState *vc)
1083 {
1084 VDEState *s = vc->opaque;
1085 qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
1086 vde_close(s->vde);
1087 qemu_free(s);
1088 }
1089
1090 static int net_vde_init(VLANState *vlan, const char *model,
1091 const char *name, const char *sock,
1092 int port, const char *group, int mode)
1093 {
1094 VDEState *s;
1095 char *init_group = strlen(group) ? (char *)group : NULL;
1096 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1097
1098 struct vde_open_args args = {
1099 .port = port,
1100 .group = init_group,
1101 .mode = mode,
1102 };
1103
1104 s = qemu_mallocz(sizeof(VDEState));
1105 s->vde = vde_open(init_sock, "QEMU", &args);
1106 if (!s->vde){
1107 free(s);
1108 return -1;
1109 }
1110 s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu,
1111 NULL, vde_cleanup, s);
1112 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1113 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1114 sock, vde_datafd(s->vde));
1115 return 0;
1116 }
1117 #endif
1118
1119 /* network connection */
1120 typedef struct NetSocketState {
1121 VLANClientState *vc;
1122 int fd;
1123 int state; /* 0 = getting length, 1 = getting data */
1124 unsigned int index;
1125 unsigned int packet_len;
1126 uint8_t buf[4096];
1127 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1128 } NetSocketState;
1129
1130 typedef struct NetSocketListenState {
1131 VLANState *vlan;
1132 char *model;
1133 char *name;
1134 int fd;
1135 } NetSocketListenState;
1136
1137 /* XXX: we consider we can send the whole packet without blocking */
1138 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1139 {
1140 NetSocketState *s = opaque;
1141 uint32_t len;
1142 len = htonl(size);
1143
1144 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1145 send_all(s->fd, buf, size);
1146 }
1147
1148 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1149 {
1150 NetSocketState *s = opaque;
1151 sendto(s->fd, buf, size, 0,
1152 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1153 }
1154
1155 static void net_socket_send(void *opaque)
1156 {
1157 NetSocketState *s = opaque;
1158 int size, err;
1159 unsigned l;
1160 uint8_t buf1[4096];
1161 const uint8_t *buf;
1162
1163 size = recv(s->fd, buf1, sizeof(buf1), 0);
1164 if (size < 0) {
1165 err = socket_error();
1166 if (err != EWOULDBLOCK)
1167 goto eoc;
1168 } else if (size == 0) {
1169 /* end of connection */
1170 eoc:
1171 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1172 closesocket(s->fd);
1173 return;
1174 }
1175 buf = buf1;
1176 while (size > 0) {
1177 /* reassemble a packet from the network */
1178 switch(s->state) {
1179 case 0:
1180 l = 4 - s->index;
1181 if (l > size)
1182 l = size;
1183 memcpy(s->buf + s->index, buf, l);
1184 buf += l;
1185 size -= l;
1186 s->index += l;
1187 if (s->index == 4) {
1188 /* got length */
1189 s->packet_len = ntohl(*(uint32_t *)s->buf);
1190 s->index = 0;
1191 s->state = 1;
1192 }
1193 break;
1194 case 1:
1195 l = s->packet_len - s->index;
1196 if (l > size)
1197 l = size;
1198 if (s->index + l <= sizeof(s->buf)) {
1199 memcpy(s->buf + s->index, buf, l);
1200 } else {
1201 fprintf(stderr, "serious error: oversized packet received,"
1202 "connection terminated.\n");
1203 s->state = 0;
1204 goto eoc;
1205 }
1206
1207 s->index += l;
1208 buf += l;
1209 size -= l;
1210 if (s->index >= s->packet_len) {
1211 qemu_send_packet(s->vc, s->buf, s->packet_len);
1212 s->index = 0;
1213 s->state = 0;
1214 }
1215 break;
1216 }
1217 }
1218 }
1219
1220 static void net_socket_send_dgram(void *opaque)
1221 {
1222 NetSocketState *s = opaque;
1223 int size;
1224
1225 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1226 if (size < 0)
1227 return;
1228 if (size == 0) {
1229 /* end of connection */
1230 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1231 return;
1232 }
1233 qemu_send_packet(s->vc, s->buf, size);
1234 }
1235
1236 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1237 {
1238 struct ip_mreq imr;
1239 int fd;
1240 int val, ret;
1241 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1242 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1243 inet_ntoa(mcastaddr->sin_addr),
1244 (int)ntohl(mcastaddr->sin_addr.s_addr));
1245 return -1;
1246
1247 }
1248 fd = socket(PF_INET, SOCK_DGRAM, 0);
1249 if (fd < 0) {
1250 perror("socket(PF_INET, SOCK_DGRAM)");
1251 return -1;
1252 }
1253
1254 val = 1;
1255 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1256 (const char *)&val, sizeof(val));
1257 if (ret < 0) {
1258 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1259 goto fail;
1260 }
1261
1262 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1263 if (ret < 0) {
1264 perror("bind");
1265 goto fail;
1266 }
1267
1268 /* Add host to multicast group */
1269 imr.imr_multiaddr = mcastaddr->sin_addr;
1270 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1271
1272 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1273 (const char *)&imr, sizeof(struct ip_mreq));
1274 if (ret < 0) {
1275 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1276 goto fail;
1277 }
1278
1279 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1280 val = 1;
1281 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1282 (const char *)&val, sizeof(val));
1283 if (ret < 0) {
1284 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1285 goto fail;
1286 }
1287
1288 socket_set_nonblock(fd);
1289 return fd;
1290 fail:
1291 if (fd >= 0)
1292 closesocket(fd);
1293 return -1;
1294 }
1295
1296 static void net_socket_cleanup(VLANClientState *vc)
1297 {
1298 NetSocketState *s = vc->opaque;
1299 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1300 close(s->fd);
1301 qemu_free(s);
1302 }
1303
1304 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1305 const char *model,
1306 const char *name,
1307 int fd, int is_connected)
1308 {
1309 struct sockaddr_in saddr;
1310 int newfd;
1311 socklen_t saddr_len;
1312 NetSocketState *s;
1313
1314 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1315 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1316 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1317 */
1318
1319 if (is_connected) {
1320 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1321 /* must be bound */
1322 if (saddr.sin_addr.s_addr==0) {
1323 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1324 fd);
1325 return NULL;
1326 }
1327 /* clone dgram socket */
1328 newfd = net_socket_mcast_create(&saddr);
1329 if (newfd < 0) {
1330 /* error already reported by net_socket_mcast_create() */
1331 close(fd);
1332 return NULL;
1333 }
1334 /* clone newfd to fd, close newfd */
1335 dup2(newfd, fd);
1336 close(newfd);
1337
1338 } else {
1339 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1340 fd, strerror(errno));
1341 return NULL;
1342 }
1343 }
1344
1345 s = qemu_mallocz(sizeof(NetSocketState));
1346 s->fd = fd;
1347
1348 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram,
1349 NULL, net_socket_cleanup, s);
1350 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1351
1352 /* mcast: save bound address as dst */
1353 if (is_connected) s->dgram_dst=saddr;
1354
1355 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1356 "socket: fd=%d (%s mcast=%s:%d)",
1357 fd, is_connected? "cloned" : "",
1358 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1359 return s;
1360 }
1361
1362 static void net_socket_connect(void *opaque)
1363 {
1364 NetSocketState *s = opaque;
1365 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1366 }
1367
1368 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1369 const char *model,
1370 const char *name,
1371 int fd, int is_connected)
1372 {
1373 NetSocketState *s;
1374 s = qemu_mallocz(sizeof(NetSocketState));
1375 s->fd = fd;
1376 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive,
1377 NULL, net_socket_cleanup, s);
1378 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1379 "socket: fd=%d", fd);
1380 if (is_connected) {
1381 net_socket_connect(s);
1382 } else {
1383 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1384 }
1385 return s;
1386 }
1387
1388 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1389 const char *model, const char *name,
1390 int fd, int is_connected)
1391 {
1392 int so_type=-1, optlen=sizeof(so_type);
1393
1394 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1395 (socklen_t *)&optlen)< 0) {
1396 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1397 return NULL;
1398 }
1399 switch(so_type) {
1400 case SOCK_DGRAM:
1401 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1402 case SOCK_STREAM:
1403 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1404 default:
1405 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1406 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1407 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1408 }
1409 return NULL;
1410 }
1411
1412 static void net_socket_accept(void *opaque)
1413 {
1414 NetSocketListenState *s = opaque;
1415 NetSocketState *s1;
1416 struct sockaddr_in saddr;
1417 socklen_t len;
1418 int fd;
1419
1420 for(;;) {
1421 len = sizeof(saddr);
1422 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1423 if (fd < 0 && errno != EINTR) {
1424 return;
1425 } else if (fd >= 0) {
1426 break;
1427 }
1428 }
1429 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1430 if (!s1) {
1431 closesocket(fd);
1432 } else {
1433 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1434 "socket: connection from %s:%d",
1435 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1436 }
1437 }
1438
1439 static int net_socket_listen_init(VLANState *vlan,
1440 const char *model,
1441 const char *name,
1442 const char *host_str)
1443 {
1444 NetSocketListenState *s;
1445 int fd, val, ret;
1446 struct sockaddr_in saddr;
1447
1448 if (parse_host_port(&saddr, host_str) < 0)
1449 return -1;
1450
1451 s = qemu_mallocz(sizeof(NetSocketListenState));
1452
1453 fd = socket(PF_INET, SOCK_STREAM, 0);
1454 if (fd < 0) {
1455 perror("socket");
1456 return -1;
1457 }
1458 socket_set_nonblock(fd);
1459
1460 /* allow fast reuse */
1461 val = 1;
1462 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1463
1464 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1465 if (ret < 0) {
1466 perror("bind");
1467 return -1;
1468 }
1469 ret = listen(fd, 0);
1470 if (ret < 0) {
1471 perror("listen");
1472 return -1;
1473 }
1474 s->vlan = vlan;
1475 s->model = strdup(model);
1476 s->name = name ? strdup(name) : NULL;
1477 s->fd = fd;
1478 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1479 return 0;
1480 }
1481
1482 static int net_socket_connect_init(VLANState *vlan,
1483 const char *model,
1484 const char *name,
1485 const char *host_str)
1486 {
1487 NetSocketState *s;
1488 int fd, connected, ret, err;
1489 struct sockaddr_in saddr;
1490
1491 if (parse_host_port(&saddr, host_str) < 0)
1492 return -1;
1493
1494 fd = socket(PF_INET, SOCK_STREAM, 0);
1495 if (fd < 0) {
1496 perror("socket");
1497 return -1;
1498 }
1499 socket_set_nonblock(fd);
1500
1501 connected = 0;
1502 for(;;) {
1503 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1504 if (ret < 0) {
1505 err = socket_error();
1506 if (err == EINTR || err == EWOULDBLOCK) {
1507 } else if (err == EINPROGRESS) {
1508 break;
1509 #ifdef _WIN32
1510 } else if (err == WSAEALREADY) {
1511 break;
1512 #endif
1513 } else {
1514 perror("connect");
1515 closesocket(fd);
1516 return -1;
1517 }
1518 } else {
1519 connected = 1;
1520 break;
1521 }
1522 }
1523 s = net_socket_fd_init(vlan, model, name, fd, connected);
1524 if (!s)
1525 return -1;
1526 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1527 "socket: connect to %s:%d",
1528 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1529 return 0;
1530 }
1531
1532 static int net_socket_mcast_init(VLANState *vlan,
1533 const char *model,
1534 const char *name,
1535 const char *host_str)
1536 {
1537 NetSocketState *s;
1538 int fd;
1539 struct sockaddr_in saddr;
1540
1541 if (parse_host_port(&saddr, host_str) < 0)
1542 return -1;
1543
1544
1545 fd = net_socket_mcast_create(&saddr);
1546 if (fd < 0)
1547 return -1;
1548
1549 s = net_socket_fd_init(vlan, model, name, fd, 0);
1550 if (!s)
1551 return -1;
1552
1553 s->dgram_dst = saddr;
1554
1555 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1556 "socket: mcast=%s:%d",
1557 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1558 return 0;
1559
1560 }
1561
1562 typedef struct DumpState {
1563 VLANClientState *pcap_vc;
1564 int fd;
1565 int pcap_caplen;
1566 } DumpState;
1567
1568 #define PCAP_MAGIC 0xa1b2c3d4
1569
1570 struct pcap_file_hdr {
1571 uint32_t magic;
1572 uint16_t version_major;
1573 uint16_t version_minor;
1574 int32_t thiszone;
1575 uint32_t sigfigs;
1576 uint32_t snaplen;
1577 uint32_t linktype;
1578 };
1579
1580 struct pcap_sf_pkthdr {
1581 struct {
1582 int32_t tv_sec;
1583 int32_t tv_usec;
1584 } ts;
1585 uint32_t caplen;
1586 uint32_t len;
1587 };
1588
1589 static void dump_receive(void *opaque, const uint8_t *buf, int size)
1590 {
1591 DumpState *s = opaque;
1592 struct pcap_sf_pkthdr hdr;
1593 int64_t ts;
1594 int caplen;
1595
1596 /* Early return in case of previous error. */
1597 if (s->fd < 0) {
1598 return;
1599 }
1600
1601 ts = muldiv64 (qemu_get_clock(vm_clock),1000000, ticks_per_sec);
1602 caplen = size > s->pcap_caplen ? s->pcap_caplen : size;
1603
1604 hdr.ts.tv_sec = ts / 1000000000LL;
1605 hdr.ts.tv_usec = ts % 1000000;
1606 hdr.caplen = caplen;
1607 hdr.len = size;
1608 if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||
1609 write(s->fd, buf, caplen) != caplen) {
1610 qemu_log("-net dump write error - stop dump\n");
1611 close(s->fd);
1612 s->fd = -1;
1613 }
1614 }
1615
1616 static void net_dump_cleanup(VLANClientState *vc)
1617 {
1618 DumpState *s = vc->opaque;
1619
1620 close(s->fd);
1621 qemu_free(s);
1622 }
1623
1624 static int net_dump_init(VLANState *vlan, const char *device,
1625 const char *name, const char *filename, int len)
1626 {
1627 struct pcap_file_hdr hdr;
1628 DumpState *s;
1629
1630 s = qemu_malloc(sizeof(DumpState));
1631
1632 s->fd = open(filename, O_CREAT | O_WRONLY, 0644);
1633 if (s->fd < 0) {
1634 fprintf(stderr, "-net dump: can't open %s\n", filename);
1635 return -1;
1636 }
1637
1638 s->pcap_caplen = len;
1639
1640 hdr.magic = PCAP_MAGIC;
1641 hdr.version_major = 2;
1642 hdr.version_minor = 4;
1643 hdr.thiszone = 0;
1644 hdr.sigfigs = 0;
1645 hdr.snaplen = s->pcap_caplen;
1646 hdr.linktype = 1;
1647
1648 if (write(s->fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
1649 perror("-net dump write error");
1650 close(s->fd);
1651 qemu_free(s);
1652 return -1;
1653 }
1654
1655 s->pcap_vc = qemu_new_vlan_client(vlan, device, name, dump_receive, NULL,
1656 net_dump_cleanup, s);
1657 snprintf(s->pcap_vc->info_str, sizeof(s->pcap_vc->info_str),
1658 "dump to %s (len=%d)", filename, len);
1659 return 0;
1660 }
1661
1662 /* find or alloc a new VLAN */
1663 VLANState *qemu_find_vlan(int id)
1664 {
1665 VLANState **pvlan, *vlan;
1666 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1667 if (vlan->id == id)
1668 return vlan;
1669 }
1670 vlan = qemu_mallocz(sizeof(VLANState));
1671 vlan->id = id;
1672 vlan->next = NULL;
1673 pvlan = &first_vlan;
1674 while (*pvlan != NULL)
1675 pvlan = &(*pvlan)->next;
1676 *pvlan = vlan;
1677 return vlan;
1678 }
1679
1680 static int nic_get_free_idx(void)
1681 {
1682 int index;
1683
1684 for (index = 0; index < MAX_NICS; index++)
1685 if (!nd_table[index].used)
1686 return index;
1687 return -1;
1688 }
1689
1690 void qemu_check_nic_model(NICInfo *nd, const char *model)
1691 {
1692 const char *models[2];
1693
1694 models[0] = model;
1695 models[1] = NULL;
1696
1697 qemu_check_nic_model_list(nd, models, model);
1698 }
1699
1700 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1701 const char *default_model)
1702 {
1703 int i, exit_status = 0;
1704
1705 if (!nd->model)
1706 nd->model = strdup(default_model);
1707
1708 if (strcmp(nd->model, "?") != 0) {
1709 for (i = 0 ; models[i]; i++)
1710 if (strcmp(nd->model, models[i]) == 0)
1711 return;
1712
1713 fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1714 exit_status = 1;
1715 }
1716
1717 fprintf(stderr, "qemu: Supported NIC models: ");
1718 for (i = 0 ; models[i]; i++)
1719 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1720
1721 exit(exit_status);
1722 }
1723
1724 int net_client_init(const char *device, const char *p)
1725 {
1726 static const char * const fd_params[] = {
1727 "vlan", "name", "fd", NULL
1728 };
1729 char buf[1024];
1730 int vlan_id, ret;
1731 VLANState *vlan;
1732 char *name = NULL;
1733
1734 vlan_id = 0;
1735 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1736 vlan_id = strtol(buf, NULL, 0);
1737 }
1738 vlan = qemu_find_vlan(vlan_id);
1739
1740 if (get_param_value(buf, sizeof(buf), "name", p)) {
1741 name = strdup(buf);
1742 }
1743 if (!strcmp(device, "nic")) {
1744 static const char * const nic_params[] = {
1745 "vlan", "name", "macaddr", "model", NULL
1746 };
1747 NICInfo *nd;
1748 uint8_t *macaddr;
1749 int idx = nic_get_free_idx();
1750
1751 if (check_params(buf, sizeof(buf), nic_params, p) < 0) {
1752 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1753 buf, p);
1754 return -1;
1755 }
1756 if (idx == -1 || nb_nics >= MAX_NICS) {
1757 fprintf(stderr, "Too Many NICs\n");
1758 ret = -1;
1759 goto out;
1760 }
1761 nd = &nd_table[idx];
1762 macaddr = nd->macaddr;
1763 macaddr[0] = 0x52;
1764 macaddr[1] = 0x54;
1765 macaddr[2] = 0x00;
1766 macaddr[3] = 0x12;
1767 macaddr[4] = 0x34;
1768 macaddr[5] = 0x56 + idx;
1769
1770 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1771 if (parse_macaddr(macaddr, buf) < 0) {
1772 fprintf(stderr, "invalid syntax for ethernet address\n");
1773 ret = -1;
1774 goto out;
1775 }
1776 }
1777 if (get_param_value(buf, sizeof(buf), "model", p)) {
1778 nd->model = strdup(buf);
1779 }
1780 nd->vlan = vlan;
1781 nd->name = name;
1782 nd->used = 1;
1783 name = NULL;
1784 nb_nics++;
1785 vlan->nb_guest_devs++;
1786 ret = idx;
1787 } else
1788 if (!strcmp(device, "none")) {
1789 if (*p != '\0') {
1790 fprintf(stderr, "qemu: 'none' takes no parameters\n");
1791 return -1;
1792 }
1793 /* does nothing. It is needed to signal that no network cards
1794 are wanted */
1795 ret = 0;
1796 } else
1797 #ifdef CONFIG_SLIRP
1798 if (!strcmp(device, "user")) {
1799 static const char * const slirp_params[] = {
1800 "vlan", "name", "hostname", "restrict", "ip", NULL
1801 };
1802 if (check_params(buf, sizeof(buf), slirp_params, p) < 0) {
1803 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1804 buf, p);
1805 return -1;
1806 }
1807 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1808 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1809 }
1810 if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1811 slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1812 }
1813 if (get_param_value(buf, sizeof(buf), "ip", p)) {
1814 slirp_ip = strdup(buf);
1815 }
1816 vlan->nb_host_devs++;
1817 ret = net_slirp_init(vlan, device, name);
1818 } else if (!strcmp(device, "channel")) {
1819 long port;
1820 char name[20], *devname;
1821 struct VMChannel *vmc;
1822
1823 port = strtol(p, &devname, 10);
1824 devname++;
1825 if (port < 1 || port > 65535) {
1826 fprintf(stderr, "vmchannel wrong port number\n");
1827 ret = -1;
1828 goto out;
1829 }
1830 vmc = malloc(sizeof(struct VMChannel));
1831 snprintf(name, 20, "vmchannel%ld", port);
1832 vmc->hd = qemu_chr_open(name, devname, NULL);
1833 if (!vmc->hd) {
1834 fprintf(stderr, "qemu: could not open vmchannel device"
1835 "'%s'\n", devname);
1836 ret = -1;
1837 goto out;
1838 }
1839 vmc->port = port;
1840 slirp_add_exec(3, vmc->hd, 4, port);
1841 qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
1842 NULL, vmc);
1843 ret = 0;
1844 } else
1845 #endif
1846 #ifdef _WIN32
1847 if (!strcmp(device, "tap")) {
1848 static const char * const tap_params[] = {
1849 "vlan", "name", "ifname", NULL
1850 };
1851 char ifname[64];
1852
1853 if (check_params(buf, sizeof(buf), tap_params, p) < 0) {
1854 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1855 buf, p);
1856 return -1;
1857 }
1858 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1859 fprintf(stderr, "tap: no interface name\n");
1860 ret = -1;
1861 goto out;
1862 }
1863 vlan->nb_host_devs++;
1864 ret = tap_win32_init(vlan, device, name, ifname);
1865 } else
1866 #elif defined (_AIX)
1867 #else
1868 if (!strcmp(device, "tap")) {
1869 char ifname[64];
1870 char setup_script[1024], down_script[1024];
1871 int fd;
1872 vlan->nb_host_devs++;
1873 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1874 if (check_params(buf, sizeof(buf), fd_params, p) < 0) {
1875 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1876 buf, p);
1877 return -1;
1878 }
1879 fd = strtol(buf, NULL, 0);
1880 fcntl(fd, F_SETFL, O_NONBLOCK);
1881 net_tap_fd_init(vlan, device, name, fd);
1882 ret = 0;
1883 } else {
1884 static const char * const tap_params[] = {
1885 "vlan", "name", "ifname", "script", "downscript", NULL
1886 };
1887 if (check_params(buf, sizeof(buf), tap_params, p) < 0) {
1888 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1889 buf, p);
1890 return -1;
1891 }
1892 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1893 ifname[0] = '\0';
1894 }
1895 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1896 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1897 }
1898 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1899 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1900 }
1901 ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1902 }
1903 } else
1904 #endif
1905 if (!strcmp(device, "socket")) {
1906 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1907 int fd;
1908 if (check_params(buf, sizeof(buf), fd_params, p) < 0) {
1909 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1910 buf, p);
1911 return -1;
1912 }
1913 fd = strtol(buf, NULL, 0);
1914 ret = -1;
1915 if (net_socket_fd_init(vlan, device, name, fd, 1))
1916 ret = 0;
1917 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1918 static const char * const listen_params[] = {
1919 "vlan", "name", "listen", NULL
1920 };
1921 if (check_params(buf, sizeof(buf), listen_params, p) < 0) {
1922 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1923 buf, p);
1924 return -1;
1925 }
1926 ret = net_socket_listen_init(vlan, device, name, buf);
1927 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1928 static const char * const connect_params[] = {
1929 "vlan", "name", "connect", NULL
1930 };
1931 if (check_params(buf, sizeof(buf), connect_params, p) < 0) {
1932 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1933 buf, p);
1934 return -1;
1935 }
1936 ret = net_socket_connect_init(vlan, device, name, buf);
1937 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1938 static const char * const mcast_params[] = {
1939 "vlan", "name", "mcast", NULL
1940 };
1941 if (check_params(buf, sizeof(buf), mcast_params, p) < 0) {
1942 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1943 buf, p);
1944 return -1;
1945 }
1946 ret = net_socket_mcast_init(vlan, device, name, buf);
1947 } else {
1948 fprintf(stderr, "Unknown socket options: %s\n", p);
1949 ret = -1;
1950 goto out;
1951 }
1952 vlan->nb_host_devs++;
1953 } else
1954 #ifdef CONFIG_VDE
1955 if (!strcmp(device, "vde")) {
1956 static const char * const vde_params[] = {
1957 "vlan", "name", "sock", "port", "group", "mode", NULL
1958 };
1959 char vde_sock[1024], vde_group[512];
1960 int vde_port, vde_mode;
1961
1962 if (check_params(buf, sizeof(buf), vde_params, p) < 0) {
1963 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1964 buf, p);
1965 return -1;
1966 }
1967 vlan->nb_host_devs++;
1968 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1969 vde_sock[0] = '\0';
1970 }
1971 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1972 vde_port = strtol(buf, NULL, 10);
1973 } else {
1974 vde_port = 0;
1975 }
1976 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1977 vde_group[0] = '\0';
1978 }
1979 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1980 vde_mode = strtol(buf, NULL, 8);
1981 } else {
1982 vde_mode = 0700;
1983 }
1984 ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
1985 } else
1986 #endif
1987 if (!strcmp(device, "dump")) {
1988 int len = 65536;
1989
1990 if (get_param_value(buf, sizeof(buf), "len", p) > 0) {
1991 len = strtol(buf, NULL, 0);
1992 }
1993 if (!get_param_value(buf, sizeof(buf), "file", p)) {
1994 snprintf(buf, sizeof(buf), "qemu-vlan%d.pcap", vlan_id);
1995 }
1996 ret = net_dump_init(vlan, device, name, buf, len);
1997 } else {
1998 fprintf(stderr, "Unknown network device: %s\n", device);
1999 ret = -1;
2000 goto out;
2001 }
2002 if (ret < 0) {
2003 fprintf(stderr, "Could not initialize device '%s'\n", device);
2004 }
2005 out:
2006 if (name)
2007 free(name);
2008 return ret;
2009 }
2010
2011 void net_client_uninit(NICInfo *nd)
2012 {
2013 nd->vlan->nb_guest_devs--;
2014 nb_nics--;
2015 nd->used = 0;
2016 free((void *)nd->model);
2017 }
2018
2019 static int net_host_check_device(const char *device)
2020 {
2021 int i;
2022 const char *valid_param_list[] = { "tap", "socket", "dump"
2023 #ifdef CONFIG_SLIRP
2024 ,"user"
2025 #endif
2026 #ifdef CONFIG_VDE
2027 ,"vde"
2028 #endif
2029 };
2030 for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
2031 if (!strncmp(valid_param_list[i], device,
2032 strlen(valid_param_list[i])))
2033 return 1;
2034 }
2035
2036 return 0;
2037 }
2038
2039 void net_host_device_add(Monitor *mon, const char *device, const char *opts)
2040 {
2041 if (!net_host_check_device(device)) {
2042 monitor_printf(mon, "invalid host network device %s\n", device);
2043 return;
2044 }
2045 net_client_init(device, opts);
2046 }
2047
2048 void net_host_device_remove(Monitor *mon, int vlan_id, const char *device)
2049 {
2050 VLANState *vlan;
2051 VLANClientState *vc;
2052
2053 vlan = qemu_find_vlan(vlan_id);
2054
2055 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
2056 if (!strcmp(vc->name, device)) {
2057 break;
2058 }
2059 }
2060
2061 if (!vc) {
2062 monitor_printf(mon, "can't find device %s\n", device);
2063 return;
2064 }
2065 if (!net_host_check_device(vc->model)) {
2066 monitor_printf(mon, "invalid host network device %s\n", device);
2067 return;
2068 }
2069 qemu_del_vlan_client(vc);
2070 }
2071
2072 int net_client_parse(const char *str)
2073 {
2074 const char *p;
2075 char *q;
2076 char device[64];
2077
2078 p = str;
2079 q = device;
2080 while (*p != '\0' && *p != ',') {
2081 if ((q - device) < sizeof(device) - 1)
2082 *q++ = *p;
2083 p++;
2084 }
2085 *q = '\0';
2086 if (*p == ',')
2087 p++;
2088
2089 return net_client_init(device, p);
2090 }
2091
2092 void do_info_network(Monitor *mon)
2093 {
2094 VLANState *vlan;
2095 VLANClientState *vc;
2096
2097 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2098 monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
2099 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2100 monitor_printf(mon, " %s: %s\n", vc->name, vc->info_str);
2101 }
2102 }
2103
2104 int do_set_link(Monitor *mon, const char *name, const char *up_or_down)
2105 {
2106 VLANState *vlan;
2107 VLANClientState *vc = NULL;
2108
2109 for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2110 for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2111 if (strcmp(vc->name, name) == 0)
2112 goto done;
2113 done:
2114
2115 if (!vc) {
2116 monitor_printf(mon, "could not find network device '%s'", name);
2117 return 0;
2118 }
2119
2120 if (strcmp(up_or_down, "up") == 0)
2121 vc->link_down = 0;
2122 else if (strcmp(up_or_down, "down") == 0)
2123 vc->link_down = 1;
2124 else
2125 monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
2126 "valid\n", up_or_down);
2127
2128 if (vc->link_status_changed)
2129 vc->link_status_changed(vc);
2130
2131 return 1;
2132 }
2133
2134 void net_cleanup(void)
2135 {
2136 VLANState *vlan;
2137
2138 /* close network clients */
2139 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2140 VLANClientState *vc = vlan->first_client;
2141
2142 while (vc) {
2143 VLANClientState *next = vc->next;
2144
2145 qemu_del_vlan_client(vc);
2146
2147 vc = next;
2148 }
2149 }
2150 }
2151
2152 void net_client_check(void)
2153 {
2154 VLANState *vlan;
2155
2156 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2157 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2158 continue;
2159 if (vlan->nb_guest_devs == 0)
2160 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2161 if (vlan->nb_host_devs == 0)
2162 fprintf(stderr,
2163 "Warning: vlan %d is not connected to host network\n",
2164 vlan->id);
2165 }
2166 }