// sftp returns the *sftp.Client to the server, handling reconnects and coalesced dialing
// for concurrent callers.
489263
func (s *Storage) sftp() (*sftp.Client, error) {
	s.mu.Lock()
	if s.sc != nil {
		defer s.mu.Unlock()
		// TODO: remove all this "lastGet" stuff once the wait
		// mechanism has test coverage and we're sending
		// periodic heartbeats over the SSH channel.
		if now := time.Now(); s.lastGet.After(now.Add(-30 * time.Second)) {
			s.lastGet = now
			return s.sc, nil
		} else {
			// It's been awhile. Let's see if it's still good.
			_, err := s.sc.Stat(".")
			if err != nil {
				s.markConnDeadLocked()
			} else {
				s.lastGet = now
				return s.sc, nil
			}
		}
	}
	s.mu.Unlock()
	ci, err := s.getClientGroup.Do("", func() (interface{}, error) {
		sc, waiter, toClose, err := s.dialSFTP()
		if err != nil {
			return nil, err
		}
		if waiter != nil {
			go s.monitorSSHConn(waiter)
		}
		s.mu.Lock()
		defer s.mu.Unlock()
		s.connCloser = toClose
		s.sc = sc
		s.lastGet = time.Now()
		return sc, nil
	})
	if err != nil {
		return nil, err
	}
	return ci.(*sftp.Client), nil
}
715511
func (c *asyncClient) Hset(arg0 string, arg1 string, arg2 []byte) (stat FutureBool, err Error) {
	arg0bytes := []byte(arg0)
	arg1bytes := []byte(arg1)
	arg2bytes := arg2

	resp, err := c.conn.QueueRequest(&HSET, [][]byte{arg0bytes, arg1bytes, arg2bytes})
	if err == nil {
		stat = resp.future.(FutureBool)
	}

	return
}
265474
func (w *wrappedMux) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	w.handler.ServeHTTP(resp, req)
}
665560
func (s *Server) ReadSSFStreamSocket(serverConn net.Conn) {
	defer func() {
		serverConn.Close()
	}()

	// initialize the capacity to the max size
	// based on the number of tags we add later
	tags := make([]string, 1, 3)
	tags[0] = "ssf_format:framed"

	for {
		msg, err := protocol.ReadSSF(serverConn)
		if err != nil {
			if err == io.EOF {
				// Client hangup, close this
				s.Statsd.Count("frames.disconnects", 1, nil, 1.0)
				return
			}
			if protocol.IsFramingError(err) {
				log.WithError(err).
					WithField("remote", serverConn.RemoteAddr()).
					Info("Frame error reading from SSF connection. Closing.")
				tags = append(tags, []string{"packet_type:unknown", "reason:framing"}...)
				s.Statsd.Incr("ssf.error_total", tags, 1.0)
				return
			}
			// Non-frame errors means we can continue reading:
			log.WithError(err).
				WithField("remote", serverConn.RemoteAddr()).
				Error("Error processing an SSF frame")
			tags = append(tags, []string{"packet_type:unknown", "reason:processing"}...)
			s.Statsd.Incr("ssf.error_total", tags, 1.0)
			tags = tags[:1]
			continue
		}
		s.handleSSF(msg, "framed")
	}
}
110020
func (c *Client) UpdateFTP(i *UpdateFTPInput) (*FTP, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == 0 {
		return nil, ErrMissingVersion
	}

	if i.Name == "" {
		return nil, ErrMissingName
	}

	path := fmt.Sprintf("/service/%s/version/%d/logging/ftp/%s", i.Service, i.Version, i.Name)
	resp, err := c.PutForm(path, i, nil)
	if err != nil {
		return nil, err
	}

	var b *FTP
	if err := decodeJSON(&b, resp.Body); err != nil {
		return nil, err
	}
	return b, nil
}
926560
func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	s.mux.ServeHTTP(resp, req)
}
946654
func (c *Client) GetFTP(i *GetFTPInput) (*FTP, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == 0 {
		return nil, ErrMissingVersion
	}

	if i.Name == "" {
		return nil, ErrMissingName
	}

	path := fmt.Sprintf("/service/%s/version/%d/logging/ftp/%s", i.Service, i.Version, i.Name)
	resp, err := c.Get(path, nil)
	if err != nil {
		return nil, err
	}

	var b *FTP
	if err := decodeJSON(&b, resp.Body); err != nil {
		return nil, err
	}
	return b, nil
}
1098318
func requestFromPacket(ctx context.Context, pkt hasPath) *Request {
	method := requestMethod(pkt)
	request := NewRequest(method, pkt.getPath())
	request.ctx, request.cancelCtx = context.WithCancel(ctx)

	switch p := pkt.(type) {
	case *sshFxpOpenPacket:
		request.Flags = p.Pflags
	case *sshFxpSetstatPacket:
		request.Flags = p.Flags
		request.Attrs = p.Attrs.([]byte)
	case *sshFxpRenamePacket:
		request.Target = cleanPath(p.Newpath)
	case *sshFxpSymlinkPacket:
		request.Target = cleanPath(p.Linkpath)
	}
	return request
}
301315
func (e Ext) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	urlpath := strings.TrimSuffix(r.URL.Path, "/")
	if len(r.URL.Path) > 0 && path.Ext(urlpath) == "" && r.URL.Path[len(r.URL.Path)-1] != '/' {
		for _, ext := range e.Extensions {
			_, err := os.Stat(httpserver.SafePath(e.Root, urlpath) + ext)
			if err == nil {
				r.URL.Path = urlpath + ext
				break
			}
		}
	}
	return e.Next.ServeHTTP(w, r)
}
521325
func (h *pubsubHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	handler := func(socket *websocket.Conn) {
		logger.Debugf("start of *pubsubHandler.ServeHTTP")
		defer socket.Close()

		// If we get to here, no more errors to report, so we report a nil
		// error.  This way the first line of the socket is always a json
		// formatted simple error.
		h.sendError(socket, req, nil)

		// Here we configure the ping/pong handling for the websocket so
		// the server can notice when the client goes away.
		// See the long note in logsink.go for the rationale.
		socket.SetReadDeadline(time.Now().Add(websocket.PongDelay))
		socket.SetPongHandler(func(string) error {
			socket.SetReadDeadline(time.Now().Add(websocket.PongDelay))
			return nil
		})
		ticker := time.NewTicker(websocket.PingPeriod)
		defer ticker.Stop()

		messageCh := h.receiveMessages(socket)
		for {
			select {
			case <-h.ctxt.stop():
				return
			case <-ticker.C:
				deadline := time.Now().Add(websocket.WriteWait)
				if err := socket.WriteControl(gorillaws.PingMessage, []byte{}, deadline); err != nil {
					// This error is expected if the other end goes away. By
					// returning we close the socket through the defer call.
					logger.Debugf("failed to write ping: %s", err)
					return
				}
			case m := <-messageCh:
				logger.Tracef("topic: %q, data: %v", m.Topic, m.Data)
				_, err := h.hub.Publish(m.Topic, m.Data)
				if err != nil {
					logger.Errorf("publish failed: %v", err)
				}
			}
		}
	}
	websocket.Serve(w, req, handler)
}
240665
func (xff *XFF) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	r.RemoteAddr = GetRemoteAddrIfAllowed(r, xff.allowed)
	next(w, r)
}
371903
func NewClient(clientCtx context.Context, conf *cloudstorage.Config, host string, port int, folder string, config *ssh.ClientConfig) (*Client, error) {

	//u.Debugf("new sftp host=%q port=%d folder=%q", host, port, folder)
	target, err := sftpAddr(host, port)
	if err != nil {
		gou.WarnCtx(clientCtx, "failed creating address with %s, %d: %v", host, port, err)
		return nil, err
	}

	sshClient, err := ssh.Dial("tcp", target, config)
	if err != nil {
		gou.WarnCtx(clientCtx, "failed SFTP login for %s with error %s", config.User, err)
		return nil, err
	}

	ftpClient, err := ftp.NewClient(sshClient)
	if err != nil {
		gou.WarnCtx(clientCtx, "failed creating SFTP client for %s with error %s", config.User, err)
		sshClient.Close()
		return nil, err
	}

	uid := uuid.NewUUID().String()
	uid = strings.Replace(uid, "-", "", -1)

	client := &Client{
		ID:        uid,
		clientCtx: clientCtx,
		client:    ftpClient,
		host:      host,
		port:      port,
		cachepath: conf.TmpDir,
		bucket:    folder,
		paths:     make(map[string]struct{}),
	}

	//gou.Infof("%p created sftp client %#v", client, ftpClient)

	return client, nil
}
1092293
func (t *TLSHandler) ServeTCP(conn net.Conn) {
	t.Next.ServeTCP(tls.Server(conn, t.Config))
}
741511
func (p *Proxy) ServeTCP(conn net.Conn) {
	log.Debugf("Handling connection from %s", conn.RemoteAddr())
	defer conn.Close()
	connBackend, err := net.DialTCP("tcp", nil, p.target)
	if err != nil {
		log.Errorf("Error while connection to backend: %v", err)
		return
	}
	defer connBackend.Close()

	errChan := make(chan error, 1)
	go connCopy(conn, connBackend, errChan)
	go connCopy(connBackend, conn, errChan)

	err = <-errChan
	if err != nil {
		log.Errorf("Error during connection: %v", err)
	}
}
951673
func (f ApiAppHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, app *models.App) {
	f(w, r, app)
}
1331435
func ReqRepLatencyClient(addr string, msgSize int, roundTrips int) {
	s, err := req.NewSocket()
	if err != nil {
		log.Fatalf("Failed to make new pair socket: %v", err)
	}
	defer s.Close()

	all.AddTransports(s)
	d, err := s.NewDialer(addr, nil)
	if err != nil {
		log.Fatalf("Failed to make new dialer: %v", err)
	}

	// TCP no delay, please!
	d.SetOption(mangos.OptionNoDelay, true)

	err = d.Dial()
	if err != nil {
		log.Fatalf("Failed to dial: %v", err)
	}

	// 100 milliseconds to give TCP a chance to establish
	//time.Sleep(time.Millisecond * 100)
	msg := mangos.NewMessage(msgSize)

	total := time.Duration(0)
	for i := 0; i < roundTrips; i++ {
		msg.Header = msg.Header[:0]
		msg.Body = msg.Body[0:msgSize]
		start := time.Now()
		if err = s.SendMsg(msg); err != nil {
			log.Fatalf("Failed SendMsg: %v", err)
		}
		if msg, err = s.RecvMsg(); err != nil {
			log.Fatalf("Failed RecvMsg: %v", err)
		}
		total += time.Since(start)
	}
	msg.Free()

	lat := float64(total/time.Microsecond) / float64(roundTrips)
	fmt.Printf("message size: %d [B]\n", msgSize)
	fmt.Printf("round trip count: %d\n", roundTrips)
	fmt.Printf("average RTT: %.3f [us]\n", lat)
}
1254139
func UploadSFTP(identityFile, host, dir string, files []string) error {
	sftp := exec.Command("sftp")
	sftp.Stdout = nil
	sftp.Stderr = os.Stderr
	if identityFile != "" {
		sftp.Args = append(sftp.Args, "-i", identityFile)
	}
	sftp.Args = append(sftp.Args, host)
	fmt.Println(">>>", strings.Join(sftp.Args, " "))
	if *DryRunFlag {
		return nil
	}

	stdin, err := sftp.StdinPipe()
	if err != nil {
		return fmt.Errorf("can't create stdin pipe for sftp: %v", err)
	}
	if err := sftp.Start(); err != nil {
		return err
	}
	in := io.MultiWriter(stdin, os.Stdout)
	for _, f := range files {
		fmt.Fprintln(in, "put", f, path.Join(dir, filepath.Base(f)))
	}
	stdin.Close()
	return sftp.Wait()
}