How to use Copy method of gvisor Package

Best Syzkaller code snippet using gvisor.Copy

tun_capture_gvisor.go

Source:tun_capture_gvisor.go Github

copy

Full Screen

1package gvisor2import (3 "errors"4 "io"5 "log"6 "net"7 "strings"8 "time"9 "gvisor.dev/gvisor/pkg/context"10 "gvisor.dev/gvisor/pkg/sentry/socket/netfilter"11 "gvisor.dev/gvisor/pkg/sentry/socket/netstack"12 "gvisor.dev/gvisor/pkg/tcpip"13 "gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"14 "gvisor.dev/gvisor/pkg/tcpip/buffer"15 "gvisor.dev/gvisor/pkg/tcpip/header"16 "gvisor.dev/gvisor/pkg/tcpip/link/channel"17 "gvisor.dev/gvisor/pkg/tcpip/link/loopback"18 "gvisor.dev/gvisor/pkg/tcpip/link/sniffer"19 "gvisor.dev/gvisor/pkg/tcpip/network/arp"20 "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"21 "gvisor.dev/gvisor/pkg/tcpip/network/ipv6"22 "gvisor.dev/gvisor/pkg/tcpip/stack"23 "gvisor.dev/gvisor/pkg/tcpip/transport/icmp"24 "gvisor.dev/gvisor/pkg/tcpip/transport/raw"25 "gvisor.dev/gvisor/pkg/tcpip/transport/tcp"26 "gvisor.dev/gvisor/pkg/tcpip/transport/udp"27 "gvisor.dev/gvisor/pkg/waiter"28)29// Intercept using a TUN and google netstack to parse TCP/UDP into streams.30// The connections are redirected to a capture.ProxyHandler31type GvisorTun struct {32 // The IP stack serving the tun. It intercepts all TCP connections.33 IPStack *stack.Stack34 DefUDP tcpip.Endpoint35 DefTCP tcpip.Endpoint36 udpPacketConn net.PacketConn37 // If set, will be used to handle accepted TCP connections and UDP packets.38 // Else the Listener interface is used.39 Handler TUNHandler40 UDPHandler UDPHandler41}42// Interface implemented by TUNHandler.43type UDPHandler interface {44 HandleUdp(dstAddr net.IP, dstPort uint16,45 localAddr net.IP, localPort uint16,46 data []byte)47}48// UdpWriter is the interface implemented by the TunTransport, to send49// packets back to the virtual interface50type UdpWriter interface {51 WriteTo(data []byte, dstAddr *net.UDPAddr, srcAddr *net.UDPAddr) (int, error)52}53// Interface implemented by TUNHandler.54// Important: for android the system makes sure tun is the default route, but55// packets from the VPN app are excluded.56//57// On Linux we need a similar setup. This still requires iptables to mark58// packets from istio-proxy, and use 2 routing tables.59//60type TUNHandler interface {61 HandleTUN(conn net.Conn, target *net.TCPAddr) error62}63/*64 Client:65 - tun app has access to real network - can send/receive to any host directly,66 -- may have real routable IPv4 and/or IPV6 address67 -- may be inside a mesh - only IPv6 link local communication with other nodes68 - regular apps have the default route set to the TUN device (directly or via rule).69 - tun_capture read all packets from regular apps, terminates TCP and receives UDP70 - the TCP can forward to real destination, or tunnel to some other node.71 - or it can tunnel all connections to it's VPN server, using a QUIC forwarder at TCP72 level.73 Server:74 - server operates on L7 streams only - originates TCP and UDP as client75 - client requests are muxed over h2 (or QUIC)76 - no TUN required, no masq !77 - skips the tunneled IP and TCP headers - metadata sent at start of stream78 - only the external IP/UDP/QUIC headers.79 Both:80 - each node can act as a server - forwarding streams either upstream or to nodes in81 same mesh82 - when acting as client, it can operate without TUN - forwarding TCP streams or UDP83 at L7.84 - tun capture requires VPN to be enabled, and transparently captures all TCP85 Alternatives:86 - tun_client captures all ip frames and sends them to VPN server87 - tun_server receives ip frames from clients, injects in local tun which does ipmasq88 - tun_server can also route to other clients directly, based on ip689*/90/*91 Example android:9210: tun0: <POINTOPOINT,UP,LOWER_UP> mtu 1400 qdisc pfifo_fast state UNKNOWN qlen 50093 link/none94 inet 10.10.154.232/24 scope global tun095 inet6 2001:470:1f04:429:4a46:48e5:ae34:9ae8/64 scope global96 valid_lft forever preferred_lft forever97ip route list table all98default via 10.1.10.1 dev wlan0 table wlan0 proto static9910.1.10.0/24 dev wlan0 table wlan0 proto static scope link100default dev tun0 table tun0 proto static scope link10110.1.10.0/24 dev wlan0 proto kernel scope link src 10.1.10.12410210.10.154.0/24 dev tun0 proto kernel scope link src 10.10.154.2321032001:470:1f04:429::/64 dev tun0 table tun0 proto kernel metric 256104fe80::/64 dev tun0 table tun0 proto kernel metric 256105ip rule show1060: from all lookup local10710000: from all fwmark 0xc0000/0xd0000 lookup legacy_system10811000: from all iif tun0 lookup local_network10912000: from all fwmark 0xc0066/0xcffff lookup tun0110### EXCLUDED: VPN process11112000: from all fwmark 0x0/0x20000 uidrange 0-10115 lookup tun011212000: from all fwmark 0x0/0x20000 uidrange 10117-99999 lookup tun011313000: from all fwmark 0x10063/0x1ffff lookup local_network11413000: from all fwmark 0x10064/0x1ffff lookup wlan011513000: from all fwmark 0x10066/0x1ffff uidrange 0-0 lookup tun011613000: from all fwmark 0x10066/0x1ffff uidrange 0-10115 lookup tun011713000: from all fwmark 0x10066/0x1ffff uidrange 10117-99999 lookup tun011814000: from all oif wlan0 lookup wlan011914000: from all oif tun0 uidrange 0-10115 lookup tun012014000: from all oif tun0 uidrange 10117-99999 lookup tun012115000: from all fwmark 0x0/0x10000 lookup legacy_system12216000: from all fwmark 0x0/0x10000 lookup legacy_network12317000: from all fwmark 0x0/0x10000 lookup local_network12419000: from all fwmark 0x64/0x1ffff lookup wlan012521000: from all fwmark 0x66/0x1ffff lookup wlan012622000: from all fwmark 0x0/0xffff lookup wlan012723000: from all fwmark 0x0/0xffff uidrange 0-0 lookup main12832000: from all unreachable129*/130/*131google.transport:132- transport_demuxer.go endpoints has a table of ports to endpoints133Life of packet:134-> NIC.DeliverNetworkPacket - will make a route - remote address/link addr, nexthop, netproto135-> ipv6.HandlePacket136-> NIC.DeliverTransportPacket137-- will first attempt nic.demux, then n.stac.demux deliverPacket138-- will look for an endpoint139-- packet added to the rcv linked list140-- waiter.dispatchToChannelHandlers()141RegisterTransportEndpoint -> with the stack transport dispatcher (nic.demux), on NICID142-- takes protocol, id - registers endpoint143-- for each net+transport protocol pair, one map based on 'id'144-- id== local port, remote port, local address, remote address145--146- a NIC is created with ID(int32), [name] and 'link endpoint ID' - which is a uint64 in the 'link endpoints'147static table. The LinkEndpoint if has MTU, caps, LinkAddress(MAC), WritePacket and Attach(NetworkDispatcher)148The NetworkDispatcher.DeliverNetworkPacket is also implemented by NIC149*/150func NewTUNFD(fd io.ReadWriteCloser, handler TUNHandler, udpNat UDPHandler) UdpWriter {151 //var err error152 var linkID stack.LinkEndpoint153 //useFD := os.Getenv("CHANNEL_LINK") == ""154 //if f,ok := fd.(*os.File); ok && useFD {155 // // Bugs - after some time it stops reading.156 // // Workaround is to use the regular read with a patch.157 // linkID, err = fdbased.New(&fdbased.Options{158 // MTU: 1500,159 // FDs: []int{int(f.Fd()),},160 // File: f,161 // })162 // if err != nil {163 // log.Println("Link err", err)164 // }165 //} else {166 log.Println("Using channel based link")167 ep := channel.New(1024, 1500, "")168 linkID = ep169 t := NewGvisorTunCapture(&linkID, handler, udpNat, false)170 go func() {171 m1 := make([]byte, 1600)172 for {173 n, err := fd.Read(m1)174 if err != nil {175 log.Println("NIC read err", err)176 continue177 }178 b := buffer.NewViewFromBytes(m1[0:n])179 //log.Println("RD ", n, err)180 pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{181 Data: b.ToVectorisedView(),182 })183 ep.InjectInbound(ipv4.ProtocolNumber, pkt)184 }185 }()186 go func() {187 m1 := make([]byte, 1600)188 ctx := context.Background()189 for {190 // Read is non-blocking191 pi, err := ep.ReadContext(ctx)192 if !err {193 continue194 }195 if pi.Pkt == nil {196 continue197 }198 //log.Println(pi)199 // TODO: reuse a buffer200 vv := pi.Pkt.Views()201 n := 0202 for _, v := range vv {203 copy(m1[n:], v)204 n += v.Size()205 }206 fd.Write(m1[0:n])207 }208 }()209 //linkID = ep.LinkAddress()210 //stack.FindLinkEndpoint(linkIDID)211 //linkID = NewReaderWriterLink(fd, fd, &Options{MTU: 1600})212// }213 return t214}215type mymatch struct {216}217func (*mymatch) Name() string {218 return "my"219}220func (*mymatch) Match(hook stack.Hook, pkt *stack.PacketBuffer, interfaceName string) (matches bool, hotdrop bool) {221 tcpHeader := header.TCP(pkt.TransportHeader().View())222 if tcpHeader.DestinationPort() == 5201 {223 return true, false224 }225 return false , false226}227// NewTunCapture creates an in-process tcp stack, backed by an tun-like network interface.228// All TCP streams initiated on the tun or localhost will be captured.229func NewGvisorTunCapture(ep *stack.LinkEndpoint, handler TUNHandler, udpNat UDPHandler, snif bool) *GvisorTun {230 t := &GvisorTun{231 Handler: handler,232 UDPHandler: udpNat,233 }234 netProtos := []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol, arp.NewProtocol}235 transProtos := []stack.TransportProtocolFactory{236 tcp.NewProtocol,237 udp.NewProtocol,238 icmp.NewProtocol4,239 icmp.NewProtocol6,240 }241 ipt := netfilter.DefaultLinuxTables()242 //// 3 tables for ip4243 if false {244 natt := ipt.GetTable(stack.NATID, false)245 //// To trigger modified = true246 ipt.ReplaceTable(stack.NATID, natt, false)247 //// Default has 5 rules.248 //// HAck !!!!249 natt.Rules[0].Target = &stack.RedirectTarget{250 Port: 5201,251 NetworkProtocol: ipv4.ProtocolNumber}252 natt.Rules[0].Filter = stack.IPHeaderFilter{253 Protocol: tcp.ProtocolNumber,254 CheckProtocol: true,255 }256 //// Can only create matcher using unmarshal257 natt.Rules[0].Matchers = []stack.Matcher{258 &mymatch{},259 }260 }261 t.IPStack = stack.New(stack.Options{262 NetworkProtocols: netProtos,263 TransportProtocols: transProtos,264 //Clock: clock,265 Stats: netstack.Metrics,266 HandleLocal: false, // accept from other nics267 // Enable raw sockets for users with sufficient268 // privileges.269 RawFactory: raw.EndpointFactory{},270 //UniqueID: uniqueID,271 IPTables: ipt,272 })273 loopbackLinkID := loopback.New()274 if true || snif {275 loopbackLinkID = sniffer.New(loopbackLinkID)276 }277 t.IPStack.CreateNIC(1, loopbackLinkID)278 addr1 := "\x7f\x00\x00\x01"279 if err := t.IPStack.AddAddress(1, ipv4.ProtocolNumber, tcpip.Address(addr1)); err != nil {280 log.Print("Can't add address", err)281 return t282 }283 if err := t.IPStack.AddAddress(1, ipv6.ProtocolNumber, tcpip.Address(net.IPv6loopback)); err != nil {284 log.Print("Can't add IP6 address", err)285 return t286 }287 ep1 := *ep288 //if snif {289 // ep1 = sniffer.New(ep1)290 //}291 // NIC 2 - IP4, IP6292 t.IPStack.CreateNIC(2, ep1)293 addr2 := "\x0a\x0c\x00\x01"294 if err := t.IPStack.AddAddress(2, ipv4.ProtocolNumber, tcpip.Address(addr2)); err != nil {295 log.Print("Can't add address", err)296 return t297 }298 addr3, _ := net.ResolveIPAddr("ip", "fd::01")299 if err := t.IPStack.AddAddress(2, ipv6.ProtocolNumber, tcpip.Address(addr3.IP)); err != nil {300 log.Print("Can't add address", err)301 return t302 }303 t.IPStack.SetPromiscuousMode(2, true)304 t.IPStack.SetSpoofing(2, true)305 sn, _ := tcpip.NewSubnet(tcpip.Address("\x00"), tcpip.AddressMask("\x00"))306 //t.IPStack.AddSubnet(2, ipv4.ProtocolNumber, sn)307 t.IPStack.AddRoute(tcpip.Route{NIC: 2, Destination: sn})308 sn, _ = tcpip.NewSubnet(tcpip.Address("\x00"), tcpip.AddressMask("\x00"))309 //t.IPStack.AddSubnet(2, ipv6.ProtocolNumber, sn)310 t.IPStack.AddRoute(tcpip.Route{NIC: 2, Destination: sn})311 gsetRouteTable(t.IPStack, ep != nil)312 //epp := newEpProxy()313 go t.DefTcpServer(handler) //echo)314 go t.DefTcp6Server() //echo)315 go t.defUdpServer()316 t.defUdp6Server()317 // Bound to 10.22.0.5, which is routed to dmesh1318 //addrN := tcpip.FullAddress{2, tcpip.Address(net.IPv4(10, 55, 0, 5).To4()), 5228}319 //c1, err := gonet.NewPacketConn(t.IPStack, addrN, ipv4.ProtocolNumber)320 //if err != nil {321 // log.Println("XXXXXX ", err)322 //}323 //t.udpPacketConn = c1324 //go t.udpPing(2, t.IPStack)325 return t326}327// Debugging reception - send a packet every 5 seconds to port 1999.328// DST IP is the current eth IP329func (nt *GvisorTun) udpPing(NICID tcpip.NICID, stack *stack.Stack) {330 //addr1 := tcpip.FullAddress{NICID, tcpip.Address(net.IPv4(10, 12, 0, 5).To4()), 5228}331 // Works:332 // Doesn't seem to work333 //addr1 := tcpip.FullAddress{NICID, tcpip.Address(net.IPv4(73, 158, 64, 16).To4()), 5228}334 for {335 time.Sleep(15 * time.Second)336 //c1.WriteTo([]byte("Hi1"), &net.UDPAddr{Port: 1999, IP: net.IPv4(10, 12, 0, 5)})337 //nt.udpPacketConn.WriteTo([]byte("Hi2 1234"), &net.UDPAddr{Port: 1999, IP: net.IPv4(10, 10, 201, 200)})338 ip9 := net.ParseIP("2001:470:1f04:428::9")339 nt.udpPacketConn.WriteTo([]byte("Hi2 1234"), &net.UDPAddr{Port: 1999, IP: ip9})340 }341}342func (nt *GvisorTun) WriteTo(data []byte, dst *net.UDPAddr, src *net.UDPAddr) (int, error) {343 addrb := []byte(dst.IP)344 //srcaddrb := []byte(src.IP.To4())345 // TODO: how about from ?346 // TODO: do we need to make a copy ? netstack passes ownership, we may reuse buffers347 n, _, err := nt.DefUDP.Write(tcpip.SlicePayload(data), tcpip.WriteOptions{348 To: &tcpip.FullAddress{349 Port: uint16(dst.Port),350 Addr: tcpip.Address(addrb),351 },352 // TODO(costin): PATCH353 //From: &tcpip.FullAddress{354 // Port: uint16(src.Port),355 // Addr: tcpip.Address(srcaddrb),356 //},357 })358 if err != nil {359 return 0, errors.New(err.String())360 }361 return int(n), nil362}363//type tcpHandler func(wq *waiter.Queue, ep tcpip.Endpoint)364//type UdpLocalReader interface {365// ReadLocal(addr *tcpip.DoubleAddress) (buffer.View, tcpip.ControlMessages, *tcpip.Error)366//}367func (nt *GvisorTun) defUdpServer() error {368 // Like a socket369 var wq waiter.Queue370 ep, err := nt.IPStack.NewEndpoint(udp.ProtocolNumber, ipv4.ProtocolNumber, &wq)371 if err != nil {372 return errors.New(err.String())373 }374 nt.DefUDP = ep375 // No address - listen on all376 err = ep.Bind(tcpip.FullAddress{377 //Addr: "\x01", - error378 //Addr: "\x00\x00\x00\x00",379 //Port: 2000,380 Port: 0xffff,381 //Port: 15001,382 })383 if err != nil {384 ep.Close()385 return errors.New(err.String())386 }387 ep.SocketOptions().SetReceiveOriginalDstAddress(true)388 we, ch := waiter.NewChannelEntry(nil)389 wq.EventRegister(&we, waiter.EventIn)390 go func() {391 for {392 // Will have the peer address393 add := tcpip.FullAddress{}394 //ep.SetSockOpt()395 // Add is send address. Control should include the dest addr ( for raw )396 v, c, err := ep.Read(&add)397 //v, _, err := ep.(UdpLocalReader).ReadLocal(&add)398 if err == tcpip.ErrWouldBlock {399 select {400 case <-ch:401 continue402 }403 }404 // TODO: add back full address for UDP405 if nt.UDPHandler != nil {406 nt.UDPHandler.HandleUdp(net.IP(c.OriginalDstAddress.Addr),407 c.OriginalDstAddress.Port,408 net.IP(add.Addr), add.Port,409 v)410 }411 }412 }()413 return nil414}415func (nt *GvisorTun) defUdp6Server() error {416 // Like a socket417 //var wq waiter.Queue418 //419 //ep6, err := nt.IPStack.NewEndpoint(udp.ProtocolNumber, ipv6.ProtocolNumber, &wq)420 //if err != nil {421 // return errors.New(err.String())422 //}423 //err = ep6.Bind(tcpip.FullAddress{424 // //Addr: "\x01", - error425 // Addr: tcpip.Address(net.IPv6loopback),426 // //Port: 2000,427 // Port: 0xffff,428 // NIC: 2,429 //}, nil)430 //if err != nil {431 // ep6.Close()432 // return errors.New(err.String())433 //}434 //nt.IPStack.Capture(ipv6.ProtocolNumber, udp.ProtocolNumber, ep6.(stack.TransportEndpoint))435 //436 //we, ch := waiter.NewChannelEntry(nil)437 //wq.EventRegister(&we, waiter.EventIn)438 ////defer wq.EventUnregister(&we)439 //440 //go func() {441 // for {442 // // Will have the peer address443 // add := tcpip.DoubleAddress{}444 // //ep.SetSockOpt()445 // v, _, err := ep6.(UdpLocalReader).ReadLocal(&add)446 // if err == tcpip.ErrWouldBlock {447 // select {448 // case <-ch:449 // continue450 // }451 // }452 //453 // la := net.IP([]byte(add.LocalAddr))454 // //if la.To4() == nil {455 // // log.Print("IP6 ", la)456 // //}457 // if add.LocalAddr[0] == 0xff {458 // continue459 // }460 //461 // if nt.UDPHandler != nil {462 // nt.UDPHandler.HandleUdp(la, add.LocalPort,463 // net.IP([]byte(add.FullAddress.Addr)), add.FullAddress.Port,464 // v)465 // }466 //467 // }468 //}()469 return nil470}471//var (472// Dump = false473//)474func (nt *GvisorTun) DefTcpServer(handler TUNHandler) {475 var wq waiter.Queue476 // No address - listen on all477 //err = ep.Bind(tcpip.FullAddress{478 // Port: 0xffff,479 //}, nil) // reserves port480 //if err != nil {481 // ep.Close()482 // return nil, wq, errors.New(err.String())483 //}484 // MISSING ACCEPT485 //ep, _ := nt.IPStack.NewRawEndpoint( tcp.ProtocolNumber,ipv4.ProtocolNumber, &wq, false)486 ep, _ := nt.IPStack.NewEndpoint( tcp.ProtocolNumber,ipv4.ProtocolNumber, &wq)487 ep.Bind(tcpip.FullAddress{Port: 0xffff})488 //ep.Bind(tcpip.FullAddress{Port: 5201})489 if err := ep.Listen(100); err != nil { // calls Register490 ep.Close()491 return492 }493 tl := gonet.NewTCPListener(nt.IPStack, &wq, ep)494 tl.ReverseAddr = true495 for {496 c, err := tl.Accept()497 if err != nil {498 log.Println(err)499 continue500 }501 go handler.HandleTUN(c, nil)502 }503 //we, listenCh := waiter.NewChannelEntry(nil)504 //wq.EventRegister(&we, waiter.EventIn)505 //506 //// receive TCP packets on port507 //go func() {508 // defer wq.EventUnregister(&we)509 // for {510 // epin, wqin, err := ep.Accept()511 // if err != nil {512 // if err == tcpip.ErrWouldBlock {513 // <-listenCh514 // continue515 // }516 // log.Println("Unexpected accept error")517 // }518 // if Dump {519 // add, _ := epin.GetRemoteAddress()520 // ladd, _ := epin.GetLocalAddress()521 // log.Printf("TUN: Accepted %v %v", ladd, add)522 // }523 //524 // conn := gonet.NewConn(wqin, epin)525 // go func() {526 // err := handler.HandleTUN(conn)527 // if err != nil {528 // return529 // }530 // }()531 //532 // }533 //}()534}535func (nt *GvisorTun) DefTcp6Server() {536 //var wq waiter.Queue537 //ep, err := nt.IPStack.NewEndpoint(tcp.ProtocolNumber, ipv6.ProtocolNumber, &wq)538 //if err != nil {539 // return nil, wq, errors.New(err.String())540 //}541 //542 //// No address - listen on all543 //err = ep.Bind(tcpip.FullAddress{544 // Addr: tcpip.Address(net.IPv6loopback),545 // Port: 0xffff,546 // NIC: 2,547 //}, nil) // reserves port548 //if err != nil {549 // ep.Close()550 // return nil, wq, errors.New(err.String())551 //}552 //nt.IPStack.Capture(ipv6.ProtocolNumber, tcp.ProtocolNumber, ep.(stack.TransportEndpoint))553 //554 //if err := ep.Listen(10); err != nil { // calls Register555 // ep.Close()556 // return nil, wq, errors.New(err.String())557 //}558 //559 //we, listenCh := waiter.NewChannelEntry(nil)560 //wq.EventRegister(&we, waiter.EventIn)561 //562 //// receive TCP packets on port563 //go func() {564 // defer wq.EventUnregister(&we)565 // for {566 // epin, wqin, err := ep.Accept()567 // if err != nil {568 // if err == tcpip.ErrWouldBlock {569 // <-listenCh570 // continue571 // }572 // log.Println("Unexpected accept error")573 // }574 // if Dump {575 // add, _ := epin.GetRemoteAddress()576 // ladd, _ := epin.GetLocalAddress()577 // log.Printf("TUN: Accepted %v %v", ladd, add)578 // }579 //580 // conn := gonet.NewConn(wqin, epin)581 // go func() {582 // err := nt.Handler.HandleTUN(conn)583 // if err != nil {584 // return585 // }586 // }()587 //588 // }589 //}()590 //591 //return ep, wq, nil592}593func ga2na(address tcpip.Address) net.IP {594 ab := []byte(address)595 return net.IP(ab)596}597func sn(net, mask string) tcpip.Subnet {598 r, _ := tcpip.NewSubnet(tcpip.Address([]byte(net)), tcpip.AddressMask([]byte(mask)))599 return r600}601func gsetRouteTable(ipstack *stack.Stack, real bool) {602 ipstack.SetRouteTable([]tcpip.Route{603 {604 Destination: sn("\x7f\x00\x00\x00", "\xff\x00\x00\x00"),605 Gateway: "",606 NIC: 1,607 },608 { // 10.12.0.2 - IP of the tun609 Destination: sn("\x0a\x0c\x00\x02", "\xff\xff\xff\xff"),610 Gateway: "",611 NIC: 2,612 },613 { // 10.12.0.0 - routed to the tun614 Destination: sn("\x0a\x0c\x00\x00", "\xff\xff\x00\x00"),615 Gateway: "",616 NIC: 2,617 },618 {619 Destination: sn("\x00\x00\x00\x00", "\x00\x00\x00\x00"),620 Gateway: "",621 NIC: 2,622 },623 {624 Destination: sn(string(net.IPv6loopback), strings.Repeat("\xff", 16)),625 Gateway: "",626 NIC: 1,627 },628 {629 Destination: sn(strings.Repeat("\x00", 16), strings.Repeat("\x00", 16)),630 Gateway: "",631 NIC: 2,632 },633 })634}635/*636 Terms:637 - netstack - the network stack implementation638 - nic - virtual interface639 -- route table640 -- address641 - packet injected and sent by link - dmtun (but doesn't work android) or channel based642 - View - slice of buffer, TrimFront, CapLength,643 -644*/...

