1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // A simulated network for use within NaCl. 6 // The simulation is not particularly tied to NaCl, 7 // but other systems have real networks. 8 9 package syscall 10 11 import ( 12 "sync" 13 "sync/atomic" 14 ) 15 16 // Interface to timers implemented in package runtime. 17 // Must be in sync with ../runtime/runtime.h:/^struct.Timer$ 18 // Really for use by package time, but we cannot import time here. 19 20 type runtimeTimer struct { 21 i int 22 when int64 23 period int64 24 f func(interface{}, uintptr) // NOTE: must not be closure 25 arg interface{} 26 seq uintptr 27 } 28 29 func startTimer(*runtimeTimer) 30 func stopTimer(*runtimeTimer) bool 31 32 type timer struct { 33 expired bool 34 q *queue 35 r runtimeTimer 36 } 37 38 func (t *timer) start(q *queue, deadline int64) { 39 if deadline == 0 { 40 return 41 } 42 t.q = q 43 t.r.when = deadline 44 t.r.f = timerExpired 45 t.r.arg = t 46 startTimer(&t.r) 47 } 48 49 func (t *timer) stop() { 50 stopTimer(&t.r) 51 } 52 53 func timerExpired(i interface{}, seq uintptr) { 54 t := i.(*timer) 55 go func() { 56 t.q.Lock() 57 defer t.q.Unlock() 58 t.expired = true 59 t.q.canRead.Broadcast() 60 t.q.canWrite.Broadcast() 61 }() 62 } 63 64 // Network constants and data structures. These match the traditional values. 65 66 const ( 67 AF_UNSPEC = iota 68 AF_UNIX 69 AF_INET 70 AF_INET6 71 ) 72 73 const ( 74 SHUT_RD = iota 75 SHUT_WR 76 SHUT_RDWR 77 ) 78 79 const ( 80 SOCK_STREAM = 1 + iota 81 SOCK_DGRAM 82 SOCK_RAW 83 SOCK_SEQPACKET 84 ) 85 86 const ( 87 IPPROTO_IP = 0 88 IPPROTO_IPV4 = 4 89 IPPROTO_IPV6 = 0x29 90 IPPROTO_TCP = 6 91 IPPROTO_UDP = 0x11 92 ) 93 94 // Misc constants expected by package net but not supported. 95 const ( 96 _ = iota 97 SOL_SOCKET 98 SO_TYPE 99 NET_RT_IFLIST 100 IFNAMSIZ 101 IFF_UP 102 IFF_BROADCAST 103 IFF_LOOPBACK 104 IFF_POINTOPOINT 105 IFF_MULTICAST 106 IPV6_V6ONLY 107 SOMAXCONN 108 F_DUPFD_CLOEXEC 109 SO_BROADCAST 110 SO_REUSEADDR 111 SO_REUSEPORT 112 SO_RCVBUF 113 SO_SNDBUF 114 SO_KEEPALIVE 115 SO_LINGER 116 SO_ERROR 117 IP_PORTRANGE 118 IP_PORTRANGE_DEFAULT 119 IP_PORTRANGE_LOW 120 IP_PORTRANGE_HIGH 121 IP_MULTICAST_IF 122 IP_MULTICAST_LOOP 123 IP_ADD_MEMBERSHIP 124 IPV6_PORTRANGE 125 IPV6_PORTRANGE_DEFAULT 126 IPV6_PORTRANGE_LOW 127 IPV6_PORTRANGE_HIGH 128 IPV6_MULTICAST_IF 129 IPV6_MULTICAST_LOOP 130 IPV6_JOIN_GROUP 131 TCP_NODELAY 132 TCP_KEEPINTVL 133 TCP_KEEPIDLE 134 135 SYS_FCNTL = 500 // unsupported 136 ) 137 138 var SocketDisableIPv6 bool 139 140 // A Sockaddr is one of the SockaddrXxx structs. 141 type Sockaddr interface { 142 // copy returns a copy of the underlying data. 143 copy() Sockaddr 144 145 // key returns the value of the underlying data, 146 // for comparison as a map key. 147 key() interface{} 148 } 149 150 type SockaddrInet4 struct { 151 Port int 152 Addr [4]byte 153 } 154 155 func (sa *SockaddrInet4) copy() Sockaddr { 156 sa1 := *sa 157 return &sa1 158 } 159 160 func (sa *SockaddrInet4) key() interface{} { return *sa } 161 162 type SockaddrInet6 struct { 163 Port int 164 ZoneId uint32 165 Addr [16]byte 166 } 167 168 func (sa *SockaddrInet6) copy() Sockaddr { 169 sa1 := *sa 170 return &sa1 171 } 172 173 func (sa *SockaddrInet6) key() interface{} { return *sa } 174 175 type SockaddrUnix struct { 176 Name string 177 } 178 179 func (sa *SockaddrUnix) copy() Sockaddr { 180 sa1 := *sa 181 return &sa1 182 } 183 184 func (sa *SockaddrUnix) key() interface{} { return *sa } 185 186 type SockaddrDatalink struct { 187 Len uint8 188 Family uint8 189 Index uint16 190 Type uint8 191 Nlen uint8 192 Alen uint8 193 Slen uint8 194 Data [12]int8 195 } 196 197 func (sa *SockaddrDatalink) copy() Sockaddr { 198 sa1 := *sa 199 return &sa1 200 } 201 202 func (sa *SockaddrDatalink) key() interface{} { return *sa } 203 204 // RoutingMessage represents a routing message. 205 type RoutingMessage interface { 206 unimplemented() 207 } 208 209 type IPMreq struct { 210 Multiaddr [4]byte /* in_addr */ 211 Interface [4]byte /* in_addr */ 212 } 213 214 type IPv6Mreq struct { 215 Multiaddr [16]byte /* in6_addr */ 216 Interface uint32 217 } 218 219 type Linger struct { 220 Onoff int32 221 Linger int32 222 } 223 224 type ICMPv6Filter struct { 225 Filt [8]uint32 226 } 227 228 // A queue is the bookkeeping for a synchronized buffered queue. 229 // We do not use channels because we need to be able to handle 230 // writes after and during close, and because a chan byte would 231 // require too many send and receive operations in real use. 232 type queue struct { 233 sync.Mutex 234 canRead sync.Cond 235 canWrite sync.Cond 236 r int // total read index 237 w int // total write index 238 m int // index mask 239 closed bool 240 } 241 242 func (q *queue) init(size int) { 243 if size&(size-1) != 0 { 244 panic("invalid queue size - must be power of two") 245 } 246 q.canRead.L = &q.Mutex 247 q.canWrite.L = &q.Mutex 248 q.m = size - 1 249 } 250 251 func past(deadline int64) bool { 252 sec, nsec := now() 253 return deadline > 0 && deadline < sec*1e9+int64(nsec) 254 } 255 256 func (q *queue) waitRead(n int, deadline int64) (int, error) { 257 if past(deadline) { 258 return 0, EAGAIN 259 } 260 var t timer 261 t.start(q, deadline) 262 for q.w-q.r == 0 && !q.closed && !t.expired { 263 q.canRead.Wait() 264 } 265 t.stop() 266 m := q.w - q.r 267 if m == 0 && t.expired { 268 return 0, EAGAIN 269 } 270 if m > n { 271 m = n 272 q.canRead.Signal() // wake up next reader too 273 } 274 q.canWrite.Signal() 275 return m, nil 276 } 277 278 func (q *queue) waitWrite(n int, deadline int64) (int, error) { 279 if past(deadline) { 280 return 0, EAGAIN 281 } 282 var t timer 283 t.start(q, deadline) 284 for q.w-q.r > q.m && !q.closed && !t.expired { 285 q.canWrite.Wait() 286 } 287 t.stop() 288 m := q.m + 1 - (q.w - q.r) 289 if m == 0 && t.expired { 290 return 0, EAGAIN 291 } 292 if m == 0 { 293 return 0, EAGAIN 294 } 295 if m > n { 296 m = n 297 q.canWrite.Signal() // wake up next writer too 298 } 299 q.canRead.Signal() 300 return m, nil 301 } 302 303 func (q *queue) close() { 304 q.Lock() 305 defer q.Unlock() 306 q.closed = true 307 q.canRead.Broadcast() 308 q.canWrite.Broadcast() 309 } 310 311 // A byteq is a byte queue. 312 type byteq struct { 313 queue 314 data []byte 315 } 316 317 func newByteq() *byteq { 318 q := &byteq{ 319 data: make([]byte, 4096), 320 } 321 q.init(len(q.data)) 322 return q 323 } 324 325 func (q *byteq) read(b []byte, deadline int64) (int, error) { 326 q.Lock() 327 defer q.Unlock() 328 n, err := q.waitRead(len(b), deadline) 329 if err != nil { 330 return 0, err 331 } 332 b = b[:n] 333 for len(b) > 0 { 334 m := copy(b, q.data[q.r&q.m:]) 335 q.r += m 336 b = b[m:] 337 } 338 return n, nil 339 } 340 341 func (q *byteq) write(b []byte, deadline int64) (n int, err error) { 342 q.Lock() 343 defer q.Unlock() 344 for n < len(b) { 345 nn, err := q.waitWrite(len(b[n:]), deadline) 346 if err != nil { 347 return n, err 348 } 349 bb := b[n : n+nn] 350 n += nn 351 for len(bb) > 0 { 352 m := copy(q.data[q.w&q.m:], bb) 353 q.w += m 354 bb = bb[m:] 355 } 356 } 357 return n, nil 358 } 359 360 // A msgq is a queue of messages. 361 type msgq struct { 362 queue 363 data []interface{} 364 } 365 366 func newMsgq() *msgq { 367 q := &msgq{ 368 data: make([]interface{}, 32), 369 } 370 q.init(len(q.data)) 371 return q 372 } 373 374 func (q *msgq) read(deadline int64) (interface{}, error) { 375 q.Lock() 376 defer q.Unlock() 377 n, err := q.waitRead(1, deadline) 378 if err != nil { 379 return nil, err 380 } 381 if n == 0 { 382 return nil, nil 383 } 384 m := q.data[q.r&q.m] 385 q.r++ 386 return m, nil 387 } 388 389 func (q *msgq) write(m interface{}, deadline int64) error { 390 q.Lock() 391 defer q.Unlock() 392 _, err := q.waitWrite(1, deadline) 393 if err != nil { 394 return err 395 } 396 q.data[q.w&q.m] = m 397 q.w++ 398 return nil 399 } 400 401 // An addr is a sequence of bytes uniquely identifying a network address. 402 // It is not human-readable. 403 type addr string 404 405 // A conn is one side of a stream-based network connection. 406 // That is, a stream-based network connection is a pair of cross-connected conns. 407 type conn struct { 408 rd *byteq 409 wr *byteq 410 local addr 411 remote addr 412 } 413 414 // A pktconn is one side of a packet-based network connection. 415 // That is, a packet-based network connection is a pair of cross-connected pktconns. 416 type pktconn struct { 417 rd *msgq 418 wr *msgq 419 local addr 420 remote addr 421 } 422 423 // A listener accepts incoming stream-based network connections. 424 type listener struct { 425 rd *msgq 426 local addr 427 } 428 429 // A netFile is an open network file. 430 type netFile struct { 431 defaultFileImpl 432 proto *netproto 433 sotype int 434 listener *msgq 435 packet *msgq 436 rd *byteq 437 wr *byteq 438 rddeadline int64 439 wrdeadline int64 440 addr Sockaddr 441 raddr Sockaddr 442 } 443 444 // A netAddr is a network address in the global listener map. 445 // All the fields must have defined == operations. 446 type netAddr struct { 447 proto *netproto 448 sotype int 449 addr interface{} 450 } 451 452 // net records the state of the network. 453 // It maps a network address to the listener on that address. 454 var net = struct { 455 sync.Mutex 456 listener map[netAddr]*netFile 457 }{ 458 listener: make(map[netAddr]*netFile), 459 } 460 461 // TODO(rsc): Some day, do a better job with port allocation. 462 // For playground programs, incrementing is fine. 463 var nextport = 2 464 465 // A netproto contains protocol-specific functionality 466 // (one for AF_INET, one for AF_INET6 and so on). 467 // It is a struct instead of an interface because the 468 // implementation needs no state, and I expect to 469 // add some data fields at some point. 470 type netproto struct { 471 bind func(*netFile, Sockaddr) error 472 } 473 474 var netprotoAF_INET = &netproto{ 475 bind: func(f *netFile, sa Sockaddr) error { 476 if sa == nil { 477 f.addr = &SockaddrInet4{ 478 Port: nextport, 479 Addr: [4]byte{127, 0, 0, 1}, 480 } 481 nextport++ 482 return nil 483 } 484 addr, ok := sa.(*SockaddrInet4) 485 if !ok { 486 return EINVAL 487 } 488 addr = addr.copy().(*SockaddrInet4) 489 if addr.Port == 0 { 490 addr.Port = nextport 491 nextport++ 492 } 493 f.addr = addr 494 return nil 495 }, 496 } 497 498 var netprotos = map[int]*netproto{ 499 AF_INET: netprotoAF_INET, 500 } 501 502 // These functions implement the usual BSD socket operations. 503 504 func (f *netFile) bind(sa Sockaddr) error { 505 if f.addr != nil { 506 return EISCONN 507 } 508 if err := f.proto.bind(f, sa); err != nil { 509 return err 510 } 511 if f.sotype == SOCK_DGRAM { 512 _, ok := net.listener[netAddr{f.proto, f.sotype, f.addr.key()}] 513 if ok { 514 f.addr = nil 515 return EADDRINUSE 516 } 517 net.listener[netAddr{f.proto, f.sotype, f.addr.key()}] = f 518 f.packet = newMsgq() 519 } 520 return nil 521 } 522 523 func (f *netFile) listen(backlog int) error { 524 net.Lock() 525 defer net.Unlock() 526 if f.listener != nil { 527 return EINVAL 528 } 529 _, ok := net.listener[netAddr{f.proto, f.sotype, f.addr.key()}] 530 if ok { 531 return EADDRINUSE 532 } 533 net.listener[netAddr{f.proto, f.sotype, f.addr.key()}] = f 534 f.listener = newMsgq() 535 return nil 536 } 537 538 func (f *netFile) accept() (fd int, sa Sockaddr, err error) { 539 msg, err := f.listener.read(f.readDeadline()) 540 if err != nil { 541 return -1, nil, err 542 } 543 newf, ok := msg.(*netFile) 544 if !ok { 545 // must be eof 546 return -1, nil, EAGAIN 547 } 548 return newFD(newf), newf.raddr.copy(), nil 549 } 550 551 func (f *netFile) connect(sa Sockaddr) error { 552 if past(f.writeDeadline()) { 553 return EAGAIN 554 } 555 if f.addr == nil { 556 if err := f.bind(nil); err != nil { 557 return err 558 } 559 } 560 net.Lock() 561 if sa == nil { 562 net.Unlock() 563 return EINVAL 564 } 565 sa = sa.copy() 566 if f.raddr != nil { 567 net.Unlock() 568 return EISCONN 569 } 570 if f.sotype == SOCK_DGRAM { 571 net.Unlock() 572 f.raddr = sa 573 return nil 574 } 575 if f.listener != nil { 576 net.Unlock() 577 return EISCONN 578 } 579 l, ok := net.listener[netAddr{f.proto, f.sotype, sa.key()}] 580 if !ok { 581 net.Unlock() 582 return ECONNREFUSED 583 } 584 f.raddr = sa 585 f.rd = newByteq() 586 f.wr = newByteq() 587 newf := &netFile{ 588 proto: f.proto, 589 sotype: f.sotype, 590 addr: f.raddr, 591 raddr: f.addr, 592 rd: f.wr, 593 wr: f.rd, 594 } 595 net.Unlock() 596 l.listener.write(newf, f.writeDeadline()) 597 return nil 598 } 599 600 func (f *netFile) read(b []byte) (int, error) { 601 if f.rd == nil { 602 if f.raddr != nil { 603 n, _, err := f.recvfrom(b, 0) 604 return n, err 605 } 606 return 0, ENOTCONN 607 } 608 return f.rd.read(b, f.readDeadline()) 609 } 610 611 func (f *netFile) write(b []byte) (int, error) { 612 if f.wr == nil { 613 if f.raddr != nil { 614 err := f.sendto(b, 0, f.raddr) 615 var n int 616 if err == nil { 617 n = len(b) 618 } 619 return n, err 620 } 621 return 0, ENOTCONN 622 } 623 return f.wr.write(b, f.writeDeadline()) 624 } 625 626 type pktmsg struct { 627 buf []byte 628 addr Sockaddr 629 } 630 631 func (f *netFile) recvfrom(p []byte, flags int) (n int, from Sockaddr, err error) { 632 if f.sotype != SOCK_DGRAM { 633 return 0, nil, EINVAL 634 } 635 if f.packet == nil { 636 return 0, nil, ENOTCONN 637 } 638 msg1, err := f.packet.read(f.readDeadline()) 639 if err != nil { 640 return 0, nil, err 641 } 642 msg, ok := msg1.(*pktmsg) 643 if !ok { 644 return 0, nil, EAGAIN 645 } 646 return copy(p, msg.buf), msg.addr, nil 647 } 648 649 func (f *netFile) sendto(p []byte, flags int, to Sockaddr) error { 650 if f.sotype != SOCK_DGRAM { 651 return EINVAL 652 } 653 if f.packet == nil { 654 if err := f.bind(nil); err != nil { 655 return err 656 } 657 } 658 net.Lock() 659 if to == nil { 660 net.Unlock() 661 return EINVAL 662 } 663 to = to.copy() 664 l, ok := net.listener[netAddr{f.proto, f.sotype, to.key()}] 665 if !ok || l.packet == nil { 666 net.Unlock() 667 return ECONNREFUSED 668 } 669 net.Unlock() 670 msg := &pktmsg{ 671 buf: make([]byte, len(p)), 672 addr: f.addr, 673 } 674 copy(msg.buf, p) 675 l.packet.write(msg, f.writeDeadline()) 676 return nil 677 } 678 679 func (f *netFile) close() error { 680 if f.listener != nil { 681 f.listener.close() 682 } 683 if f.packet != nil { 684 f.packet.close() 685 } 686 if f.rd != nil { 687 f.rd.close() 688 } 689 if f.wr != nil { 690 f.wr.close() 691 } 692 return nil 693 } 694 695 func fdToNetFile(fd int) (*netFile, error) { 696 f, err := fdToFile(fd) 697 if err != nil { 698 return nil, err 699 } 700 impl := f.impl 701 netf, ok := impl.(*netFile) 702 if !ok { 703 return nil, EINVAL 704 } 705 return netf, nil 706 } 707 708 func Socket(proto, sotype, unused int) (fd int, err error) { 709 p := netprotos[proto] 710 if p == nil { 711 return -1, EPROTONOSUPPORT 712 } 713 if sotype != SOCK_STREAM && sotype != SOCK_DGRAM { 714 return -1, ESOCKTNOSUPPORT 715 } 716 f := &netFile{ 717 proto: p, 718 sotype: sotype, 719 } 720 return newFD(f), nil 721 } 722 723 func Bind(fd int, sa Sockaddr) error { 724 f, err := fdToNetFile(fd) 725 if err != nil { 726 return err 727 } 728 return f.bind(sa) 729 } 730 731 func StopIO(fd int) error { 732 f, err := fdToNetFile(fd) 733 if err != nil { 734 return err 735 } 736 f.close() 737 return nil 738 } 739 740 func Listen(fd int, backlog int) error { 741 f, err := fdToNetFile(fd) 742 if err != nil { 743 return err 744 } 745 return f.listen(backlog) 746 } 747 748 func Accept(fd int) (newfd int, sa Sockaddr, err error) { 749 f, err := fdToNetFile(fd) 750 if err != nil { 751 return 0, nil, err 752 } 753 return f.accept() 754 } 755 756 func Getsockname(fd int) (sa Sockaddr, err error) { 757 f, err := fdToNetFile(fd) 758 if err != nil { 759 return nil, err 760 } 761 if f.addr == nil { 762 return nil, ENOTCONN 763 } 764 return f.addr.copy(), nil 765 } 766 767 func Getpeername(fd int) (sa Sockaddr, err error) { 768 f, err := fdToNetFile(fd) 769 if err != nil { 770 return nil, err 771 } 772 if f.raddr == nil { 773 return nil, ENOTCONN 774 } 775 return f.raddr.copy(), nil 776 } 777 778 func Connect(fd int, sa Sockaddr) error { 779 f, err := fdToNetFile(fd) 780 if err != nil { 781 return err 782 } 783 return f.connect(sa) 784 } 785 786 func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) { 787 f, err := fdToNetFile(fd) 788 if err != nil { 789 return 0, nil, err 790 } 791 return f.recvfrom(p, flags) 792 } 793 794 func Sendto(fd int, p []byte, flags int, to Sockaddr) error { 795 f, err := fdToNetFile(fd) 796 if err != nil { 797 return err 798 } 799 return f.sendto(p, flags, to) 800 } 801 802 func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn, recvflags int, from Sockaddr, err error) { 803 f, err := fdToNetFile(fd) 804 if err != nil { 805 return 806 } 807 n, from, err = f.recvfrom(p, flags) 808 return 809 } 810 811 func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) error { 812 _, err := SendmsgN(fd, p, oob, to, flags) 813 return err 814 } 815 816 func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) { 817 f, err := fdToNetFile(fd) 818 if err != nil { 819 return 0, err 820 } 821 switch f.sotype { 822 case SOCK_STREAM: 823 n, err = f.write(p) 824 case SOCK_DGRAM: 825 n = len(p) 826 err = f.sendto(p, flags, to) 827 } 828 if err != nil { 829 return 0, err 830 } 831 return n, nil 832 } 833 834 func GetsockoptInt(fd, level, opt int) (value int, err error) { 835 f, err := fdToNetFile(fd) 836 if err != nil { 837 return 0, err 838 } 839 switch { 840 case level == SOL_SOCKET && opt == SO_TYPE: 841 return f.sotype, nil 842 } 843 return 0, ENOTSUP 844 } 845 846 func SetsockoptInt(fd, level, opt int, value int) error { 847 return nil 848 } 849 850 func SetsockoptByte(fd, level, opt int, value byte) error { 851 _, err := fdToNetFile(fd) 852 if err != nil { 853 return err 854 } 855 return ENOTSUP 856 } 857 858 func SetsockoptLinger(fd, level, opt int, l *Linger) error { 859 return nil 860 } 861 862 func SetReadDeadline(fd int, t int64) error { 863 f, err := fdToNetFile(fd) 864 if err != nil { 865 return err 866 } 867 atomic.StoreInt64(&f.rddeadline, t) 868 return nil 869 } 870 871 func (f *netFile) readDeadline() int64 { 872 return atomic.LoadInt64(&f.rddeadline) 873 } 874 875 func SetWriteDeadline(fd int, t int64) error { 876 f, err := fdToNetFile(fd) 877 if err != nil { 878 return err 879 } 880 atomic.StoreInt64(&f.wrdeadline, t) 881 return nil 882 } 883 884 func (f *netFile) writeDeadline() int64 { 885 return atomic.LoadInt64(&f.wrdeadline) 886 } 887 888 func Shutdown(fd int, how int) error { 889 f, err := fdToNetFile(fd) 890 if err != nil { 891 return err 892 } 893 switch how { 894 case SHUT_RD: 895 f.rd.close() 896 case SHUT_WR: 897 f.wr.close() 898 case SHUT_RDWR: 899 f.rd.close() 900 f.wr.close() 901 } 902 return nil 903 } 904 905 func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error { panic("SetsockoptICMPv") } 906 func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) error { panic("SetsockoptIPMreq") } 907 func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) error { panic("SetsockoptIPv") } 908 func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) error { panic("SetsockoptInet") } 909 func SetsockoptString(fd, level, opt int, s string) error { panic("SetsockoptString") } 910 func SetsockoptTimeval(fd, level, opt int, tv *Timeval) error { panic("SetsockoptTimeval") } 911 func Socketpair(domain, typ, proto int) (fd [2]int, err error) { panic("Socketpair") } 912 913 func SetNonblock(fd int, nonblocking bool) error { return nil } 914