func (x *DeleteStorageObjectRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[21]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*ListPurchasesRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{28}
}


func (mbox *Mailbox) newClient() (*client.Client, error) {
	var imapClient *client.Client
	var err error
	if mbox.TLS {
		config := new(tls.Config)
		config.InsecureSkipVerify = mbox.IgnoreCertErrors
		imapClient, err = client.DialTLS(mbox.Host, config)
	} else {
		imapClient, err = client.Dial(mbox.Host)
	}
	if err != nil {
		return imapClient, err
	}

	err = imapClient.Login(mbox.User, mbox.Pwd)
	if err != nil {
		return imapClient, err
	}

	_, err = imapClient.Select(mbox.Folder, mbox.ReadOnly)
	if err != nil {
		return imapClient, err
	}

	return imapClient, nil
}


func (x *UpdateAccountRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[36]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*LeaderboardRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{25}
}


func (p *BinaryProtocol) readStringBody(size int32) (value string, err error) {
	if size < 0 {
		return "", nil
	}
	if uint64(size) > p.trans.RemainingBytes() {
		return "", invalidDataLength
	}
	var buf []byte
	if int(size) <= len(p.buffer) {
		buf = p.buffer[0:size]
	} else {
		buf = make([]byte, size)
	}
	_, e := io.ReadFull(p.trans, buf)
	return string(buf), NewProtocolException(e)
}


func isRepositoryGitPath(path string) bool {
	return strings.HasSuffix(path, ".git") ||
		strings.Contains(path, ".git"+string(os.PathSeparator)) ||
		// Windows treats ".git." the same as ".git"
		strings.HasSuffix(path, ".git.") ||
		strings.Contains(path, ".git."+string(os.PathSeparator))
}


func (p *HTTPClient) closeResponse() error {
	var err error
	if p.response != nil && p.response.Body != nil {
		// The docs specify that if keepalive is enabled and the response body is not
		// read to completion the connection will never be returned to the pool and
		// reused. Errors are being ignored here because if the connection is invalid
		// and this fails for some reason, the Close() method will do any remaining
		// cleanup.
		io.Copy(ioutil.Discard, p.response.Body)

		err = p.response.Body.Close()
	}

	p.response = nil
	return err
}


func (x *UnlinkDeviceRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[35]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error {
	switch m.Device {
	case "cgroup":
		// No mount point(s) need to be created:
		//
		// * for v1, mount points are saved by CRIU because
		//   /sys/fs/cgroup is a tmpfs mount
		//
		// * for v2, /sys/fs/cgroup is a real mount, but
		//   the mountpoint appears as soon as /sys is mounted
		return nil
	case "bind":
		// The prepareBindMount() function checks if source
		// exists. So it cannot be used for other filesystem types.
		if err := prepareBindMount(m, c.config.Rootfs); err != nil {
			return err
		}
	default:
		// for all other filesystems just create the mountpoints
		dest, err := securejoin.SecureJoin(c.config.Rootfs, m.Destination)
		if err != nil {
			return err
		}
		if err := checkProcMount(c.config.Rootfs, dest, ""); err != nil {
			return err
		}
		if err := os.MkdirAll(dest, 0o755); err != nil {
			return err
		}
	}
	return nil
}


func (x *RuntimeInfo) Reset() {
	*x = RuntimeInfo{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[41]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func TestResourceServer_ValidateAccessToken(t *testing.T) {
	r := newMockResourceServer(t)
	_, err := r.ValidateAccessToken(context.Background(), "myserver", sampleIDToken)
	assert.Error(t, err)
}


func TestEscapeJSONString(t *testing.T) {
	for _, str := range []string{"", "foobar", `foo"bar`, `foo\bar`, "foo\n\tbar"} {
		escaped := EscapeJSONString(str)
		var unmarshaled string
		err := json.Unmarshal([]byte(`"` + escaped + `"`), &unmarshaled)
		require.NoError(t, err, str)
		assert.Equal(t, str, unmarshaled, str)
	}
}


func TestCORSFilter_AllowedDomains(t *testing.T) {
	for _, each := range allowedDomainInput {
		tearDown()
		ws := new(WebService)
		ws.Route(ws.PUT("/cors").To(dummy))
		Add(ws)

		cors := CrossOriginResourceSharing{
			AllowedDomains: each.domains,
			CookiesAllowed: true,
			Container:      DefaultContainer}
		Filter(cors.Filter)

		httpRequest, _ := http.NewRequest("PUT", "http://api.his.com/cors", nil)
		httpRequest.Header.Set(HEADER_Origin, each.origin)
		httpWriter := httptest.NewRecorder()
		DefaultContainer.Dispatch(httpWriter, httpRequest)
		actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin)
		if actual != each.origin && each.allowed {
			t.Fatal("expected to be accepted")
		}
		if actual == each.origin && !each.allowed {
			t.Fatal("did not expect to be accepted")
		}
	}
}


func (x *UserList) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[39]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (x *CallApiEndpointRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[12]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*DeleteWalletLedgerRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{22}
}


func (*DeleteFriendRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{16}
}


func (x *StatusList_Status) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[49]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*RuntimeInfo_ModuleInfo) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{41, 0}
}


func Render(tmpl string, s *types.Step) (types.StepSlice, error) {
	buffer := new(bytes.Buffer)
	config := new(types.Build)

	velaFuncs := funcHandler{envs: convertPlatformVars(s.Environment)}
	templateFuncMap := map[string]interface{}{
		"vela": velaFuncs.returnPlatformVar,
	}

	// parse the template with Masterminds/sprig functions
	//
	// https://pkg.go.dev/github.com/Masterminds/sprig?tab=doc#TxtFuncMap
	t, err := template.New(s.Name).Funcs(sprig.TxtFuncMap()).Funcs(templateFuncMap).Parse(tmpl)
	if err != nil {
		return types.StepSlice{}, fmt.Errorf("unable to parse template %s: %v", s.Template.Name, err)
	}

	// apply the variables to the parsed template
	err = t.Execute(buffer, s.Template.Variables)
	if err != nil {
		return types.StepSlice{}, fmt.Errorf("unable to execute template %s: %v", s.Template.Name, err)
	}

	// unmarshal the template to the pipeline
	err = yaml.Unmarshal(buffer.Bytes(), config)
	if err != nil {
		return types.StepSlice{}, fmt.Errorf("unable to unmarshal yaml: %v", err)
	}

	// ensure all templated steps have template prefix
	for index, newStep := range config.Steps {
		config.Steps[index].Name = fmt.Sprintf("%s_%s", s.Name, newStep.Name)
	}

	return config.Steps, nil
}


func (hs *HTTPServer) pluginMarkdown(ctx context.Context, pluginId string, name string) ([]byte, error) {
	plugin, exists := hs.pluginStore.Plugin(ctx, pluginId)
	if !exists {
		return nil, plugins.NotFoundError{PluginID: pluginId}
	}

	// nolint:gosec
	// We can ignore the gosec G304 warning on this one because `plugin.PluginDir` is based
	// on plugin the folder structure on disk and not user input.
	path := filepath.Join(plugin.PluginDir, fmt.Sprintf("%s.md", strings.ToUpper(name)))
	exists, err := fs.Exists(path)
	if err != nil {
		return nil, err
	}
	if !exists {
		path = filepath.Join(plugin.PluginDir, fmt.Sprintf("%s.md", strings.ToLower(name)))
	}

	exists, err = fs.Exists(path)
	if err != nil {
		return nil, err
	}
	if !exists {
		return make([]byte, 0), nil
	}

	// nolint:gosec
	// We can ignore the gosec G304 warning on this one because `plugin.PluginDir` is based
	// on plugin the folder structure on disk and not user input.
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	return data, nil
}


func checkAuth(ctx context.Context, config Config, auth string) (context.Context, bool) {
	const basicPrefix = "Basic "
	const bearerPrefix = "Bearer "

	if strings.HasPrefix(auth, basicPrefix) {
		// Basic authentication.
		username, password, ok := parseBasicAuth(auth)
		if !ok {
			return ctx, false
		}

		if username != config.GetConsole().Username || password != config.GetConsole().Password {
			// Username and/or password do not match.
			return ctx, false
		}

		ctx = context.WithValue(context.WithValue(context.WithValue(ctx, ctxConsoleRoleKey{}, console.UserRole_USER_ROLE_ADMIN), ctxConsoleUsernameKey{}, username), ctxConsoleEmailKey{}, "")
		// Basic authentication successful.
		return ctx, true
	} else if strings.HasPrefix(auth, bearerPrefix) {
		// Bearer token authentication.
		token, err := jwt.Parse(auth[len(bearerPrefix):], func(token *jwt.Token) (interface{}, error) {
			if s, ok := token.Method.(*jwt.SigningMethodHMAC); !ok || s.Hash != crypto.SHA256 {
				return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
			}
			return []byte(config.GetConsole().SigningKey), nil
		})
		if err != nil {
			// Token verification failed.
			return ctx, false
		}
		uname, email, role, exp, ok := parseConsoleToken([]byte(config.GetConsole().SigningKey), auth[len(bearerPrefix):])
		if !ok || !token.Valid {
			// The token or its claims are invalid.
			return ctx, false
		}
		if !ok {
			// Expiry time claim is invalid.
			return ctx, false
		}
		if exp <= time.Now().UTC().Unix() {
			// Token expired.
			return ctx, false
		}

		ctx = context.WithValue(context.WithValue(context.WithValue(ctx, ctxConsoleRoleKey{}, role), ctxConsoleUsernameKey{}, uname), ctxConsoleEmailKey{}, email)

		return ctx, true
	}

	return ctx, false
}


func (x *DeleteGroupUserRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[18]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (s *SMTP) GetDialer() (mailer.Dialer, error) {
	// Setup the message and dial
	hp := strings.Split(s.Host, ":")
	if len(hp) < 2 {
		hp = append(hp, "25")
	}
	host := hp[0]
	// Any issues should have been caught in validation, but we'll
	// double check here.
	port, err := strconv.Atoi(hp[1])
	if err != nil {
		log.Error(err)
		return nil, err
	}
	d := gomail.NewDialer(host, port, s.Username, s.Password)
	d.TLSConfig = &tls.Config{
		ServerName:         host,
		InsecureSkipVerify: s.IgnoreCertErrors,
	}
	hostname, err := os.Hostname()
	if err != nil {
		log.Error(err)
		hostname = "localhost"
	}
	d.LocalName = hostname
	return &Dialer{d}, err
}


func (err ErrInvalidCloneAddr) Error() string {
	return fmt.Sprintf("invalid clone address [is_url_error: %v, is_invalid_path: %v, is_permission_denied: %v]",
		err.IsURLError, err.IsInvalidPath, err.IsPermissionDenied)
}


func (p *CompactProtocol) ReadBinary() (value []byte, err error) {
	length, e := p.readVarint32()
	if e != nil {
		return nil, NewProtocolException(e)
	}
	if length == 0 {
		return []byte{}, nil
	}
	if length < 0 {
		return nil, invalidDataLength
	}
	if uint64(length) > p.trans.RemainingBytes() {
		return nil, invalidDataLength
	}

	buf := make([]byte, length)
	_, e = io.ReadFull(p.trans, buf)
	return buf, NewProtocolException(e)
}


func (x *ListGroupsRequest) Reset() {
	*x = ListGroupsRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[27]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func main() {
	hostPtr := flag.String("host", "localhost:9159", "the hostname that the server should listen on.")
	tokenPtr := flag.String("token", "", "the Proxy Access Token used to restrict access to the server.")
	allowedOriginsPtr := flag.String("allowed-origins", "*", "a comma separated list of allowed origins.")
	bannedOutputsPtr := flag.String("banned-outputs", "", "a comma separated list of banned outputs.")
	flag.Parse()

	finished := make(chan bool)
	libproxy.Initialize(*tokenPtr, *hostPtr, *allowedOriginsPtr, *bannedOutputsPtr, onProxyStateChangeServer, false, finished)

	<-finished
}


func (p *HTTPClient) Read(buf []byte) (int, error) {
	if p.response == nil {
		return 0, NewTransportException(NOT_OPEN, "Response buffer is empty, no request.")
	}
	n, err := p.response.Body.Read(buf)
	if n > 0 && (err == nil || err == io.EOF) {
		return n, nil
	}
	return n, NewTransportExceptionFromError(err)
}


func (*ListStorageRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{30}
}


func (x *Leaderboard) Reset() {
	*x = Leaderboard{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[23]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (s *Server) CheckDeletionToken(deletionToken, token, filename string) error {
	s.Lock(token, filename)
	defer s.Unlock(token, filename)

	var metadata Metadata

	r, _, err := s.storage.Get(token, fmt.Sprintf("%s.metadata", filename))
	if s.storage.IsNotExist(err) {
		return nil
	} else if err != nil {
		return err
	}

	defer r.Close()

	if err := json.NewDecoder(r).Decode(&metadata); err != nil {
		return err
	} else if metadata.DeletionToken != deletionToken {
		return errors.New("Deletion token doesn't match.")
	}

	return nil
}


func isMatchingRedirectURI(uri string, haystack []string) bool {
	requested, err := url.Parse(uri)
	if err != nil {
		return false
	}

	for _, b := range haystack {
		if strings.ToLower(b) == strings.ToLower(uri) || isLoopbackURI(requested, b) {
			return true
		}
	}
	return false
}


func TestUnsafeAllowPrivateRanges (t *testing.T) {
	a := assert.New(t)

	conf := NewConfig()
	a.NoError(conf.SetDenyRanges([]string {"192.168.0.0/24", "10.0.0.0/8"}))
	conf.ConnectTimeout = 10 * time.Second
	conf.ExitTimeout = 10 * time.Second
	conf.AdditionalErrorMessageOnDeny = "Proxy denied"

	conf.UnsafeAllowPrivateRanges = true

	testIPs := []testCase{
		testCase{"8.8.8.8", 1, ipAllowDefault},

		// Specific blocked networks
		testCase{"10.0.0.1", 1, ipDenyUserConfigured},
		testCase{"10.0.0.1", 321, ipDenyUserConfigured},
		testCase{"10.0.1.1", 1, ipDenyUserConfigured},
		testCase{"172.16.0.1", 1, ipAllowDefault},
		testCase{"172.16.1.1", 1, ipAllowDefault},
		testCase{"192.168.0.1", 1, ipDenyUserConfigured},
		testCase{"192.168.1.1", 1, ipAllowDefault},

		// localhost
		testCase{"127.0.0.1", 1, ipDenyNotGlobalUnicast},
		testCase{"127.255.255.255", 1, ipDenyNotGlobalUnicast},
		testCase{"::1", 1, ipDenyNotGlobalUnicast},

		// ec2 metadata endpoint
		testCase{"169.254.169.254", 1, ipDenyNotGlobalUnicast},

		// Broadcast addresses
		testCase{"255.255.255.255", 1, ipDenyNotGlobalUnicast},
		testCase{"ff02:0:0:0:0:0:0:2", 1, ipDenyNotGlobalUnicast},
	}

	for _, test := range testIPs {
		localIP := net.ParseIP(test.ip)
		if localIP == nil {
			t.Errorf("Could not parse IP from string: %s", test.ip)
			continue
		}
		localAddr := net.TCPAddr{
			IP:   localIP,
			Port: test.port,
		}

		got := classifyAddr(conf, &localAddr)
		if got != test.expected {
			t.Errorf("Misclassified IP (%s): should be %s, but is instead %s.", localIP, test.expected, got)
		}
	}

}


func TestClean(t *testing.T) {
	tests := []struct {
		path   string
		expVal string
	}{
		{
			path:   "../../../readme.txt",
			expVal: "readme.txt",
		},
		{
			path:   "a/../../../readme.txt",
			expVal: "readme.txt",
		},
		{
			path:   "/../a/b/../c/../readme.txt",
			expVal: "a/readme.txt",
		},
		{
			path:   "/a/readme.txt",
			expVal: "a/readme.txt",
		},
		{
			path:   "/",
			expVal: "",
		},

		{
			path:   "/a/b/c/readme.txt",
			expVal: "a/b/c/readme.txt",
		},
	}
	for _, test := range tests {
		t.Run("", func(t *testing.T) {
			assert.Equal(t, test.expVal, Clean(test.path))
		})
	}
}


func createDefaultConfigFileIfNotExists() error {
	defaultFilePath := GetDefaultConfigFilePath()
	if isExists(defaultFilePath) {
		return nil
	}
	folderPath := filepath.Dir(defaultFilePath)
	if !isExists(folderPath) {
		err := os.Mkdir(folderPath, folderPermission)
		if err != nil {
			return err
		}
	}
	f, err := os.Create(defaultFilePath)
	if err != nil {
		return err
	}
	return f.Close()
}


func IsLocalHostname(hostname string, allowlist []string) bool {
	for _, allow := range allowlist {
		if hostname == allow {
			return false
		}
	}

	ips, err := net.LookupIP(hostname)
	if err != nil {
		return true
	}
	for _, ip := range ips {
		for _, cidr := range localCIDRs {
			if cidr.Contains(ip) {
				return true
			}
		}
	}
	return false
}


func (*Username) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{38}
}


func (p *CompactProtocol) ReadFieldBegin() (name string, typeId Type, id int16, err error) {
	t, err := p.readByteDirect()
	if err != nil {
		return
	}

	// if it's a stop, then we can return immediately, as the struct is over.
	if (t & 0x0f) == STOP {
		return "", STOP, 0, nil
	}

	// mask off the 4 MSB of the type header. it could contain a field id delta.
	modifier := int16((t & 0xf0) >> 4)
	if modifier == 0 {
		// not a delta. look ahead for the zigzag varint field id.
		id, err = p.ReadI16()
		if err != nil {
			return
		}
	} else {
		// has a delta. add the delta to the last read field id.
		id = int16(p.lastFieldIDRead) + modifier
	}
	typeId, e := p.getType(compactType(t & 0x0f))
	if e != nil {
		err = NewProtocolException(e)
		return
	}

	// if this happens to be a boolean field, the value is encoded in the type
	if p.isBoolType(t) {
		// save the boolean value in a special instance variable.
		p.boolValue = (byte(t)&0x0f == COMPACT_BOOLEAN_TRUE)
		p.boolValueIsNotNull = true
	}

	// push the new field onto the field stack so we can keep the deltas going.
	p.lastFieldIDRead = int(id)
	return
}


func ServeData(ctx *context.Context, name string, size int64, reader io.Reader) error {
	buf := make([]byte, 1024)
	n, err := util.ReadAtMost(reader, buf)
	if err != nil {
		return err
	}
	if n >= 0 {
		buf = buf[:n]
	}

	ctx.Resp.Header().Set("Cache-Control", "public,max-age=86400")

	if size >= 0 {
		ctx.Resp.Header().Set("Content-Length", fmt.Sprintf("%d", size))
	} else {
		log.Error("ServeData called to serve data: %s with size < 0: %d", name, size)
	}
	name = path.Base(name)

	// Google Chrome dislike commas in filenames, so let's change it to a space
	name = strings.ReplaceAll(name, ",", " ")

	st := typesniffer.DetectContentType(buf)

	mappedMimeType := ""
	if setting.MimeTypeMap.Enabled {
		fileExtension := strings.ToLower(filepath.Ext(name))
		mappedMimeType = setting.MimeTypeMap.Map[fileExtension]
	}
	if st.IsText() || ctx.FormBool("render") {
		cs, err := charset.DetectEncoding(buf)
		if err != nil {
			log.Error("Detect raw file %s charset failed: %v, using by default utf-8", name, err)
			cs = "utf-8"
		}
		if mappedMimeType == "" {
			mappedMimeType = "text/plain"
		}
		ctx.Resp.Header().Set("Content-Type", mappedMimeType+"; charset="+strings.ToLower(cs))
	} else {
		ctx.Resp.Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
		if mappedMimeType != "" {
			ctx.Resp.Header().Set("Content-Type", mappedMimeType)
		}
		if (st.IsImage() || st.IsPDF()) && (setting.UI.SVG.Enabled || !st.IsSvgImage()) {
			ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
			if st.IsSvgImage() {
				ctx.Resp.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox")
				ctx.Resp.Header().Set("X-Content-Type-Options", "nosniff")
				ctx.Resp.Header().Set("Content-Type", typesniffer.SvgMimeType)
			}
		} else {
			ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
		}
	}

	_, err = ctx.Resp.Write(buf)
	if err != nil {
		return err
	}
	_, err = io.Copy(ctx.Resp, reader)
	return err
}


func handleConnect(config *Config, pctx *goproxy.ProxyCtx) error {
	sctx := pctx.UserData.(*smokescreenContext)

	// Check if requesting role is allowed to talk to remote
	sctx.decision, sctx.lookupTime, pctx.Error = checkIfRequestShouldBeProxied(config, pctx.Req, pctx.Req.Host)
	if pctx.Error != nil {
		return pctx.Error
	}
	if !sctx.decision.allow {
		return denyError{errors.New(sctx.decision.reason)}
	}

	return nil
}


func (p *Profile) writeConfWgQuick(data *WgConf) (pth string, err error) {
	allowedIps := []string{}
	if data.Routes != nil {
		for _, route := range data.Routes {
			allowedIps = append(allowedIps, route.Network)
		}
	}
	if data.Routes6 != nil {
		for _, route := range data.Routes6 {
			allowedIps = append(allowedIps, route.Network)
		}
	}

	addr := data.Address
	if data.Address6 != "" {
		addr += "," + data.Address6
	}

	templData := WgConfData{
		Address:    addr,
		PrivateKey: p.PrivateKeyWg,
		PublicKey:  data.PublicKey,
		AllowedIps: strings.Join(allowedIps, ","),
		Endpoint:   fmt.Sprintf("%s:%d", data.Hostname, data.Port),
	}

	if data.DnsServers != nil && len(data.DnsServers) > 0 {
		templData.HasDns = true
		templData.DnsServers = strings.Join(data.DnsServers, ",")
	}

	output := &bytes.Buffer{}
	err = WgConfTempl.Execute(output, templData)
	if err != nil {
		err = &errortypes.ParseError{
			errors.Wrap(err, "profile: Failed to exec wg template"),
		}
		return
	}

	rootDir := ""
	switch runtime.GOOS {
	case "linux":
		rootDir = WgLinuxConfPath

		err = os.MkdirAll(WgLinuxConfPath, 0700)
		if err != nil {
			err = &errortypes.WriteError{
				errors.Wrap(
					err, "profile: Failed to create wg conf directory"),
			}
			return
		}
	case "darwin":
		rootDir = WgMacConfPath

		err = os.MkdirAll(WgMacConfPath, 0700)
		if err != nil {
			err = &errortypes.WriteError{
				errors.Wrap(
					err, "profile: Failed to create wg conf directory"),
			}
			return
		}
	default:
		rootDir, err = utils.GetTempDir()
		if err != nil {
			return
		}
	}

	pth = filepath.Join(rootDir, p.Iface+".conf")

	os.Remove(pth)
	err = ioutil.WriteFile(
		pth,
		[]byte(output.String()),
		os.FileMode(0600),
	)
	if err != nil {
		err = &WriteError{
			errors.Wrap(err, "profile: Failed to write wg conf"),
		}
		return
	}

	return
}


func (*CallApiEndpointRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{12}
}


func WriteCode(id string, code string) {
	memory.Code[id] = code
}


func (x *DeleteFriendRequest) Reset() {
	*x = DeleteFriendRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[16]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (p *BinaryProtocol) ReadBinary() ([]byte, error) {
	size, e := p.ReadI32()
	if e != nil {
		return nil, e
	}
	if size < 0 {
		return nil, invalidDataLength
	}
	if uint64(size) > p.trans.RemainingBytes() {
		return nil, invalidDataLength
	}

	isize := int(size)
	buf := make([]byte, isize)
	_, err := io.ReadFull(p.trans, buf)
	return buf, NewProtocolException(err)
}


func (*DeleteStorageObjectRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{21}
}


func (*Config_Warning) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{14, 0}
}


func (*DeleteGroupUserRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{18}
}


func checkVersion() {
	// Templates.
	data, err := ioutil.ReadFile(path.Join(setting.StaticRootPath, "templates/.VERSION"))
	if err != nil {
		log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
	}
	if string(data) != setting.AppVer {
		log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
	}

	// Check dependency version.
	macaronVer := git.MustParseVersion(strings.Join(strings.Split(macaron.Version(), ".")[:3], "."))
	if macaronVer.LessThan(git.MustParseVersion("0.2.3")) {
		log.Fatal(4, "Package macaron version is too old, did you forget to update?(github.com/Unknwon/macaron)")
	}
	i18nVer := git.MustParseVersion(i18n.Version())
	if i18nVer.LessThan(git.MustParseVersion("0.0.2")) {
		log.Fatal(4, "Package i18n version is too old, did you forget to update?(github.com/macaron-contrib/i18n)")
	}
	sessionVer := git.MustParseVersion(session.Version())
	if sessionVer.LessThan(git.MustParseVersion("0.0.3")) {
		log.Fatal(4, "Package session version is too old, did you forget to update?(github.com/macaron-contrib/session)")
	}
}


func (x *ListAccountsRequest) Reset() {
	*x = ListAccountsRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[26]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (p *HTTPClient) RemainingBytes() (num_bytes uint64) {
	len := p.response.ContentLength
	if len >= 0 {
		return uint64(len)
	}

	return UnknownRemaining // the truth is, we just don't know unless framed is used
}


func (x *StorageList) Reset() {
	*x = StorageList{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[33]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *WalletLedgerList) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[43]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*ListGroupsRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{27}
}


func TestReadMIMEHeaderNonCompliant(t *testing.T) {
	// Invalid HTTP response header as sent by an Axis security
	// camera: (this is handled by IE, Firefox, Chrome, curl, etc.)
	r := reader("Foo: bar\r\n" +
		"Content-Language: en\r\n" +
		"SID : 0\r\n" +
		"Audio Mode : None\r\n" +
		"Privilege : 127\r\n\r\n")
	m, err := r.ReadMIMEHeader()
	want := MIMEHeader{
		"Foo":              {"bar"},
		"Content-Language": {"en"},
		"Sid":              {"0"},
		"Audio-Mode":       {"None"},
		"Privilege":        {"127"},
	}
	if !reflect.DeepEqual(m, want) || err != nil {
		t.Fatalf("ReadMIMEHeader =\n%v, %v; want:\n%v", m, err, want)
	}
}


func TestInvalidPaddingOpen(t *testing.T) {
	key := make([]byte, 32)
	nonce := make([]byte, 16)

	// Plaintext with invalid padding
	plaintext := padBuffer(make([]byte, 28), aes.BlockSize)
	plaintext[len(plaintext)-1] = 0xFF

	io.ReadFull(rand.Reader, key)
	io.ReadFull(rand.Reader, nonce)

	block, _ := aes.NewCipher(key)
	cbc := cipher.NewCBCEncrypter(block, nonce)
	buffer := append([]byte{}, plaintext...)
	cbc.CryptBlocks(buffer, buffer)

	aead, _ := NewCBCHMAC(key, aes.NewCipher)
	ctx := aead.(*cbcAEAD)

	// Mutated ciphertext, but with correct auth tag
	size := len(buffer)
	ciphertext, tail := resize(buffer, size+(len(key)/2))
	copy(tail, ctx.computeAuthTag(nil, nonce, ciphertext[:size]))

	// Open should fail (b/c of invalid padding, even though tag matches)
	_, err := aead.Open(nil, nonce, ciphertext, nil)
	if err == nil || !strings.Contains(err.Error(), "invalid padding") {
		t.Error("no or unexpected error on open with invalid padding:", err)
	}
}


func (*WalletLedgerList) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{43}
}


func fixTransferEncoding(requestMethod string, header Header) ([]string, error) {
	raw, present := header["Transfer-Encoding"]
	if !present {
		return nil, nil
	}

	delete(header, "Transfer-Encoding")

	encodings := strings.Split(raw[0], ",")
	te := make([]string, 0, len(encodings))
	// TODO: Even though we only support "identity" and "chunked"
	// encodings, the loop below is designed with foresight. One
	// invariant that must be maintained is that, if present,
	// chunked encoding must always come first.
	for _, encoding := range encodings {
		encoding = strings.ToLower(strings.TrimSpace(encoding))
		// "identity" encoding is not recorded
		if encoding == "identity" {
			break
		}
		if encoding != "chunked" {
			return nil, &badStringError{"unsupported transfer encoding", encoding}
		}
		te = te[0 : len(te)+1]
		te[len(te)-1] = encoding
	}
	if len(te) > 1 {
		return nil, &badStringError{"too many transfer encodings", strings.Join(te, ",")}
	}
	if len(te) > 0 {
		// Chunked encoding trumps Content-Length. See RFC 2616
		// Section 4.4. Currently len(te) > 0 implies chunked
		// encoding.
		delete(header, "Content-Length")
		return te, nil
	}

	return nil, nil
}


func (x *StatusList) Reset() {
	*x = StatusList{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[40]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *ListStorageRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[30]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (s *ConsoleServer) lookupConsoleUser(ctx context.Context, unameOrEmail, password string) (id uuid.UUID, uname string, email string, role console.UserRole, err error) {
	role = console.UserRole_USER_ROLE_UNKNOWN
	query := "SELECT id, username, email, role, password, disable_time FROM console_user WHERE username = $1 OR email = $1"
	var dbPassword []byte
	var dbDisableTime pgtype.Timestamptz
	err = s.db.QueryRowContext(ctx, query, unameOrEmail).Scan(&id, &uname, &email, &role, &dbPassword, &dbDisableTime)
	if err != nil {
		if err == sql.ErrNoRows {
			err = nil
		}
		return
	}

	// Check if it's disabled.
	if dbDisableTime.Status == pgtype.Present && dbDisableTime.Time.Unix() != 0 {
		s.logger.Info("Console user account is disabled.", zap.String("username", unameOrEmail))
		err = status.Error(codes.PermissionDenied, "Invalid credentials.")
		return
	}

	// Check password
	err = bcrypt.CompareHashAndPassword(dbPassword, []byte(password))
	if err != nil {
		err = status.Error(codes.Unauthenticated, "Invalid credentials.")
		return
	}

	return

}


func GetCode(id string) string {
	return memory.Code[id]
}


func ReadWriteProtocolTest(t *testing.T, protocolFactory ProtocolFactory) {
	buf := bytes.NewBuffer(make([]byte, 0, 1024))
	l := HTTPClientSetupForTest(t)
	defer l.Close()
	transports := []TransportFactory{
		NewMemoryBufferTransportFactory(1024),
		NewStreamTransportFactory(buf, buf, true),
		NewFramedTransportFactory(NewMemoryBufferTransportFactory(1024)),
		NewHTTPPostClientTransportFactory("http://" + l.Addr().String()),
	}

	doForAllTransports := func(protTest protocolTest) {
		for _, tf := range transports {
			trans := tf.GetTransport(nil)
			p := protocolFactory.GetProtocol(trans)
			protTest(t, p, trans)
			trans.Close()
		}
	}

	doForAllTransports(ReadWriteBool)
	doForAllTransports(ReadWriteByte)
	doForAllTransports(ReadWriteI16)
	doForAllTransports(ReadWriteI32)
	doForAllTransports(ReadWriteI64)
	doForAllTransports(ReadWriteDouble)
	doForAllTransports(ReadWriteFloat)
	doForAllTransports(ReadWriteString)
	doForAllTransports(ReadWriteBinary)
	doForAllTransports(ReadWriteStruct)

	// perform set of many sequenced reads and writes
	doForAllTransports(func(t testing.TB, p Protocol, trans Transport) {
		ReadWriteI64(t, p, trans)
		ReadWriteDouble(t, p, trans)
		ReadWriteFloat(t, p, trans)
		ReadWriteBinary(t, p, trans)
		ReadWriteByte(t, p, trans)
		ReadWriteStruct(t, p, trans)
	})
}


		s := strings.Map(func(c rune) rune {
			switch c {
			case ' ', '\t', '\n', '\f', '\r':
				return c
			}
			return -1
		}, p.tok.Data)
		if s != "" {
			p.addText(s)
		}
	case StartTagToken:
		switch p.tok.DataAtom {
		case a.Html:
			return inBodyIM(p)
		case a.Frameset:
			p.addElement()
		case a.Frame:
			p.addElement()
			p.oe.pop()
			p.acknowledgeSelfClosingTag()
		case a.Noframes:
			return inHeadIM(p)
		case a.Template:
			// TODO: remove this divergence from the HTML5 spec.
			//
			// See https://bugs.chromium.org/p/chromium/issues/detail?id=829668
			return inTemplateIM(p)
		}
	case EndTagToken:
		switch p.tok.DataAtom {
		case a.Frameset:
			if p.oe.top().DataAtom != a.Html {
				p.oe.pop()
				if p.oe.top().DataAtom != a.Frameset {
					p.im = afterFramesetIM
					return true
				}
			}
		}
	default:
		// Ignore the token.
	}


func (x *Leaderboard) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[23]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (x *CallApiEndpointResponse) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[13]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func TestNewOAuth2ResourceServer(t *testing.T) {
	newMockResourceServer(t)
}


func (x *DeleteGroupRequest) Reset() {
	*x = DeleteGroupRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[17]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (rarFormat) Read(input io.Reader, destination string) error {
	rr, err := rardecode.NewReader(input, "")
	if err != nil {
		return fmt.Errorf("read: failed to create reader: %v", err)
	}

	for {
		header, err := rr.Next()
		if err == io.EOF {
			break
		} else if err != nil {
			return err
		}

		if header.IsDir {
			err = mkdir(filepath.Join(destination, header.Name))
			if err != nil {
				return err
			}
			continue
		}

		// if files come before their containing folders, then we must
		// create their folders before writing the file
		err = mkdir(filepath.Dir(filepath.Join(destination, header.Name)))
		if err != nil {
			return err
		}

		err = writeNewFile(filepath.Join(destination, header.Name), rr, header.Mode())
		if err != nil {
			return err
		}
	}

	return nil
}


func isLoopbackURI(requested *url.URL, registeredURI string) bool {
	registered, err := url.Parse(registeredURI)
	if err != nil {
		return false
	}

	if registered.Scheme != "http" || !isLoopbackAddress(registered.Host) {
		return false
	}

	if requested.Scheme == "http" && isLoopbackAddress(requested.Host) && registered.Path == requested.Path {
		return true
	}

	return false
}


func (x *DeleteGroupUserRequest) Reset() {
	*x = DeleteGroupUserRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[18]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (*UpdateGroupRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{37}
}


func resize(in []byte, n int) (head, tail []byte) {
	if cap(in) >= n {
		head = in[:n]
	} else {
		head = make([]byte, n)
		copy(head, in)
	}

	tail = head[len(in):]
	return
}


func (x *StatusList) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[40]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (x *DeleteWalletLedgerRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[22]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (x *DeleteLeaderboardRecordRequest) Reset() {
	*x = DeleteLeaderboardRecordRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[20]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func newContainerInit(t initType, pipe *os.File, consoleSocket *os.File, fifoFd, logFd int) (initer, error) {
	var config *initConfig
	if err := json.NewDecoder(pipe).Decode(&config); err != nil {
		return nil, err
	}
	if err := populateProcessEnvironment(config.Env); err != nil {
		return nil, err
	}
	switch t {
	case initSetns:
		return &linuxSetnsInit{
			pipe:          pipe,
			consoleSocket: consoleSocket,
			config:        config,
			logFd:         logFd,
		}, nil
	case initStandard:
		return &linuxStandardInit{
			pipe:          pipe,
			consoleSocket: consoleSocket,
			parentPid:     unix.Getppid(),
			config:        config,
			fifoFd:        fifoFd,
			logFd:         logFd,
		}, nil
	}
	return nil, fmt.Errorf("unknown init type %q", t)
}


func parseConsoleToken(hmacSecretByte []byte, tokenString string) (username, email string, role console.UserRole, exp int64, ok bool) {
	token, err := jwt.ParseWithClaims(tokenString, &ConsoleTokenClaims{}, func(token *jwt.Token) (interface{}, error) {
		if s, ok := token.Method.(*jwt.SigningMethodHMAC); !ok || s.Hash != crypto.SHA256 {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return hmacSecretByte, nil
	})
	if err != nil {
		return
	}
	claims, ok := token.Claims.(*ConsoleTokenClaims)
	if !ok || !token.Valid {
		return
	}
	return claims.Username, claims.Email, claims.Role, claims.ExpiresAt, true
}


func (x *StorageList) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[33]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (x *ListAccountsRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[26]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*LeaderboardList) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{24}
}


func (x *WalletLedgerList) Reset() {
	*x = WalletLedgerList{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[43]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *LeaderboardRequest) Reset() {
	*x = LeaderboardRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[25]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func doTmpfsCopyUp(m *configs.Mount, rootfs, mountLabel string) (Err error) {
	// Set up a scratch dir for the tmpfs on the host.
	tmpdir, err := prepareTmp("/tmp")
	if err != nil {
		return fmt.Errorf("tmpcopyup: failed to setup tmpdir: %w", err)
	}
	defer cleanupTmp(tmpdir)
	tmpDir, err := ioutil.TempDir(tmpdir, "runctmpdir")
	if err != nil {
		return fmt.Errorf("tmpcopyup: failed to create tmpdir: %w", err)
	}
	defer os.RemoveAll(tmpDir)

	// Configure the *host* tmpdir as if it's the container mount. We change
	// m.Destination since we are going to mount *on the host*.
	oldDest := m.Destination
	m.Destination = tmpDir
	err = mountPropagate(m, "/", mountLabel)
	m.Destination = oldDest
	if err != nil {
		return err
	}
	defer func() {
		if Err != nil {
			if err := unmount(tmpDir, unix.MNT_DETACH); err != nil {
				logrus.Warnf("tmpcopyup: %v", err)
			}
		}
	}()

	return utils.WithProcfd(rootfs, m.Destination, func(procfd string) (Err error) {
		// Copy the container data to the host tmpdir. We append "/" to force
		// CopyDirectory to resolve the symlink rather than trying to copy the
		// symlink itself.
		if err := fileutils.CopyDirectory(procfd+"/", tmpDir); err != nil {
			return fmt.Errorf("tmpcopyup: failed to copy %s to %s (%s): %w", m.Destination, procfd, tmpDir, err)
		}
		// Now move the mount into the container.
		if err := mount(tmpDir, m.Destination, procfd, "", unix.MS_MOVE, ""); err != nil {
			return fmt.Errorf("tmpcopyup: failed to move mount: %w", err)
		}
		return nil
	})
}


func cmdGet(args *docopt.Args, client *tuf.Client) error {
	if _, err := client.Update(); err != nil && !tuf.IsLatestSnapshot(err) {
		return err
	}
	target := util.NormalizeTarget(args.String["<target>"])
	file, err := ioutil.TempFile("", "go-tuf")
	if err != nil {
		return err
	}
	tmp := tmpFile{file}
	if err := client.Download(target, &tmp); err != nil {
		return err
	}
	defer tmp.Delete()
	if _, err := tmp.Seek(0, io.SeekStart); err != nil {
		return err
	}
	_, err = io.Copy(os.Stdout, file)
	return err
}


func (x *Username) Reset() {
	*x = Username{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[38]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func TestGetDynamic(t *testing.T) {
	savedServices := services
	savedGetVCSDirFn := getVCSDirFn
	defer func() {
		services = savedServices
		getVCSDirFn = savedGetVCSDirFn
	}()
	services = []*service{{pattern: regexp.MustCompile(".*"), get: testGet}}
	getVCSDirFn = testGet
	client := &http.Client{Transport: testTransport(testWeb)}

	for _, tt := range getDynamicTests {
		dir, err := getDynamic(context.Background(), client, tt.importPath, "")

		if tt.dir == nil {
			if err == nil {
				t.Errorf("getDynamic(client, %q, etag) did not return expected error", tt.importPath)
			}
			continue
		}

		if err != nil {
			t.Errorf("getDynamic(client, %q, etag) return unexpected error: %v", tt.importPath, err)
			continue
		}

		if !cmp.Equal(dir, tt.dir) {
			t.Errorf("getDynamic(client, %q, etag) =\n     %+v,\nwant %+v", tt.importPath, dir, tt.dir)
			for i, f := range dir.Files {
				var want *File
				if i < len(tt.dir.Files) {
					want = tt.dir.Files[i]
				}
				t.Errorf("file %d = %+v, want %+v", i, f, want)
			}
		}
	}
}


func (x *Config_Warning) Reset() {
	*x = Config_Warning{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[46]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *MatchStateRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[32]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (x *RuntimeInfo_ModuleInfo) Reset() {
	*x = RuntimeInfo_ModuleInfo{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[50]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *ConsoleSession) Reset() {
	*x = ConsoleSession{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[15]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *Config) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[14]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (o *casaService) GetServerAppInfo(id, t string) model.ServerAppList {

	head := make(map[string]string)

	head["Authorization"] = GetToken()
	infoS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/info/"+id+"?t="+t, head)

	info := model.ServerAppList{}
	json2.Unmarshal([]byte(gjson.Get(infoS, "data").String()), &info)

	return info
}


func (*RuntimeInfo) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{41}
}


func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {

	// Logic based on response type or status
	if noBodyExpected(requestMethod) {
		return 0, nil
	}
	if status/100 == 1 {
		return 0, nil
	}
	switch status {
	case 204, 304:
		return 0, nil
	}

	// Logic based on Transfer-Encoding
	if chunked(te) {
		return -1, nil
	}

	// Logic based on Content-Length
	cl := strings.TrimSpace(header.get("Content-Length"))
	if cl != "" {
		n, err := parseContentLength(cl)
		if err != nil {
			return -1, err
		}
		return n, nil
	} else {
		header.Del("Content-Length")
	}

	if !isResponse && requestMethod == "GET" {
		// RFC 2616 doesn't explicitly permit nor forbid an
		// entity-body on a GET request so we permit one if
		// declared, but we default to 0 here (not -1 below)
		// if there's no mention of a body.
		return 0, nil
	}

	// Body-EOF logic based on other methods (like closing, or chunked coding)
	return -1, nil
}


func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
	// Prevent SQL inject.
	opt.Keyword = strings.TrimSpace(opt.Keyword)
	if len(opt.Keyword) == 0 {
		return repos, nil
	}

	opt.Keyword = strings.Split(opt.Keyword, " ")[0]
	if len(opt.Keyword) == 0 {
		return repos, nil
	}
	opt.Keyword = strings.ToLower(opt.Keyword)

	repos = make([]*Repository, 0, opt.Limit)

	// Append conditions.
	sess := x.Limit(opt.Limit)
	if opt.Uid > 0 {
		sess.Where("owner_id=?", opt.Uid)
	}
	sess.And("lower_name like '%" + opt.Keyword + "%'").Find(&repos)
	return repos, err
}


func (x *Username) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[38]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*Provider) Render(ctx *provider.Context, config, data string) string {
	result := blackfriday.Run([]byte(data))

	return string(result)
}


func (c Criteria) OrderBy() string {
	if c.Sort == "" {
		c.Sort = "title"
	}
	f := fieldMap[strings.ToLower(c.Sort)]
	var mapped string
	if f == nil {
		log.Error("Invalid field in 'sort' field", "field", c.Sort)
		mapped = c.Sort
	} else {
		if f.order == "" {
			mapped = f.field
		} else {
			mapped = f.order
		}
	}
	if c.Order != "" {
		mapped = mapped + " " + c.Order
	}
	return mapped
}


func (*Config) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{14}
}


func SettingsEmailPost(c *context.Context, f form.AddEmail) {
	c.Title("settings.emails")
	c.PageIs("SettingsEmails")

	// Make emailaddress primary.
	if c.Query("_method") == "PRIMARY" {
		if err := db.MakeEmailPrimary(&db.EmailAddress{ID: c.QueryInt64("id")}); err != nil {
			c.ServerError("MakeEmailPrimary", err)
			return
		}

		c.SubURLRedirect("/user/settings/email")
		return
	}

	// Add Email address.
	emails, err := db.GetEmailAddresses(c.User.ID)
	if err != nil {
		c.ServerError("GetEmailAddresses", err)
		return
	}
	c.Data["Emails"] = emails

	if c.HasError() {
		c.Success(SETTINGS_EMAILS)
		return
	}

	emailAddr := &db.EmailAddress{
		UID:         c.User.ID,
		Email:       f.Email,
		IsActivated: !conf.Auth.RequireEmailConfirmation,
	}
	if err := db.AddEmailAddress(emailAddr); err != nil {
		if db.IsErrEmailAlreadyUsed(err) {
			c.RenderWithErr(c.Tr("form.email_been_used"), SETTINGS_EMAILS, &f)
		} else {
			c.ServerError("AddEmailAddress", err)
		}
		return
	}

	// Send confirmation email
	if conf.Auth.RequireEmailConfirmation {
		email.SendActivateEmailMail(c.Context, db.NewMailerUser(c.User), emailAddr.Email)

		if err := c.Cache.Put("MailResendLimit_"+c.User.LowerName, c.User.LowerName, 180); err != nil {
			log.Error("Set cache 'MailResendLimit' failed: %v", err)
		}
		c.Flash.Info(c.Tr("settings.add_email_confirmation_sent", emailAddr.Email, conf.Auth.ActivateCodeLives/60))
	} else {
		c.Flash.Success(c.Tr("settings.add_email_success"))
	}

	c.SubURLRedirect("/user/settings/email")
}


func (*UpdateGroupUserStateRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{19}
}


func (x *ListSubscriptionsRequest) Reset() {
	*x = ListSubscriptionsRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[29]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *ListPurchasesRequest) Reset() {
	*x = ListPurchasesRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[28]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *UnlinkDeviceRequest) Reset() {
	*x = UnlinkDeviceRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[35]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func MigratePost(c *context.Context, f form.MigrateRepo) {
	c.Data["Title"] = c.Tr("new_migrate")

	ctxUser := checkContextUser(c, f.Uid)
	if c.Written() {
		return
	}
	c.Data["ContextUser"] = ctxUser

	if c.HasError() {
		c.Success(MIGRATE)
		return
	}

	remoteAddr, err := f.ParseRemoteAddr(c.User)
	if err != nil {
		if db.IsErrInvalidCloneAddr(err) {
			c.Data["Err_CloneAddr"] = true
			addrErr := err.(db.ErrInvalidCloneAddr)
			switch {
			case addrErr.IsURLError:
				c.RenderWithErr(c.Tr("form.url_error"), MIGRATE, &f)
			case addrErr.IsPermissionDenied:
				c.RenderWithErr(c.Tr("repo.migrate.permission_denied"), MIGRATE, &f)
			case addrErr.IsInvalidPath:
				c.RenderWithErr(c.Tr("repo.migrate.invalid_local_path"), MIGRATE, &f)
			default:
				c.Error(err, "unexpected error")
			}
		} else {
			c.Error(err, "parse remote address")
		}
		return
	}

	repo, err := db.MigrateRepository(c.User, ctxUser, db.MigrateRepoOptions{
		Name:        f.RepoName,
		Description: f.Description,
		IsPrivate:   f.Private || conf.Repository.ForcePrivate,
		IsUnlisted:  f.Unlisted,
		IsMirror:    f.Mirror,
		RemoteAddr:  remoteAddr,
	})
	if err == nil {
		log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, f.RepoName)
		c.Redirect(conf.Server.Subpath + "/" + ctxUser.Name + "/" + f.RepoName)
		return
	}

	if repo != nil {
		if errDelete := db.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil {
			log.Error("DeleteRepository: %v", errDelete)
		}
	}

	if strings.Contains(err.Error(), "Authentication failed") ||
		strings.Contains(err.Error(), "could not read Username") {
		c.Data["Err_Auth"] = true
		c.RenderWithErr(c.Tr("form.auth_failed", db.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
		return
	} else if strings.Contains(err.Error(), "fatal:") {
		c.Data["Err_CloneAddr"] = true
		c.RenderWithErr(c.Tr("repo.migrate.failed", db.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
		return
	}

	handleCreateError(c, ctxUser, err, "MigratePost", MIGRATE, &f)
}


func (*StorageList) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{33}
}


func (x *UpdateGroupRequest) Reset() {
	*x = UpdateGroupRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[37]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (*StatusList) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{40}
}


func (x *RuntimeInfo_ModuleInfo) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[50]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (p *OAuthProxy) IsValidRedirect(redirect string) bool {
	switch {
	case redirect == "":
		// The user didn't specify a redirect, should fallback to `/`
		return false
	case strings.HasPrefix(redirect, "/") && !strings.HasPrefix(redirect, "//") && !invalidRedirectRegex.MatchString(redirect):
		return true
	case strings.HasPrefix(redirect, "http://") || strings.HasPrefix(redirect, "https://"):
		redirectURL, err := url.Parse(redirect)
		if err != nil {
			logger.Printf("Rejecting invalid redirect %q: scheme unsupported or missing", redirect)
			return false
		}
		redirectHostname := redirectURL.Hostname()

		for _, domain := range p.whitelistDomains {
			domainHostname, domainPort := splitHostPort(strings.TrimLeft(domain, "."))
			if domainHostname == "" {
				continue
			}

			if (redirectHostname == domainHostname) || (strings.HasPrefix(domain, ".") && strings.HasSuffix(redirectHostname, domainHostname)) {
				// the domain names match, now validate the ports
				// if the whitelisted domain's port is '*', allow all ports
				// if the whitelisted domain contains a specific port, only allow that port
				// if the whitelisted domain doesn't contain a port at all, only allow empty redirect ports ie http and https
				redirectPort := redirectURL.Port()
				if (domainPort == "*") ||
					(domainPort == redirectPort) ||
					(domainPort == "" && redirectPort == "") {
					return true
				}
			}
		}

		logger.Printf("Rejecting invalid redirect %q: domain / port not in whitelist", redirect)
		return false
	default:
		logger.Printf("Rejecting invalid redirect %q: not an absolute or relative URL", redirect)
		return false
	}
}


func (x *DeleteStorageObjectRequest) Reset() {
	*x = DeleteStorageObjectRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[21]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func UnpackTar(filename string, destination string, verbosityLevel int) (err error) {
	Verbose = verbosityLevel
	f, err := os.Stat(destination)
	if os.IsNotExist(err) {
		return fmt.Errorf("destination directory '%s' does not exist", destination)
	}
	filemode := f.Mode()
	if !filemode.IsDir() {
		return fmt.Errorf("destination '%s' is not a directory", destination)
	}
	if !validSuffix(filename) {
		return fmt.Errorf("unrecognized archive suffix")
	}
	var file *os.File
	// #nosec G304
	if file, err = os.Open(filename); err != nil {
		return err
	}
	defer file.Close()
	err = os.Chdir(destination)
	if err != nil {
		return errors.Wrapf(err, "error changing directory to %s", destination)
	}
	var fileReader io.Reader = file
	var decompressor *gzip.Reader
	if strings.HasSuffix(filename, globals.GzExt) {
		if decompressor, err = gzip.NewReader(file); err != nil {
			return err
		}
		defer decompressor.Close()
	}
	var reader *tar.Reader
	if decompressor != nil {
		reader = tar.NewReader(decompressor)
	} else {
		reader = tar.NewReader(fileReader)
	}
	return unpackTarFiles(reader)
}


func (ctx *cbcAEAD) Seal(dst, nonce, plaintext, data []byte) []byte {
	// Output buffer -- must take care not to mangle plaintext input.
	ciphertext := make([]byte, len(plaintext)+ctx.Overhead())[:len(plaintext)]
	copy(ciphertext, plaintext)
	ciphertext = padBuffer(ciphertext, ctx.blockCipher.BlockSize())

	cbc := cipher.NewCBCEncrypter(ctx.blockCipher, nonce)

	cbc.CryptBlocks(ciphertext, ciphertext)
	authtag := ctx.computeAuthTag(data, nonce, ciphertext)

	ret, out := resize(dst, len(dst)+len(ciphertext)+len(authtag))
	copy(out, ciphertext)
	copy(out[len(ciphertext):], authtag)

	return ret
}


func TestReadWriteCompactProtocol(t *testing.T) {
	ReadWriteProtocolTest(t, NewCompactProtocolFactory())
	// CompactProtocol is capable of reading and writing in different goroutines.
	ReadWriteProtocolParallelTest(t, NewCompactProtocolFactory())
	transports := []Transport{
		NewMemoryBuffer(),
		NewStreamTransportRW(bytes.NewBuffer(make([]byte, 0, 16384))),
		NewFramedTransport(NewMemoryBuffer()),
	}
	for _, trans := range transports {
		p := NewCompactProtocol(trans)
		ReadWriteBool(t, p, trans)
		p = NewCompactProtocol(trans)
		ReadWriteByte(t, p, trans)
		p = NewCompactProtocol(trans)
		ReadWriteI16(t, p, trans)
		p = NewCompactProtocol(trans)
		ReadWriteI32(t, p, trans)
		p = NewCompactProtocol(trans)
		ReadWriteI64(t, p, trans)
		p = NewCompactProtocol(trans)
		ReadWriteDouble(t, p, trans)
		p = NewCompactProtocol(trans)
		ReadWriteFloat(t, p, trans)
		p = NewCompactProtocol(trans)
		ReadWriteString(t, p, trans)
		p = NewCompactProtocol(trans)
		ReadWriteBinary(t, p, trans)
		p = NewCompactProtocol(trans)
		ReadWriteStruct(t, p, trans)
		trans.Close()
	}
}


func (x *ListPurchasesRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[28]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func newMockResourceServer(t testing.TB) ResourceServer {
	ctx := context.Background()
	dummy := ""
	serverURL := &dummy
	hf := func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/.well-known/oauth-authorization-server" {
			w.Header().Set("Content-Type", "application/json")
			_, err := io.WriteString(w, strings.ReplaceAll(`{
				"issuer": "https://dev-14186422.okta.com",
				"authorization_endpoint": "https://example.com/auth",
				"token_endpoint": "https://example.com/token",
				"jwks_uri": "URL/keys",
				"id_token_signing_alg_values_supported": ["RS256"]
			}`, "URL", *serverURL))

			if !assert.NoError(t, err) {
				t.FailNow()
			}

			return
		} else if r.URL.Path == "/keys" {
			keys := jwk.NewSet()
			raw, err := json.Marshal(keys)
			if err != nil {
				http.Error(w, err.Error(), 400)
				return
			}

			w.Header().Set("Content-Type", "application/json")
			_, err = io.WriteString(w, string(raw))

			if !assert.NoError(t, err) {
				t.FailNow()
			}
		}

		http.NotFound(w, r)
	}

	s := httptest.NewServer(http.HandlerFunc(hf))
	defer s.Close()

	*serverURL = s.URL

	http.DefaultClient = s.Client()

	r, err := NewOAuth2ResourceServer(ctx, authConfig.ExternalAuthorizationServer{
		BaseURL: stdlibConfig.URL{URL: *config.MustParseURL(s.URL)},
	}, stdlibConfig.URL{})
	if !assert.NoError(t, err) {
		t.FailNow()
	}

	return r
}


func (x *UpdateGroupUserStateRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[19]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


			func(ctx etreeutils.NSContext, signedInfo *etree.Element) error {
				detachedSignedInfo, err := etreeutils.NSDetatch(ctx, signedInfo)
				if err != nil {
					return err
				}

				c14NMethod, err := etreeutils.NSFindOneChildCtx(ctx, detachedSignedInfo, Namespace, CanonicalizationMethodTag)
				if err != nil {
					return err
				}

				if c14NMethod == nil {
					return errors.New("missing CanonicalizationMethod on Signature")
				}

				c14NAlgorithm := c14NMethod.SelectAttrValue(AlgorithmAttr, "")

				var canonicalSignedInfo *etree.Element

				switch AlgorithmID(c14NAlgorithm) {
				case CanonicalXML10ExclusiveAlgorithmId:
					err := etreeutils.TransformExcC14n(detachedSignedInfo, "")
					if err != nil {
						return err
					}

					// NOTE: TransformExcC14n transforms the element in-place,
					// while canonicalPrep isn't meant to. Once we standardize
					// this behavior we can drop this, as well as the adding and
					// removing of elements below.
					canonicalSignedInfo = detachedSignedInfo

				case CanonicalXML11AlgorithmId:
					canonicalSignedInfo = canonicalPrep(detachedSignedInfo, map[string]struct{}{})

				case CanonicalXML10RecAlgorithmId:
					canonicalSignedInfo = canonicalPrep(detachedSignedInfo, map[string]struct{}{})

				case CanonicalXML10CommentAlgorithmId:
					canonicalSignedInfo = canonicalPrep(detachedSignedInfo, map[string]struct{}{})

				default:
					return fmt.Errorf("invalid CanonicalizationMethod on Signature: %s", c14NAlgorithm)
				}

				el.RemoveChild(signedInfo)
				el.AddChild(canonicalSignedInfo)

				found = true

				return etreeutils.ErrTraversalHalted
			})


func UnpackXzTar(filename string, destination string, verbosityLevel int) (err error) {
	Verbose = verbosityLevel
	if !common.FileExists(filename) {
		return fmt.Errorf("file %s not found", filename)
	}
	if !common.DirExists(destination) {
		return fmt.Errorf("directory %s not found", destination)
	}
	filename, err = common.AbsolutePath(filename)
	if err != nil {
		return err
	}
	err = os.Chdir(destination)
	if err != nil {
		return errors.Wrapf(err, "error changing directory to %s", destination)
	}
	// #nosec G304
	f, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer f.Close()
	// Create an xz Reader
	r, err := xz.NewReader(f, 0)
	if err != nil {
		return err
	}
	// Create a tar Reader
	tr := tar.NewReader(r)
	return unpackTarFiles(tr)
}


func (db *DB) Verify(s *data.Signed, role string, minVersion int64) error {

	err := db.VerifyIgnoreExpiredCheck(s, role, minVersion)

	if err != nil {
		return err
	}

	sm := &signedMeta{}
	if err := json.Unmarshal(s.Signed, sm); err != nil {
		return err
	}

	if IsExpired(sm.Expires) {
		return ErrExpired{sm.Expires}
	}

	return nil
}


func ZeroTierLeaveNetwork(c *gin.Context) {
	networkId := c.Param("id")
	service.MyService.ZeroTier().ZeroTierLeaveNetwork(networkId)
	if len(networkId) == 0 {
		c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
		return
	}
	c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}


func NewLocalSessionCache(config Config) SessionCache {
	ctx, ctxCancelFn := context.WithCancel(context.Background())

	s := &LocalSessionCache{
		config: config,

		ctx:         ctx,
		ctxCancelFn: ctxCancelFn,

		cache: make(map[uuid.UUID]*sessionCacheUser),
	}

	go func() {
		ticker := time.NewTicker(2 * time.Duration(config.GetSession().TokenExpirySec) * time.Second)
		for {
			select {
			case <-s.ctx.Done():
				ticker.Stop()
				return
			case t := <-ticker.C:
				tMs := t.UTC().Unix()
				s.Lock()
				for userID, cache := range s.cache {
					for token, exp := range cache.sessionTokens {
						if exp <= tMs {
							delete(cache.sessionTokens, token)
						}
					}
					for token, exp := range cache.refreshTokens {
						if exp <= tMs {
							delete(cache.refreshTokens, token)
						}
					}
					if len(cache.sessionTokens) == 0 && len(cache.refreshTokens) == 0 {
						delete(s.cache, userID)
					}
				}
				s.Unlock()
			}
		}
	}()

	return s
}


func ZeroTierJoinNetwork(c *gin.Context) {
	networkId := c.Param("id")
	service.MyService.ZeroTier().ZeroTierJoinNetwork(networkId)
	if len(networkId) == 0 {
		c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
		return
	}
	c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}


func SnapshotFileMetaEqual(actual data.SnapshotFileMeta, expected data.SnapshotFileMeta) error {
	// TUF-1.0 no longer considers the length and hashes to be a required
	// member of snapshots. However they are considering requiring hashes
	// for delegated roles to avoid an attack described in Section 5.6 of
	// the Mercury paper:
	// https://github.com/theupdateframework/specification/pull/40
	if expected.Length != 0 && actual.Length != expected.Length {
		return ErrWrongLength{expected.Length, actual.Length}
	}

	if len(expected.Hashes) != 0 {
		if err := hashEqual(actual.Hashes, expected.Hashes); err != nil {
			return err
		}
	}

	if err := versionEqual(actual.Version, expected.Version); err != nil {
		return err
	}

	return nil
}


func (*StorageCollectionsList) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{34}
}


func (s *ConsoleServer) Authenticate(ctx context.Context, in *console.AuthenticateRequest) (*console.ConsoleSession, error) {
	role := console.UserRole_USER_ROLE_UNKNOWN
	var uname string
	var email string
	switch in.Username {
	case s.config.GetConsole().Username:
		if in.Password == s.config.GetConsole().Password {
			role = console.UserRole_USER_ROLE_ADMIN
			uname = in.Username
		}
	default:
		var err error
		uname, email, role, err = s.lookupConsoleUser(ctx, in.Username, in.Password)
		if err != nil {
			return nil, err
		}
	}

	if role == console.UserRole_USER_ROLE_UNKNOWN {
		return nil, status.Error(codes.Unauthenticated, "Invalid credentials.")
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, &ConsoleTokenClaims{
		ExpiresAt: time.Now().UTC().Add(time.Duration(s.config.GetConsole().TokenExpirySec) * time.Second).Unix(),
		Username:  uname,
		Email:     email,
		Role:      role,
		Cookie:    s.cookie,
	})
	key := []byte(s.config.GetConsole().SigningKey)
	signedToken, _ := token.SignedString(key)
	return &console.ConsoleSession{Token: signedToken}, nil
}


func padBuffer(buffer []byte, blockSize int) []byte {
	missing := blockSize - (len(buffer) % blockSize)
	ret, out := resize(buffer, len(buffer)+missing)
	padding := bytes.Repeat([]byte{byte(missing)}, missing)
	copy(out, padding)
	return ret
}


func (x *WalletLedger) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[42]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (x *RuntimeInfo) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[41]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (x *ConsoleSession) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[15]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (p *CompactProtocol) ReadString() (value string, err error) {
	length, e := p.readVarint32()
	if e != nil {
		return "", NewProtocolException(e)
	}
	if length < 0 {
		return "", invalidDataLength
	}
	if uint64(length) > p.trans.RemainingBytes() {
		return "", invalidDataLength
	}

	if length == 0 {
		return "", nil
	}
	var buf []byte
	if length <= int32(len(p.rBuffer)) {
		buf = p.rBuffer[0:length]
	} else {
		buf = make([]byte, length)
	}
	_, e = io.ReadFull(p.trans, buf)
	return string(buf), NewProtocolException(e)
}


func NewFositeMemoryStore(
	r InternalRegistry,
	c Configuration,
) *FositeMemoryStore {
	return &FositeMemoryStore{
		AuthorizeCodes: make(map[string]authorizeCode),
		IDSessions:     make(map[string]fosite.Requester),
		AccessTokens:   make(map[string]fosite.Requester),
		PKCES:          make(map[string]fosite.Requester),
		RefreshTokens:  make(map[string]fosite.Requester),

		c: c,
		r: r,
	}
}


func MakeEmailPrimary(email *EmailAddress) error {
	has, err := x.Get(email)
	if err != nil {
		return err
	} else if !has {
		return errors.EmailNotFound{Email: email.Email}
	}

	if !email.IsActivated {
		return errors.EmailNotVerified{Email: email.Email}
	}

	user := &User{ID: email.UID}
	has, err = x.Get(user)
	if err != nil {
		return err
	} else if !has {
		return errors.UserNotExist{UserID: email.UID}
	}

	// Make sure the former primary email doesn't disappear.
	formerPrimaryEmail := &EmailAddress{Email: user.Email}
	has, err = x.Get(formerPrimaryEmail)
	if err != nil {
		return err
	}

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return err
	}

	if !has {
		formerPrimaryEmail.UID = user.ID
		formerPrimaryEmail.IsActivated = user.IsActive
		if _, err = sess.Insert(formerPrimaryEmail); err != nil {
			return err
		}
	}

	user.Email = email.Email
	if _, err = sess.ID(user.ID).AllCols().Update(user); err != nil {
		return err
	}

	return sess.Commit()
}


func (x *DeleteGroupRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[17]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (f MigrateRepo) ParseRemoteAddr(user *db.User) (string, error) {
	remoteAddr := strings.TrimSpace(f.CloneAddr)

	// Remote address can be HTTP/HTTPS/Git URL or local path.
	if strings.HasPrefix(remoteAddr, "http://") ||
		strings.HasPrefix(remoteAddr, "https://") ||
		strings.HasPrefix(remoteAddr, "git://") {
		u, err := url.Parse(remoteAddr)
		if err != nil {
			return "", db.ErrInvalidCloneAddr{IsURLError: true}
		}

		if netutil.IsLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) {
			return "", db.ErrInvalidCloneAddr{IsURLError: true}
		}

		if len(f.AuthUsername)+len(f.AuthPassword) > 0 {
			u.User = url.UserPassword(f.AuthUsername, f.AuthPassword)
		}
		// To prevent CRLF injection in git protocol, see https://github.com/gogs/gogs/issues/6413
		if u.Scheme == "git" && (strings.Contains(remoteAddr, "%0d") || strings.Contains(remoteAddr, "%0a")) {
			return "", db.ErrInvalidCloneAddr{IsURLError: true}
		}
		remoteAddr = u.String()
	} else if !user.CanImportLocal() {
		return "", db.ErrInvalidCloneAddr{IsPermissionDenied: true}
	} else if !com.IsDir(remoteAddr) {
		return "", db.ErrInvalidCloneAddr{IsInvalidPath: true}
	}

	return remoteAddr, nil
}


func (*Leaderboard) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{23}
}


func isMatchingRedirectURI(uri string, haystack []string) bool {
	requested, err := url.Parse(uri)
	if err != nil {
		return false
	}

	for _, b := range haystack {
		if strings.ToLower(b) == strings.ToLower(uri) || isLoopbackURI(requested, b) {
			return true
		}
	}
	return false
}


func (x *StorageCollectionsList) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[34]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (d *partialArray) add(key string, val *lazyNode) error {
	if key == "-" {
		*d = append(*d, val)
		return nil
	}

	idx, err := strconv.Atoi(key)
	if err != nil {
		return err
	}

	ary := make([]*lazyNode, len(*d)+1)

	cur := *d

	if idx < 0 {
		idx *= -1

		if idx > len(ary) {
			return fmt.Errorf("Unable to access invalid index: %d", idx)
		}
		idx = len(ary) - idx
	}

	copy(ary[0:idx], cur[0:idx])
	ary[idx] = val
	copy(ary[idx+1:], cur[idx:])

	*d = ary
	return nil
}


func (x *WriteStorageObjectRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[44]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*StatusList_Status) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{40, 0}
}


func PrintVerificationHeader(imgRef string, co *cosign.CheckOpts, bundleVerified bool) {
	fmt.Fprintf(os.Stderr, "\nVerification for %s --\n", imgRef)
	fmt.Fprintln(os.Stderr, "The following checks were performed on each of these signatures:")
	if co.ClaimVerifier != nil {
		if co.Annotations != nil {
			fmt.Fprintln(os.Stderr, "  - The specified annotations were verified.")
		}
		fmt.Fprintln(os.Stderr, "  - The cosign claims were validated")
	}
	if bundleVerified {
		fmt.Fprintln(os.Stderr, "  - Existence of the claims in the transparency log was verified offline")
	} else if co.RekorClient != nil {
		fmt.Fprintln(os.Stderr, "  - The claims were present in the transparency log")
		fmt.Fprintln(os.Stderr, "  - The signatures were integrated into the transparency log when the certificate was valid")
	}
	if co.SigVerifier != nil {
		fmt.Fprintln(os.Stderr, "  - The signatures were verified against the specified public key")
	}
	fmt.Fprintln(os.Stderr, "  - Any certificates were verified against the Fulcio roots.")
}


func (*WalletLedger) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{42}
}


func (*UserList) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{39}
}


func cmdList(args *docopt.Args, client *tuf.Client) error {
	if _, err := client.Update(); err != nil && !tuf.IsLatestSnapshot(err) {
		return err
	}
	targets, err := client.Targets()
	if err != nil {
		return err
	}
	w := tabwriter.NewWriter(os.Stdout, 1, 2, 2, ' ', 0)
	defer w.Flush()
	fmt.Fprintln(w, "PATH\tSIZE")
	for path, meta := range targets {
		fmt.Fprintf(w, "%s\t%s\n", path, humanize.Bytes(uint64(meta.Length)))
	}
	return nil
}


func (p *HTTPClient) ReadByte() (c byte, err error) {
	return readByte(p.response.Body)
}


func WithRelabeledContainerMounts(mountLabel string) oci.SpecOpts {
	return func(ctx context.Context, client oci.Client, _ *containers.Container, s *runtimespec.Spec) (err error) {
		if mountLabel == "" {
			return nil
		}
		for _, m := range s.Mounts {
			switch m.Destination {
			case etcHosts, etcHostname, resolvConfPath:
				if err := label.Relabel(m.Source, mountLabel, false); err != nil {
					return err
				}
			}
		}
		return nil
	}
}


func TestIsLocalHostname(t *testing.T) {
	tests := []struct {
		hostname  string
		allowlist []string
		want      bool
	}{
		{hostname: "localhost", want: true},       // #00
		{hostname: "127.0.0.1", want: true},       // #01
		{hostname: "::1", want: true},             // #02
		{hostname: "0:0:0:0:0:0:0:1", want: true}, // #03
		{hostname: "fuf.me", want: true},          // #04
		{hostname: "127.0.0.95", want: true},      // #05
		{hostname: "0.0.0.0", want: true},         // #06
		{hostname: "192.168.123.45", want: true},  // #07

		{hostname: "gogs.io", want: false},         // #08
		{hostname: "google.com", want: false},      // #09
		{hostname: "165.232.140.255", want: false}, // #10

		{hostname: "192.168.123.45", allowlist: []string{"10.0.0.17"}, want: true}, // #11
		{hostname: "gogs.local", allowlist: []string{"gogs.local"}, want: false},   // #12
	}
	for _, test := range tests {
		t.Run("", func(t *testing.T) {
			assert.Equal(t, test.want, IsLocalHostname(test.hostname, test.allowlist))
		})
	}
}


func (x *CallApiEndpointRequest) Reset() {
	*x = CallApiEndpointRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[12]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func validateAndUpdateWebhook(c *context.Context, orCtx *orgRepoContext, w *db.Webhook) {
	c.Data["Webhook"] = w

	if c.HasError() {
		c.Success(orCtx.TmplNew)
		return
	}

	field, msg, ok := validateWebhook(c.User, c.Locale, w)
	if !ok {
		c.FormErr(field)
		c.RenderWithErr(msg, orCtx.TmplNew, nil)
		return
	}

	if err := w.UpdateEvent(); err != nil {
		c.Error(err, "update event")
		return
	} else if err := db.UpdateWebhook(w); err != nil {
		c.Error(err, "update webhook")
		return
	}

	c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
	c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
}


func (x *WriteStorageObjectRequest) Reset() {
	*x = WriteStorageObjectRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[44]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func TestRedactURL(t *testing.T) {
	cases := []struct {
		name string
		url  *url.URL
		want string
	}{
		{
			name: "non-blank Password",
			url: &url.URL{
				Scheme: "http",
				Host:   "host.tld",
				Path:   "this:that",
				User:   url.UserPassword("user", "password"),
			},
			want: "http://user:xxxxx@host.tld/this:that",
		},
		{
			name: "blank Password",
			url: &url.URL{
				Scheme: "http",
				Host:   "host.tld",
				Path:   "this:that",
				User:   url.User("user"),
			},
			want: "http://user@host.tld/this:that",
		},
		{
			name: "nil User",
			url: &url.URL{
				Scheme: "http",
				Host:   "host.tld",
				Path:   "this:that",
				User:   url.UserPassword("", "password"),
			},
			want: "http://:xxxxx@host.tld/this:that",
		},
		{
			name: "blank Username, blank Password",
			url: &url.URL{
				Scheme: "http",
				Host:   "host.tld",
				Path:   "this:that",
			},
			want: "http://host.tld/this:that",
		},
		{
			name: "empty URL",
			url:  &url.URL{},
			want: "",
		},
		{
			name: "nil URL",
			url:  nil,
			want: "",
		},
	}

	for _, tt := range cases {
		t := t
		t.Run(tt.name, func(t *testing.T) {
			if g, w := RedactURL(tt.url), tt.want; g != w {
				t.Fatalf("got: %q\nwant: %q", g, w)
			}
		})
	}
}


func (cs chunkState) String() string {
	stateString := ""
	switch cs {
	case readChunkHeader:
		stateString = "readChunkHeader"
	case readChunkTrailer:
		stateString = "readChunkTrailer"
	case readChunk:
		stateString = "readChunk"
	case verifyChunk:
		stateString = "verifyChunk"
	case eofChunk:
		stateString = "eofChunk"

	}
	return stateString
}


func compileRegexps(regexpStrings []string) ([]*regexp.Regexp, error) {
	regexps := []*regexp.Regexp{}
	for _, regexpStr := range regexpStrings {
		r, err := regexp.Compile(regexpStr)
		if err != nil {
			return regexps, err
		}
		regexps = append(regexps, r)
	}
	return regexps, nil
}


func (ctx *cbcAEAD) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
	if len(ciphertext) < ctx.authtagBytes {
		return nil, errors.New("square/go-jose: invalid ciphertext (too short)")
	}

	offset := len(ciphertext) - ctx.authtagBytes
	expectedTag := ctx.computeAuthTag(data, nonce, ciphertext[:offset])
	match := subtle.ConstantTimeCompare(expectedTag, ciphertext[offset:])
	if match != 1 {
		return nil, errors.New("square/go-jose: invalid ciphertext (auth tag mismatch)")
	}

	cbc := cipher.NewCBCDecrypter(ctx.blockCipher, nonce)

	// Make copy of ciphertext buffer, don't want to modify in place
	buffer := append([]byte{}, []byte(ciphertext[:offset])...)

	if len(buffer)%ctx.blockCipher.BlockSize() > 0 {
		return nil, errors.New("square/go-jose: invalid ciphertext (invalid length)")
	}

	cbc.CryptBlocks(buffer, buffer)

	// Remove padding
	plaintext, err := unpadBuffer(buffer, ctx.blockCipher.BlockSize())
	if err != nil {
		return nil, err
	}

	ret, out := resize(dst, len(dst)+len(plaintext))
	copy(out, plaintext)

	return ret, nil
}


func (x *CallApiEndpointResponse) Reset() {
	*x = CallApiEndpointResponse{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[13]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (voteSet *VoteSet) MakeCommit() *Commit {
	if voteSet.signedMsgType != tmproto.PrecommitType {
		panic("Cannot MakeCommit() unless VoteSet.Type is PrecommitType")
	}
	voteSet.mtx.Lock()
	defer voteSet.mtx.Unlock()

	// Make sure we have a 2/3 majority
	if voteSet.maj23 == nil {
		panic("Cannot MakeCommit() unless a blockhash has +2/3")
	}

	// For every validator, get the precommit
	commitSigs := make([]CommitSig, len(voteSet.votes))
	for i, v := range voteSet.votes {
		commitSigs[i] = v.CommitSig()
	}

	return NewCommit(voteSet.GetHeight(), voteSet.GetRound(), *voteSet.maj23, commitSigs)
}


func (x *GetWalletLedgerRequest) Reset() {
	*x = GetWalletLedgerRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[45]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func NewConcatKDF(hash crypto.Hash, z, algID, ptyUInfo, ptyVInfo, supPubInfo, supPrivInfo []byte) io.Reader {
	buffer := make([]byte, len(algID)+len(ptyUInfo)+len(ptyVInfo)+len(supPubInfo)+len(supPrivInfo))
	n := 0
	n += copy(buffer, algID)
	n += copy(buffer[n:], ptyUInfo)
	n += copy(buffer[n:], ptyVInfo)
	n += copy(buffer[n:], supPubInfo)
	copy(buffer[n:], supPrivInfo)

	hasher := hash.New()

	return &concatKDF{
		z:      z,
		info:   buffer,
		hasher: hasher,
		cache:  []byte{},
		i:      1,
	}
}


func setCapabilities(spec *specs.Spec, keepCaps ...string) error {
	currentCaps, err := capability.NewPid2(0)
	if err != nil {
		return errors.Wrapf(err, "error reading capabilities of current process")
	}
	if err := currentCaps.Load(); err != nil {
		return errors.Wrapf(err, "error loading capabilities")
	}
	caps, err := capability.NewPid2(0)
	if err != nil {
		return errors.Wrapf(err, "error reading capabilities of current process")
	}
	capMap := map[capability.CapType][]string{
		capability.BOUNDING:    spec.Process.Capabilities.Bounding,
		capability.EFFECTIVE:   spec.Process.Capabilities.Effective,
		capability.INHERITABLE: spec.Process.Capabilities.Inheritable,
		capability.PERMITTED:   spec.Process.Capabilities.Permitted,
		capability.AMBIENT:     spec.Process.Capabilities.Ambient,
	}
	knownCaps := capability.List()
	noCap := capability.Cap(-1)
	for capType, capList := range capMap {
		for _, capToSet := range capList {
			cap := noCap
			for _, c := range knownCaps {
				if strings.EqualFold("CAP_"+c.String(), capToSet) {
					cap = c
					break
				}
			}
			if cap == noCap {
				return errors.Errorf("error mapping capability %q to a number", capToSet)
			}
			caps.Set(capType, cap)
		}
		for _, capToSet := range keepCaps {
			cap := noCap
			for _, c := range knownCaps {
				if strings.EqualFold("CAP_"+c.String(), capToSet) {
					cap = c
					break
				}
			}
			if cap == noCap {
				return errors.Errorf("error mapping capability %q to a number", capToSet)
			}
			if currentCaps.Get(capType, cap) {
				caps.Set(capType, cap)
			}
		}
	}
	if err = caps.Apply(capability.CAPS | capability.BOUNDS | capability.AMBS); err != nil {
		return errors.Wrapf(err, "error setting capabilities")
	}
	return nil
}


func readUvarint(r io.ByteReader) (x uint64, n int, err error) {
	var s uint
	i := 0
	for {
		b, err := r.ReadByte()
		if err != nil {
			return x, i, err
		}
		i++
		if b < 0x80 {
			if i > 10 || i == 10 && b > 1 {
				return x, i, errOverflowU64
			}
			return x | uint64(b)<<s, i, nil
		}
		x |= uint64(b&0x7f) << s
		s += 7
	}
}


func (*DeleteLeaderboardRecordRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{20}
}


func SanitizePath(path string) string {
	return strings.TrimLeft(path, "./")
}


func IsLatestSnapshot(err error) bool {
	_, ok := err.(ErrLatestSnapshot)
	return ok
}


func (cf *clientsFactory) UpdateNamespaces(ctx context.Context) error {
	clients, err := clientsForClusters(cf.clusters.Get())
	if err != nil {
		cf.log.Error(err, "failed to create clients for", "clusters", cf.clusters.Get())
		return err
	}

	cf.syncCaches()

	wg := sync.WaitGroup{}

	for clusterName, c := range clients {
		wg.Add(1)

		go func(clusterName string, c client.Client) {
			defer wg.Done()

			nsList := &v1.NamespaceList{}

			if err := c.List(ctx, nsList); err != nil {
				cf.log.Error(err, "failed listing namespaces", "cluster", clusterName)
			}

			cf.clustersNamespaces.Set(clusterName, nsList.Items)
		}(clusterName, c)
	}

	wg.Wait()

	return nil
}


func (x *DeleteLeaderboardRecordRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[20]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (c CrossOriginResourceSharing) isOriginAllowed(origin string) bool {
	if len(origin) == 0 {
		return false
	}
	if len(c.AllowedDomains) == 0 {
		return true
	}

	allowed := false
	for _, domain := range c.AllowedDomains {
		if domain == origin {
			allowed = true
			break
		}
	}

	if !allowed {
		if len(c.allowedOriginPatterns) == 0 {
			// compile allowed domains to allowed origin patterns
			allowedOriginRegexps, err := compileRegexps(c.AllowedDomains)
			if err != nil {
				return false
			}
			c.allowedOriginPatterns = allowedOriginRegexps
		}

		for _, pattern := range c.allowedOriginPatterns {
			if allowed = pattern.MatchString(origin); allowed {
				break
			}
		}
	}

	return allowed
}


func (*ConsoleSession) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{15}
}


func (*WriteStorageObjectRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{44}
}


func (c *Client) Update() (data.TargetFiles, error) {
	if err := c.UpdateRoots(); err != nil {
		if _, ok := err.(verify.ErrExpired); ok {
			// For backward compatibility, we wrap the ErrExpired inside
			// ErrDecodeFailed.
			return nil, ErrDecodeFailed{"root.json", err}
		}
		return nil, err
	}

	// Get timestamp.json, extract snapshot.json file meta and save the
	// timestamp.json locally
	timestampJSON, err := c.downloadMetaUnsafe("timestamp.json", defaultTimestampDownloadLimit)
	if err != nil {
		return nil, err
	}
	snapshotMeta, err := c.decodeTimestamp(timestampJSON)
	if err != nil {
		return nil, err
	}
	if err := c.local.SetMeta("timestamp.json", timestampJSON); err != nil {
		return nil, err
	}

	// Get snapshot.json, then extract file metas.
	// root.json meta should not be stored in the snapshot, if it is,
	// the root will be checked, re-downloaded
	snapshotJSON, err := c.downloadMetaFromTimestamp("snapshot.json", snapshotMeta)
	if err != nil {
		return nil, err
	}
	snapshotMetas, err := c.decodeSnapshot(snapshotJSON)
	if err != nil {
		return nil, err
	}

	// Save the snapshot.json
	if err := c.local.SetMeta("snapshot.json", snapshotJSON); err != nil {
		return nil, err
	}

	// If we don't have the targets.json, download it, determine updated
	// targets and save targets.json in local storage
	var updatedTargets data.TargetFiles
	targetsMeta := snapshotMetas["targets.json"]
	if !c.hasMetaFromSnapshot("targets.json", targetsMeta) {
		targetsJSON, err := c.downloadMetaFromSnapshot("targets.json", targetsMeta)
		if err != nil {
			return nil, err
		}
		updatedTargets, err = c.decodeTargets(targetsJSON)
		if err != nil {
			return nil, err
		}
		if err := c.local.SetMeta("targets.json", targetsJSON); err != nil {
			return nil, err
		}
	}

	return updatedTargets, nil
}


func prepareBindMount(m *configs.Mount, rootfs string) error {
	stat, err := os.Stat(m.Source)
	if err != nil {
		// error out if the source of a bind mount does not exist as we will be
		// unable to bind anything to it.
		return err
	}
	// ensure that the destination of the bind mount is resolved of symlinks at mount time because
	// any previous mounts can invalidate the next mount's destination.
	// this can happen when a user specifies mounts within other mounts to cause breakouts or other
	// evil stuff to try to escape the container's rootfs.
	var dest string
	if dest, err = securejoin.SecureJoin(rootfs, m.Destination); err != nil {
		return err
	}
	if err := checkProcMount(rootfs, dest, m.Source); err != nil {
		return err
	}
	if err := createIfNotExists(dest, stat.IsDir()); err != nil {
		return err
	}

	return nil
}


func (x *LeaderboardList) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[24]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
	// Prevent SQL inject.
	opt.Keyword = FilterSQLInject(opt.Keyword)
	if len(opt.Keyword) == 0 {
		return repos, nil
	}
	opt.Keyword = strings.ToLower(opt.Keyword)

	repos = make([]*Repository, 0, opt.Limit)

	// Append conditions.
	sess := x.Limit(opt.Limit)
	if opt.Uid > 0 {
		sess.Where("owner_id=?", opt.Uid)
	}
	if !opt.Private {
		sess.And("is_private=false")
	}
	sess.And("lower_name like '%" + opt.Keyword + "%'").Find(&repos)
	return repos, err
}


func (*UnlinkDeviceRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{35}
}


func canonicalMIMEHeaderKey(a []byte) string {
	upper := true
	for i, c := range a {
		// Canonicalize: first letter upper case
		// and upper case after each dash.
		// (Host, User-Agent, If-Modified-Since).
		// MIME headers are ASCII only, so no Unicode issues.
		if c == ' ' {
			c = '-'
		} else if upper && 'a' <= c && c <= 'z' {
			c -= toLower
		} else if !upper && 'A' <= c && c <= 'Z' {
			c += toLower
		}
		a[i] = c
		upper = c == '-' // for next time
	}
	// The compiler recognizes m[string(byteSlice)] as a special
	// case, so a copy of a's bytes into a new string does not
	// happen in this map lookup:
	if v := commonHeader[string(a)]; v != "" {
		return v
	}
	return string(a)
}


func DeleteCode(id string) {
	delete(memory.Code, id)
}


func (a *APIs) PostLogin(v *PostLoginReq) *kongchuanhujiao.Response {

	if v.Code != account.GetCode(v.ID) || v.Code == "" { // FIXME datahub 鉴权
		return kongchuanhujiao.GenerateErrResp(1, "验证码有误")
	}

	now := time.Now()
	t, err := jwt.NewTokenWithClaims(jwt.SigningMethodES256, jwt.MapClaims{
		"iss": config.GetJWTConf().Iss,
		"sub": v.ID,
		"exp": now.AddDate(0, 1, 0).Unix(),
		"nbf": now.Unix(),
		"iat": now.Unix(),
	}).SignedString(config.GetJWTConf().Key)
	if err != nil {
		logger.Error("生成 JWT Token 失败", zap.Error(err))
		return kongchuanhujiao.DefaultErrResp
	}

	return &kongchuanhujiao.Response{Message: t}
}


func consoleInterceptorFunc(logger *zap.Logger, config Config) func(context.Context, interface{}, *grpc.UnaryServerInfo, grpc.UnaryHandler) (interface{}, error) {


func (x *StatusList_Status) Reset() {
	*x = StatusList_Status{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[49]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *MatchState) Reset() {
	*x = MatchState{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[31]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (*DeleteGroupRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{17}
}


func GetIssues(uid, rid, pid, mid int64, page int, isClosed bool, labelIds, sortType string) ([]Issue, error) {
	sess := x.Limit(20, (page-1)*20)

	if rid > 0 {
		sess.Where("repo_id=?", rid).And("is_closed=?", isClosed)
	} else {
		sess.Where("is_closed=?", isClosed)
	}

	if uid > 0 {
		sess.And("assignee_id=?", uid)
	} else if pid > 0 {
		sess.And("poster_id=?", pid)
	}

	if mid > 0 {
		sess.And("milestone_id=?", mid)
	}

	if len(labelIds) > 0 {
		for _, label := range strings.Split(labelIds, ",") {
			sess.And("label_ids like '%$" + label + "|%'")
		}
	}

	switch sortType {
	case "oldest":
		sess.Asc("created")
	case "recentupdate":
		sess.Desc("updated")
	case "leastupdate":
		sess.Asc("updated")
	case "mostcomment":
		sess.Desc("num_comments")
	case "leastcomment":
		sess.Asc("num_comments")
	case "priority":
		sess.Desc("priority")
	default:
		sess.Desc("created")
	}

	var issues []Issue
	err := sess.Find(&issues)
	return issues, err
}


func (*GetWalletLedgerRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{45}
}


func (*CallApiEndpointResponse) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{13}
}


func (cr *s3ChunkedReader) readS3ChunkHeader() {
	// Read the first chunk line until CRLF.
	var hexChunkSize, hexChunkSignature []byte
	hexChunkSize, hexChunkSignature, cr.err = readChunkLine(cr.reader)
	if cr.err != nil {
		return
	}
	// <hex>;token=value - converts the hex into its uint64 form.
	cr.n, cr.err = parseHexUint(hexChunkSize)
	if cr.err != nil {
		return
	}
	if cr.n == 0 {
		cr.err = io.EOF
	}
	// Save the incoming chunk signature.
	cr.chunkSignature = string(hexChunkSignature)
}


func isLoopbackURI(requested *url.URL, registeredURI string) bool {
	registered, err := url.Parse(registeredURI)
	if err != nil {
		return false
	}

	if registered.Scheme != "http" || !isLoopbackAddress(registered.Host) {
		return false
	}

	if requested.Scheme == "http" && isLoopbackAddress(requested.Host) && registered.Path == requested.Path {
		return true
	}

	return false
}


func (*UserList_User) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{39, 0}
}


func (x *UpdateGroupRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[37]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


		private HandshakeMessage createClientHandshakeMessage(
			HandshakeType type, byte[] buffer)
		{
			switch (type)
			{
				case HandshakeType.ClientHello:
					return new TlsClientHello(this.context, buffer);

				case HandshakeType.Certificate:
					return new TlsClientCertificate(this.context, buffer);

				case HandshakeType.ClientKeyExchange:
					return new TlsClientKeyExchange(this.context, buffer);

				case HandshakeType.CertificateVerify:
					return new TlsClientCertificateVerify(this.context, buffer);

				case HandshakeType.Finished:
					return new TlsClientFinished(this.context, buffer);

				default:
					throw new TlsException(
						AlertDescription.UnexpectedMessage,
						String.Format(CultureInfo.CurrentUICulture,
							"Unknown server handshake message received ({0})",
							type.ToString()));
			}
		}


	return utils.WithProcfd(rootfs, m.Destination, func(procfd string) error {
		return mount(m.Source, m.Destination, procfd, m.Device, uintptr(m.Flags|unix.MS_REMOUNT), "")
	})


func (x *MatchState) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[31]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func RedactURL(u *url.URL) string {
	if u == nil {
		return ""
	}

	ru := *u
	if _, has := ru.User.Password(); has {
		ru.User = url.UserPassword(ru.User.Username(), "xxxxx")
	}
	return ru.String()
}


func fixTransferEncoding(requestMethod string, header Header) ([]string, error) {
	raw, present := header["Transfer-Encoding"]
	if !present {
		return nil, nil
	}

	delete(header, "Transfer-Encoding")

	encodings := strings.Split(raw[0], ",")
	te := make([]string, 0, len(encodings))
	// TODO: Even though we only support "identity" and "chunked"
	// encodings, the loop below is designed with foresight. One
	// invariant that must be maintained is that, if present,
	// chunked encoding must always come first.
	for _, encoding := range encodings {
		encoding = strings.ToLower(strings.TrimSpace(encoding))
		// "identity" encoding is not recorded
		if encoding == "identity" {
			break
		}
		if encoding != "chunked" {
			return nil, &badStringError{"unsupported transfer encoding", encoding}
		}
		te = te[0 : len(te)+1]
		te[len(te)-1] = encoding
	}
	if len(te) > 1 {
		return nil, &badStringError{"too many transfer encodings", strings.Join(te, ",")}
	}
	if len(te) > 0 {
		// Chunked encoding trumps Content-Length. See RFC 2616
		// Section 4.4. Currently len(te) > 0 implies chunked
		// encoding.
		delete(header, "Content-Length")
		return te, nil
	}

	return nil, nil
}


func (*ListSubscriptionsRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{29}
}


func (x *DeleteFriendRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[16]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (x *Config_Warning) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[46]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


		([ key, value ]) => ({ [key]: exec.bind(null, `git show -s --format=%${value}`) }),
	),


    set escape_for_html(arg:boolean)
    {
        this._escape_for_html = arg;
    }


    constructor()
    {
        // All construction occurs here
        this.setup_palettes();
        this._use_classes = false;
        this._escape_for_html = true;

        this.bold = false;
        this.fg = this.bg = null;

        this._buffer = '';

        this._url_whitelist = { 'http':1, 'https':1 };
    }


        function sendResponse(response1: Response) {
            try {
                assert(response1 instanceof ResponseClass);
                if (message.session) {
                    const counterName = ResponseClass.name.replace("Response", "");
                    message.session.incrementRequestTotalCounter(counterName);
                }
                return channel.send_response("MSG", response1, message);
            } catch (err) {
                warningLog(err);
                // istanbul ignore next
                if (err instanceof Error) {
                    // istanbul ignore next
                    errorLog(
                        "Internal error in issuing response\nplease contact support@sterfive.com",
                        message.request.toString(),
                        "\n",
                        response1.toString()
                    );
                }
                // istanbul ignore next
                throw err;
            }
        }


    userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
    totalHours,
  }


export function createCatalogWriteAction() {
  return createTemplateAction<{ name?: string; entity: Entity }>({
    id: 'catalog:write',
    description: 'Writes the catalog-info.yaml for your template',
    schema: {
      input: {
        type: 'object',
        properties: {
          entity: {
            title: 'Entity info to write catalog-info.yaml',
            description:
              'You can provide the same values used in the Entity schema.',
            type: 'object',
          },
        },
      },
    },
    async handler(ctx) {
      ctx.logStream.write(`Writing catalog-info.yaml`);
      const { entity } = ctx.input;

      await fs.writeFile(
        resolvePath(ctx.workspacePath, 'catalog-info.yaml'),
        yaml.stringify(entity),
      );
    },
  });
}


  [_sanitize](svg) {
    return svg.removeAttr('onload');
  }


    const matrix = node.getScreenCTM();
    if (res && matrix) {
      const [x, y, content] = res;
      const t = tooltip();
      t.style.opacity = "1";
      t.innerHTML = content;
      t.style.left = `${window.scrollX + x + matrix.e}px`;
      t.style.top = `${window.scrollY + y + matrix.f - 15}px`;
    } else {
      hide();
    }
  }
  node.addEventListener("mousemove", mousemove);
  node.addEventListener("mouseleave", hide);

  return {
    destroy: hide,
  };
}


            text += ` / ${c.amount(a.budget, a.currency)}`;
          }
          text += "<br>";
        });


export function escape_attribute_value(value) {
	return typeof value === 'string' ? escape(value, true) : value;
}


userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,


                response.responseHeader.serviceResult.should.eql(StatusCodes.BadDiscoveryUrlMissing);
            }

            await send_registered_server_request(discoveryServerEndpointUrl, request, check_response);
        });