// Additional initialization for Open packets
559847
func (r *Request) open(h Handlers, pkt requestPacket) responsePacket {
	flags := r.Pflags()
	var err error
	switch {
	case flags.Write, flags.Append, flags.Creat, flags.Trunc:
		r.Method = "Put"
		r.state.writerAt, err = h.FilePut.Filewrite(r)
	case flags.Read:
		r.Method = "Get"
		r.state.readerAt, err = h.FileGet.Fileread(r)
	default:
		return statusFromError(pkt, errors.New("bad file flags"))
	}
	if err != nil {
		return statusFromError(pkt, err)
	}
	return &sshFxpHandlePacket{ID: pkt.id(), Handle: r.handle}
}
936114
func (s *Session) Open() (net.Conn, error) {
	conn, err := s.OpenStream()
	if err != nil {
		return nil, err
	}
	return conn, nil
}
75191
func (g *GoHttpServer) Init(init *EngineInit) {
	g.MaxMultipartSize = int64(Config.IntDefault("server.request.max.multipart.filesize", 32)) << 20 /* 32 MB */
	g.goContextStack = utils.NewStackLock(Config.IntDefault("server.context.stack", 100),
		Config.IntDefault("server.context.maxstack", 200),
		func() interface{} {
			return NewGoContext(g)
		})
	g.goMultipartFormStack = utils.NewStackLock(Config.IntDefault("server.form.stack", 100),
		Config.IntDefault("server.form.maxstack", 200),
		func() interface{} { return &GoMultipartForm{} })
	g.ServerInit = init

	revelHandler := http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		g.Handle(writer, request)
	})

	// Adds the mux list
	g.HttpMuxList = init.HTTPMuxList
	sort.Sort(g.HttpMuxList)
	g.HasAppMux = len(g.HttpMuxList) > 0
	g.signalChan = make(chan os.Signal)

	g.Server = &http.Server{
		Addr:         init.Address,
		Handler:      revelHandler,
		ReadTimeout:  time.Duration(Config.IntDefault("http.timeout.read", 0)) * time.Second,
		WriteTimeout: time.Duration(Config.IntDefault("http.timeout.write", 0)) * time.Second,
	}

}
1142951
func (m *MockOpener) Open(arg0, arg1 []byte, arg2 protocol.PacketNumber, arg3 []byte) ([]byte, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Open", arg0, arg1, arg2, arg3)
	ret0, _ := ret[0].([]byte)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
686394
func (c *Connection) init(address string, timeout time.Duration) (err error) {

	if c.address == `` {
		c.address = address
	}
	if c.timeout == 0 && timeout != 0 {
		c.timeout = timeout
	}

	if err = c.connect(); err != nil {
		return err
	}

	c.write = make(chan interface{}, 16)
	c.Notifications = make(chan Notification, 16)

	c.responses = make(map[uint32]*chan *rpcResponse)

	go c.reader()
	go c.writer()

	rchan, _ := c.Send(Request{Method: `JSONRPC.Version`}, true)
	if err != nil {
		log.WithField(`error`, err).Error(`Connection closed`)
		return err
	}

	res, err := rchan.Read(c.timeout)
	if err != nil {
		log.WithField(`error`, err).Error(`Kodi responded`)
		return err
	}
	if version := res[`version`].(map[string]interface{}); version != nil {
		if version[`major`].(float64) < KODI_MIN_VERSION {
			return errors.New(`Kodi version too low, upgrade to Frodo or later`)
		}
	}

	return
}
204022
func New(context uint64, bytes []byte, mark string, lengthValidate bool) (packet *Packet, err error) {

	var p Packet

	// Get the mark value
	p.Mark = mark

	// Set the context
	p.context = context

	if bytes[ipv4HdrLenPos]&ipv4ProtoMask == 0x40 {
		return &p, p.parseIPv4Packet(bytes, lengthValidate)
	}

	return p.parseIPv6Packet()
}
609034
func (s *Server) OpenV3(p *Packet) (interface{}, error) {
	req := new(RequestOpenV3)
	err := UnmarshalBinary(p.Payload, req)
	if err != nil {
		return nil, err
	}

	session, err := s.getSession(p)
	if err != nil {
		return nil, err
	}

	name := req.FileName.Path()

	if req.DesiredLock != LockNone {
		return nil, &Status{
			Err:  fmt.Errorf("open lock type=%d not supported for file %q", req.DesiredLock, name),
			Code: StatusOperationNotSupported,
		}
	}

	file, err := s.OpenFile(name, req.OpenMode)
	if err != nil {
		return nil, err
	}

	res := &ReplyOpenV3{
		Handle: s.newHandle(),
	}

	session.mu.Lock()
	session.files[res.Handle] = file
	session.mu.Unlock()

	return res, nil
}
472707
func init() {
	a := unsafe.Offsetof(OutMessage{}.header) + uintptr(OutMessageHeaderSize)
	b := unsafe.Offsetof(OutMessage{}.payload)

	if a != b {
		log.Panicf(
			"header ends at offset %d, but payload starts at offset %d",
			a, b)
	}
}
627163
func (c *client) initClient() {
	s := c.srv
	c.cid = atomic.AddUint64(&s.gcid, 1)

	// Outbound data structure setup
	c.out.sz = startBufSize
	c.out.sg = sync.NewCond(&c.mu)
	opts := s.getOpts()
	// Snapshots to avoid mutex access in fast paths.
	c.out.wdl = opts.WriteDeadline
	c.out.mp = int32(opts.MaxPending)

	c.subs = make(map[string]*subscription)
	c.echo = true

	c.debug = (atomic.LoadInt32(&c.srv.logging.debug) != 0)
	c.trace = (atomic.LoadInt32(&c.srv.logging.trace) != 0)

	// This is a scratch buffer used for processMsg()
	// The msg header starts with "RMSG ", which can be used
	// for both local and routes.
	// in bytes that is [82 77 83 71 32].
	c.msgb = [msgScratchSize]byte{82, 77, 83, 71, 32}

	// This is to track pending clients that have data to be flushed
	// after we process inbound msgs from our own connection.
	c.pcd = make(map[*client]struct{})

	// snapshot the string version of the connection
	var conn string
	if ip, ok := c.nc.(*net.TCPConn); ok {
		addr := ip.RemoteAddr().(*net.TCPAddr)
		c.host = addr.IP.String()
		c.port = uint16(addr.Port)
		conn = fmt.Sprintf("%s:%d", addr.IP, addr.Port)
	}

	switch c.kind {
	case CLIENT:
		c.ncs = fmt.Sprintf("%s - cid:%d", conn, c.cid)
	case ROUTER:
		c.ncs = fmt.Sprintf("%s - rid:%d", conn, c.cid)
	case GATEWAY:
		c.ncs = fmt.Sprintf("%s - gid:%d", conn, c.cid)
	case LEAF:
		c.ncs = fmt.Sprintf("%s - lid:%d", conn, c.cid)
	case SYSTEM:
		c.ncs = "SYSTEM"
	}
}
1135864
func Init(proto, addr, socketGroup string, tlsConfig *tls.Config) ([]net.Listener, error) {
	ls := []net.Listener{}

	switch proto {
	case "fd":
		fds, err := listenFD(addr, tlsConfig)
		if err != nil {
			return nil, err
		}
		ls = append(ls, fds...)
	case "tcp":
		l, err := sockets.NewTCPSocket(addr, tlsConfig)
		if err != nil {
			return nil, err
		}
		ls = append(ls, l)
	case "unix":
		gid, err := lookupGID(socketGroup)
		if err != nil {
			if socketGroup != "" {
				if socketGroup != defaultSocketGroup {
					return nil, err
				}
				logrus.Warnf("could not change group %s to %s: %v", addr, defaultSocketGroup, err)
			}
			gid = os.Getgid()
		}
		l, err := sockets.NewUnixSocket(addr, gid)
		if err != nil {
			return nil, fmt.Errorf("can't create unix socket %s: %v", addr, err)
		}
		if _, err := homedir.StickRuntimeDirContents([]string{addr}); err != nil {
			// StickRuntimeDirContents returns nil error if XDG_RUNTIME_DIR is just unset
			logrus.WithError(err).Warnf("cannot set sticky bit on socket %s under XDG_RUNTIME_DIR", addr)
		}
		ls = append(ls, l)
	default:
		return nil, fmt.Errorf("invalid protocol format: %q", proto)
	}

	return ls, nil
}
962374
func (l *Listener) packetInput(data []byte, addr net.Addr) {
	dataValid := false
	if l.block != nil {
		l.block.Decrypt(data, data)
		data = data[nonceSize:]
		checksum := crc32.ChecksumIEEE(data[crcSize:])
		if checksum == binary.LittleEndian.Uint32(data) {
			data = data[crcSize:]
			dataValid = true
		} else {
			atomic.AddUint64(&DefaultSnmp.InCsumErrors, 1)
		}
	} else if l.block == nil {
		dataValid = true
	}

	if dataValid {
		l.sessionLock.Lock()
		s, ok := l.sessions[addr.String()]
		l.sessionLock.Unlock()

		if !ok { // new address:port
			if len(l.chAccepts) < cap(l.chAccepts) { // do not let the new sessions overwhelm accept queue
				var conv uint32
				convValid := false
				if l.fecDecoder != nil {
					isfec := binary.LittleEndian.Uint16(data[4:])
					if isfec == typeData {
						conv = binary.LittleEndian.Uint32(data[fecHeaderSizePlus2:])
						convValid = true
					}
				} else {
					conv = binary.LittleEndian.Uint32(data)
					convValid = true
				}

				if convValid { // creates a new session only if the 'conv' field in kcp is accessible
					s := newUDPSession(conv, l.dataShards, l.parityShards, l, l.conn, addr, l.block)
					s.kcpInput(data)
					l.sessionLock.Lock()
					l.sessions[addr.String()] = s
					l.sessionLock.Unlock()
					l.chAccepts <- s
				}
			}
		} else {
			s.kcpInput(data)
		}
	}
}
585576
func (packet *Packet) Init(project string) error {
	if packet.Project == "" {
		packet.Project = project
	}
	if packet.EventID == "" {
		var err error
		packet.EventID, err = uuid()
		if err != nil {
			return err
		}
	}
	if time.Time(packet.Timestamp).IsZero() {
		packet.Timestamp = Timestamp(time.Now())
	}
	if packet.Level == "" {
		packet.Level = ERROR
	}
	if packet.Logger == "" {
		packet.Logger = "root"
	}
	if packet.ServerName == "" {
		packet.ServerName = hostname
	}
	if packet.Platform == "" {
		packet.Platform = "go"
	}

	if packet.Culprit == "" {
		for _, inter := range packet.Interfaces {
			if c, ok := inter.(Culpriter); ok {
				packet.Culprit = c.Culprit()
				if packet.Culprit != "" {
					break
				}
			}
		}
	}

	return nil
}
960487
func New(queueID uint16, maxPacketsInQueue uint32, packetSize uint32) (nfq *Queue, err error) {
	nfq = &Queue{
		ID: queueID,
		// TODO: what should the chan size be?
		packets: make(chan *RawPacket, 1024),
	}
	var ret C.int

	defer func() {
		if err != nil && nfq != nil {
			if nfq.qh != nil {
				C.nfq_destroy_queue(nfq.qh)
			}

			if nfq.h != nil {
				C.nfq_close(nfq.h)
			}
		}
	}()

	if nfq.h, err = C.nfq_open(); err != nil {
		err = errors.Wrap(err, "netfilter: unable to open nfq queue handle.")
		return
	}

	if ret, err = C.nfq_unbind_pf(nfq.h, AF_INET); err != nil || ret < 0 {
		err = errors.Wrap(err, "netfilter: unable to unbind existing nfq handler.")
		return
	}

	if ret, err = C.nfq_bind_pf(nfq.h, AF_INET); err != nil || ret < 0 {
		err = errors.Wrap(err, "netfilter: unable to bind to AF_INET protocol family.")
		return
	}

	if nfq.qh, err = C.CreateQueue(nfq.h, C.u_int16_t(queueID)); err != nil || nfq.qh == nil {
		err = errors.Wrap(err, "netfilter: unable to create nfq queue.")
		return
	}

	if ret, err = C.nfq_set_queue_maxlen(nfq.qh, C.u_int32_t(maxPacketsInQueue)); err != nil || ret < 0 {
		err = errors.Wrap(err, "netfilter: unable to set nfq max queue length.")
		return
	}

	if C.nfq_set_mode(nfq.qh, C.u_int8_t(2), C.uint(packetSize)) < 0 {
		err = errors.Wrap(err, "netfilter: unable to set packet copy mode.")
		return
	}

	if nfq.fd, err = C.nfq_fd(nfq.h); err != nil {
		err = errors.Wrap(err, "netfilter: unable to get nfq queue file-descriptor.")
		return

	}

	// TODO: error handling
	// me: https://i.imgur.com/Lmy5P.gif
	C.nfnl_rcvbufsiz(C.nfq_nfnlh(nfq.h), 1024*16384)

	// register this queue object with the global dispatcher
	register(queueID, nfq.packets)

	return
}
202216
func (s *Server) Init() {
	s.mux = http.NewServeMux()

	// Register local handlers
	s.RegisterHandler(s, diagPaths2Func)
}
1213205
func (s *SecureChannelSession) open() (*responseAPDU, error) {
	return transmit(s.card, &commandAPDU{
		Cla:  claSCWallet,
		Ins:  insOpenSecureChannel,
		P1:   s.PairingIndex,
		P2:   0,
		Data: s.publicKey,
		Le:   0,
	})
}
896521
func (t *Tx) Init(b []byte) {
	t.p.init(b)
	// maxPayloadSize excludes the header of the payload, and the header
	// of the wrapping message.
	t.maxPayloadSize = uint64(len(t.p.buffer)) - 2*sizeOfSlotHeader
	t.tail = 0xfffffffe * jump
	t.next = t.tail
	t.head = t.tail + jump
	t.p.write(t.tail, slotFree)
}
1212015
func init() {
	tr := utilnet.SetTransportDefaults(&http.Transport{})
	metadataHTTPClientTimeout := time.Second * 10
	httpClient := &http.Client{
		Transport: tr,
		Timeout:   metadataHTTPClientTimeout,
	}
	credentialprovider.RegisterCredentialProvider("google-dockercfg",
		&credentialprovider.CachingDockerConfigProvider{
			Provider: &dockerConfigKeyProvider{
				metadataProvider{Client: httpClient},
			},
			Lifetime: 60 * time.Second,
		})

	credentialprovider.RegisterCredentialProvider("google-dockercfg-url",
		&credentialprovider.CachingDockerConfigProvider{
			Provider: &dockerConfigUrlKeyProvider{
				metadataProvider{Client: httpClient},
			},
			Lifetime: 60 * time.Second,
		})

	credentialprovider.RegisterCredentialProvider("google-container-registry",
		// Never cache this.  The access token is already
		// cached by the metadata service.
		&containerRegistryProvider{
			metadataProvider{Client: httpClient},
		})
}