Full Screen

Full Screen

enable.go

Source:enable.go Github

copy

Full Screen

1/*2Copyright 2016 The Kubernetes Authors All rights reserved.3Licensed under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License.5You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07Unless required by applicable law or agreed to in writing, software8distributed under the License is distributed on an "AS IS" BASIS,9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10See the License for the specific language governing permissions and11limitations under the License.12*/13package gvisor14import (15 "fmt"16 "io"17 "io/ioutil"18 "log"19 "net/http"20 "os"21 "os/exec"22 "os/signal"23 "path/filepath"24 "syscall"25 "github.com/docker/machine/libmachine/mcnutils"26 "github.com/pkg/errors"27 "k8s.io/minikube/pkg/minikube/assets"28 "k8s.io/minikube/pkg/minikube/constants"29)30const (31 nodeDir = "/node"32)33// Enable follows these steps for enabling gvisor in minikube:34// 1. creates necessary directories for storing binaries and runsc logs35// 2. downloads runsc and gvisor-containerd-shim36// 3. copies necessary containerd config files37// 4. restarts containerd38func Enable() error {39 if err := makeGvisorDirs(); err != nil {40 return errors.Wrap(err, "creating directories on node")41 }42 if err := downloadBinaries(); err != nil {43 return errors.Wrap(err, "downloading binaries")44 }45 if err := copyConfigFiles(); err != nil {46 return errors.Wrap(err, "copying config files")47 }48 if err := restartContainerd(); err != nil {49 return errors.Wrap(err, "restarting containerd")50 }51 // When pod is terminated, disable gvisor and exit52 c := make(chan os.Signal)53 signal.Notify(c, os.Interrupt, syscall.SIGTERM)54 go func() {55 <-c56 if err := Disable(); err != nil {57 log.Printf("Error disabling gvisor: %v", err)58 os.Exit(1)59 }60 os.Exit(0)61 }()62 log.Print("gvisor successfully enabled in cluster")63 // sleep for one year so the pod continuously runs64 select {}65}66// makeGvisorDirs creates necessary directories on the node67func makeGvisorDirs() error {68 // Make /run/containerd/runsc to hold logs69 fp := filepath.Join(nodeDir, "run/containerd/runsc")70 if err := os.MkdirAll(fp, 0755); err != nil {71 return errors.Wrap(err, "creating runsc dir")72 }73 // Make /usr/local/bin to store the runsc binary74 fp = filepath.Join(nodeDir, "usr/local/bin")75 if err := os.MkdirAll(fp, 0755); err != nil {76 return errors.Wrap(err, "creating usr/local/bin dir")77 }78 // Make /tmp/runsc to also hold logs79 fp = filepath.Join(nodeDir, "tmp/runsc")80 if err := os.MkdirAll(fp, 0755); err != nil {81 return errors.Wrap(err, "creating runsc logs dir")82 }83 return nil84}85func downloadBinaries() error {86 if err := runsc(); err != nil {87 return errors.Wrap(err, "downloading runsc")88 }89 if err := gvisorContainerdShim(); err != nil {90 return errors.Wrap(err, "downloading gvisor-containerd-shim")91 }92 return nil93}94// downloads the gvisor-containerd-shim95func gvisorContainerdShim() error {96 dest := filepath.Join(nodeDir, "usr/bin/gvisor-containerd-shim")97 return downloadFileToDest(constants.GvisorContainerdShimURL, dest)98}99// downloads the runsc binary and returns a path to the binary100func runsc() error {101 dest := filepath.Join(nodeDir, "usr/local/bin/runsc")102 return downloadFileToDest(constants.GvisorURL, dest)103}104// downloadFileToDest downlaods the given file to the dest105// if something already exists at dest, first remove it106func downloadFileToDest(url, dest string) error {107 client := &http.Client{}108 req, err := http.NewRequest("GET", url, nil)109 if err != nil {110 return errors.Wrapf(err, "creating request for %s", url)111 }112 req.Header.Set("User-Agent", "minikube")113 resp, err := client.Do(req)114 if err != nil {115 return err116 }117 defer resp.Body.Close()118 if _, err := os.Stat(dest); err == nil {119 if err := os.Remove(dest); err != nil {120 return errors.Wrapf(err, "removing %s for overwrite", dest)121 }122 }123 fi, err := os.Create(dest)124 if err != nil {125 return errors.Wrapf(err, "creating %s", dest)126 }127 defer fi.Close()128 if _, err := io.Copy(fi, resp.Body); err != nil {129 return errors.Wrap(err, "copying binary")130 }131 if err := fi.Chmod(0777); err != nil {132 return errors.Wrap(err, "fixing perms")133 }134 return nil135}136// Must write the following files:137// 1. gvisor-containerd-shim.toml138// 2. gvisor containerd config.toml139// and save the default version of config.toml140func copyConfigFiles() error {141 log.Printf("Storing default config.toml at %s", constants.StoredContainerdConfigTomlPath)142 if err := mcnutils.CopyFile(filepath.Join(nodeDir, constants.ContainerdConfigTomlPath), filepath.Join(nodeDir, constants.StoredContainerdConfigTomlPath)); err != nil {143 return errors.Wrap(err, "copying default config.toml")144 }145 log.Print("Copying gvisor-containerd-shim.toml...")146 if err := copyAssetToDest(constants.GvisorContainerdShimTargetName, filepath.Join(nodeDir, constants.GvisorContainerdShimTomlPath)); err != nil {147 return errors.Wrap(err, "copying gvisor-containerd-shim.toml")148 }149 log.Print("Copying containerd config.toml with gvisor...")150 if err := copyAssetToDest(constants.GvisorConfigTomlTargetName, filepath.Join(nodeDir, constants.ContainerdConfigTomlPath)); err != nil {151 return errors.Wrap(err, "copying gvisor version of config.toml")152 }153 return nil154}155func copyAssetToDest(targetName, dest string) error {156 var asset *assets.BinDataAsset157 for _, a := range assets.Addons["gvisor"].Assets {158 if a.GetTargetName() == targetName {159 asset = a160 }161 }162 // Now, copy the data from this asset to dest163 src := filepath.Join(constants.GvisorFilesPath, asset.GetTargetName())...

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 src, err := os.Open("1.txt")4 if err != nil {5 fmt.Println(err)6 os.Exit(1)7 }8 defer src.Close()9 dst, err := os.Create("2.txt")10 if err != nil {11 fmt.Println(err)12 os.Exit(1)13 }14 defer dst.Close()15 bytes, err := io.Copy(dst, src)16 if err != nil {17 fmt.Println(err)18 os.Exit(1)19 }20 fmt.Printf("Copied %d bytes.", bytes)21}

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.Create("file.txt")4 if err != nil {5 fmt.Println(err)6 }7 defer file.Close()8 file.WriteString("Hello World")9 file.Sync()10 file2, err := os.Create("file2.txt")11 if err != nil {12 fmt.Println(err)13 }14 defer file2.Close()15 file2.Sync()16 gvisor := NewGvisor()17 gvisor.Copy("file.txt", "file2.txt")18}19import (20type Gvisor struct {21}22func NewGvisor() *Gvisor {23 return &Gvisor{}24}25func (g *Gvisor) Copy(file1 string, file2 string) {26 file, err := os.Create(g.File2)27 if err != nil {28 fmt.Println(err)29 }30 defer file.Close()31 file.WriteString("Hello World")32 file.Sync()33}34--- FAIL: TestCopy (0.00s)35testing.tRunner.func1.1(0x4f7f00, 0x5f98f0)36testing.tRunner.func1(0xc0000b8c60)37panic(0x4f7f00, 0x5f98f0)38main.(*Gvisor).Copy(0xc0000

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "gvisor"3func main() {4 fmt.Println("Hello, playground")5 gvisor.Copy()6}7import "fmt"8import "gvisor"9func main() {10 fmt.Println("Hello, playground")11 gvisor.Copy()12}13import "fmt"14import "gvisor"15func main() {16 fmt.Println("Hello, playground")17 gvisor.Copy()18}19import "fmt"20import "gvisor"21func main() {22 fmt.Println("Hello, playground")23 gvisor.Copy()24}25import "fmt"26import "gvisor"27func main() {28 fmt.Println("Hello, playground")29 gvisor.Copy()30}31import "fmt"32import "gvisor"33func main() {34 fmt.Println("Hello, playground")35 gvisor.Copy()36}37import "fmt"38import "gvisor"39func main() {40 fmt.Println("Hello, playground")41 gvisor.Copy()42}43import "fmt"44import "gvisor"45func main() {46 fmt.Println("Hello, playground")47 gvisor.Copy()48}49import "fmt"50import "gvisor"51func main() {52 fmt.Println("Hello, playground")53 gvisor.Copy()54}55import "fmt"56import "gvisor"57func main() {58 fmt.Println("Hello, playground")59 gvisor.Copy()60}61import "fmt"62import "gvisor"63func main() {

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 src, err := os.Open("C:\\Users\\user\\Desktop\\1.go")4 if err != nil {5 fmt.Println(err)6 }7 defer src.Close()8 dst, err := os.Create("C:\\Users\\user\\Desktop\\2.go")9 if err != nil {10 fmt.Println(err)11 }12 defer dst.Close()13 n, err := io.Copy(dst, src)14 if err != nil {15 fmt.Println(err)16 }17 fmt.Println(n)18}

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 src, err := syscall.Open("src.txt", syscall.O_RDONLY, 0)5 if err != nil {6 fmt.Println("Error opening source file")7 }8 dest, err := syscall.Open("dest.txt", syscall.O_WRONLY|syscall.O_CREATE, 0)9 if err != nil {10 fmt.Println("Error opening destination file")11 }12 _, _, errno := syscall.Syscall(syscall.SYS_COPY_FILE_RANGE, uintptr(src), 0, uintptr(dest), 0, 1048576, 0)13 if errno != 0 {14 fmt.Println("Error copying file")15 }16 syscall.Close(src)17 syscall.Close(dest)18 fmt.Println("File copied successfully")19}20import (21func main() {22 fmt.Println("Hello, playground")23 src, err := syscall.Open("src.txt", syscall.O_RDONLY, 0)24 if err != nil {25 fmt.Println("Error opening source file")26 }27 dest, err := syscall.Open("dest.txt", syscall.O_WRONLY|syscall.O_CREATE, 0)28 if err != nil {29 fmt.Println("Error opening destination file")30 }31 _, _, errno := syscall.Syscall(syscall.SYS_COPY_FILE_RANGE, uintptr(src), 0, uintptr(dest), 0, 1048576, 0)32 if errno != 0 {33 fmt.Println("Error copying file")34 }35 syscall.Close(src)36 syscall.Close(dest)37 fmt.Println("File copied successfully")38}39import (40func main() {41 fmt.Println("Hello, playground")42 src, err := syscall.Open("src.txt", syscall.O_RDONLY, 0)43 if err != nil {44 fmt.Println("Error opening

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 gvisor := platform.NewGVisor()4 container, err := gvisor.NewContainer()5 if err != nil {6 fmt.Println(err)7 }8 task, err := container.NewTask()9 if err != nil {10 fmt.Println(err)11 }12 file, err := task.NewFile("/tmp/1.txt")13 if err != nil {14 fmt.Println(err)15 }16 file2, err := task.NewFile("/tmp/2.txt")17 if err != nil {18 fmt.Println(err)19 }20 err = file.Copy(file2)21 if err != nil {22 fmt.Println(err)23 }24 err = file.Close()25 if err != nil {26 fmt.Println(err)27 }28 err = file2.Close()29 if err != nil {30 fmt.Println(err)31 }32 err = task.Close()33 if err != nil {34 fmt.Println(err)35 }36 err = container.Close()37 if err != nil {38 fmt.Println(err)39 }40 err = gvisor.Close()41 if err != nil {42 fmt.Println(err)43 }44}45import (46func main() {47 gvisor := platform.NewGVisor()48 container, err := gvisor.NewContainer()49 if err != nil {50 fmt.Println(err)51 }52 task, err := container.NewTask()53 if err != nil {54 fmt.Println(err)55 }56 file, err := task.NewFile("/tmp/1.txt")

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 dst, err := os.Create(dstFile)4 if err != nil {5 fmt.Println("Error Creating file", err)6 }7 defer dst.Close()8 src, err := os.Open(srcFile)9 if err != nil {10 fmt.Println("Error Opening file", err)11 }12 defer src.Close()13 _, err = io.Copy(dst, src)14 if err != nil {15 fmt.Println("Error copying file", err)16 }17 fmt.Println("File copied successfully")18}

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 g := gvisor.New()4 g.Copy("1.txt","2.txt")5 fmt.Println(g.Copy("1.txt","2.txt"))6}7import (8func main() {9 g := gvisor.New()10 fmt.Println(g.Delete("1.txt"))11}12import (

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful