Exemple #1
0
func newCacheService() {
	CacheAdapter = Cfg.MustValue("cache", "ADAPTER", "memory")
	if EnableRedis {
		log.Info("Redis Enabled")
	}
	if EnableMemcache {
		log.Info("Memcache Enabled")
	}

	switch CacheAdapter {
	case "memory":
		CacheConfig = fmt.Sprintf(`{"interval":%d}`, Cfg.MustInt("cache", "INTERVAL", 60))
	case "redis", "memcache":
		CacheConfig = fmt.Sprintf(`{"conn":"%s"}`, Cfg.MustValue("cache", "HOST"))
	default:
		qlog.Fatalf("Unknown cache adapter: %s\n", CacheAdapter)
	}

	var err error
	Cache, err = cache.NewCache(CacheAdapter, CacheConfig)
	if err != nil {
		qlog.Fatalf("Init cache system failed, adapter: %s, config: %s, %v\n",
			CacheAdapter, CacheConfig, err)
	}

	log.Info("Cache Service Enabled")
}
Exemple #2
0
func main() {
	configfn := "nameserver.conf"
	data, err := ioutil.ReadFile(configfn)
	if err != nil {
		log.Fatalf("server: cannot load configuration file[%s] (%v)", configfn, err)
	}

	var conf config.Server
	if _, err := toml.Decode(string(data), &conf); err != nil {
		log.Fatalf("server: configuration file[%s] is not valid (%v)", configfn, err)
	}
	server := NewServer()
	for i, v := range conf.Disks {
		log.Infof("Adding %v to disks", v)
		server.registeredDisks = append(server.registeredDisks, &conf.Disks[i])
	}
	log.Infof("server: starting server...")

	lis, err := net.Listen("tcp", net.JoinHostPort(conf.Bind, conf.Port))

	if err != nil {
		log.Fatalf("server: failed to listen: %v", err)
	}

	log.Infof("server: listening on %s", net.JoinHostPort(conf.Bind, conf.Port))

	s := grpc.NewServer()
	pb.RegisterNameServer(s, server)
	log.Infof("server: ready to serve clients")
	s.Serve(lis)
}
Exemple #3
0
Fichier : repo.go Projet : j20/gogs
func LoadRepoConfig() {
	workDir, err := base.ExecDir()
	if err != nil {
		qlog.Fatalf("Fail to get work directory: %s\n", err)
	}

	// Load .gitignore and license files.
	types := []string{"gitignore", "license"}
	typeFiles := make([][]string, 2)
	for i, t := range types {
		cfgPath := filepath.Join(workDir, "conf", t)
		files, err := com.StatDir(cfgPath)
		if err != nil {
			qlog.Fatalf("Fail to get default %s files: %v\n", t, err)
		}
		cfgPath = filepath.Join(workDir, "custom/conf/gitignore")
		if com.IsDir(cfgPath) {
			customFiles, err := com.StatDir(cfgPath)
			if err != nil {
				qlog.Fatalf("Fail to get custom %s files: %v\n", t, err)
			}

			for _, f := range customFiles {
				if !com.IsSliceContainsStr(files, f) {
					files = append(files, f)
				}
			}
		}
		typeFiles[i] = files
	}

	LanguageIgns = typeFiles[0]
	Licenses = typeFiles[1]
}
Exemple #4
0
Fichier : conf.go Projet : j20/gogs
func newLogService() {
	log.Info("%s %s", AppName, AppVer)

	// Get and check log mode.
	LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",")
	LogConfigs = make([]string, len(LogModes))
	for i, mode := range LogModes {
		mode = strings.TrimSpace(mode)
		modeSec := "log." + mode
		if _, err := Cfg.GetSection(modeSec); err != nil {
			qlog.Fatalf("Unknown log mode: %s\n", mode)
		}

		// Log level.
		levelName := Cfg.MustValue("log."+mode, "LEVEL", "Trace")
		level, ok := logLevels[levelName]
		if !ok {
			qlog.Fatalf("Unknown log level: %s\n", levelName)
		}

		// Generate log configuration.
		switch mode {
		case "console":
			LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
		case "file":
			logPath := Cfg.MustValue(modeSec, "FILE_NAME", "log/gogs.log")
			os.MkdirAll(path.Dir(logPath), os.ModePerm)
			LogConfigs[i] = fmt.Sprintf(
				`{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
				logPath,
				Cfg.MustBool(modeSec, "LOG_ROTATE", true),
				Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
				1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
				Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
				Cfg.MustInt(modeSec, "MAX_DAYS", 7))
		case "conn":
			LogConfigs[i] = fmt.Sprintf(`{"level":"%s","reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
				Cfg.MustBool(modeSec, "RECONNECT_ON_MSG", false),
				Cfg.MustBool(modeSec, "RECONNECT", false),
				Cfg.MustValue(modeSec, "PROTOCOL", "tcp"),
				Cfg.MustValue(modeSec, "ADDR", ":7020"))
		case "smtp":
			LogConfigs[i] = fmt.Sprintf(`{"level":"%s","username":"******","password":"******","host":"%s","sendTos":"%s","subject":"%s"}`, level,
				Cfg.MustValue(modeSec, "USER", "*****@*****.**"),
				Cfg.MustValue(modeSec, "PASSWD", "******"),
				Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
				Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
				Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
		case "database":
			LogConfigs[i] = fmt.Sprintf(`{"level":"%s","driver":"%s","conn":"%s"}`, level,
				Cfg.MustValue(modeSec, "Driver"),
				Cfg.MustValue(modeSec, "CONN"))
		}

		log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, LogConfigs[i])
		log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
	}
}
Exemple #5
0
func main() {
	configfn := flag.String("config", "default.conf", "location of configuration file")
	flag.Parse()

	data, err := ioutil.ReadFile(*configfn)
	if err != nil {
		log.Fatalf("server: cannot load configuration file[%s] (%v)", *configfn, err)
	}

	var conf config.Server
	if _, err := toml.Decode(string(data), &conf); err != nil {
		log.Fatalf("server: configuration file[%s] is not valid (%v)", *configfn, err)
	}

	// default is that cfs is bootstrapped using docker
	cname, err := detectDockerContainer()
	if err != nil {
		log.Printf("server: failed to detect docker container (%v)", err)
	} else {
		stats.SetContainerName(cname)
		log.Printf("server: detect docker container %q", cname)
	}

	log.Infof("server: starting server...")

	lis, err := net.Listen("tcp", net.JoinHostPort(conf.Bind, conf.Port))
	if err != nil {
		log.Fatalf("server: failed to listen: %v", err)
	}

	log.Infof("server: listening on %s", net.JoinHostPort(conf.Bind, conf.Port))

	cfs := NewServer()

	for _, d := range conf.Disks {
		err = cfs.AddDisk(d.Name, d.Root)
		if err != nil {
			log.Fatalf("server: failed to add disk (%v)", err)
		}
	}

	// 0x1234 is the client ID for cfsctl, and its quota is 10 req/sec.
	enforce.SetQuota(0x1234, 10)

	// TODO report with influxSinker
	stats.Report(nil, 3*time.Second)

	s := grpc.NewServer()
	pb.RegisterCfsServer(s, cfs)
	pb.RegisterStatsServer(s, stats.Server())
	log.Infof("server: ready to serve clients")
	s.Serve(lis)
}
Exemple #6
0
func init() {
	var err error

	if appPath, err = exePath(); err != nil {
		qlog.Fatalf("publickey.init(fail to get app path): %v\n", err)
	}

	// Determine and create .ssh path.
	SshPath = filepath.Join(homeDir(), ".ssh")
	if err = os.MkdirAll(SshPath, os.ModePerm); err != nil {
		qlog.Fatalf("publickey.init(fail to create SshPath(%s)): %v\n", SshPath, err)
	}
}
Exemple #7
0
Fichier : repo.go Projet : j20/gogs
func NewRepoContext() {
	zip.Verbose = false

	// Check if server has basic git setting.
	stdout, stderr, err := com.ExecCmd("git", "config", "--get", "user.name")
	if strings.Contains(stderr, "fatal:") {
		qlog.Fatalf("repo.NewRepoContext(fail to get git user.name): %s", stderr)
	} else if err != nil || len(strings.TrimSpace(stdout)) == 0 {
		if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.email", "*****@*****.**"); err != nil {
			qlog.Fatalf("repo.NewRepoContext(fail to set git user.email): %s", stderr)
		} else if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
			qlog.Fatalf("repo.NewRepoContext(fail to set git user.name): %s", stderr)
		}
	}
}
Exemple #8
0
func newSessionService() {
	SessionProvider = Cfg.MustValue("session", "PROVIDER", "memory")

	SessionConfig = new(session.Config)
	SessionConfig.ProviderConfig = Cfg.MustValue("session", "PROVIDER_CONFIG")
	SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits")
	SessionConfig.CookieSecure = Cfg.MustBool("session", "COOKIE_SECURE")
	SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
	SessionConfig.GcIntervalTime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
	SessionConfig.SessionLifeTime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
	SessionConfig.SessionIDHashFunc = Cfg.MustValue("session", "SESSION_ID_HASHFUNC", "sha1")
	SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY")

	if SessionProvider == "file" {
		os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
	}

	var err error
	SessionManager, err = session.NewManager(SessionProvider, *SessionConfig)
	if err != nil {
		qlog.Fatalf("Init session system failed, provider: %s, %v\n",
			SessionProvider, err)
	}

	log.Info("Session Service Enabled")
}
Exemple #9
0
func (s *httpSender) Send(events []Event) error {
	if len(events) == 0 {
		return nil
	} else if len(events) > MaxBatchSize {
		return ErrTooManyEvents
	}

	pr, pw := io.Pipe()
	go func() {
		err := json.NewEncoder(pw).Encode(events)
		pw.CloseWithError(err)
	}()
	defer pr.Close()

	req, err := http.NewRequest("POST", s.remote, pr)
	if err != nil {
		log.Fatalf("http.NewRequest %s failed - %v", s.remote, err)
	}

	req.Header.Add("Content-type", "application/json; charset=UTF-8")

	resp, err := s.http.Do(req)
	if err != nil {
		return &httpErr{err, 0}
	} else if resp.StatusCode != 200 {
		return &httpErr{nil, resp.StatusCode}
	}
	defer resp.Body.Close()

	return nil
}
Exemple #10
0
func setUpClient() *client.Client {
	// Set up a connection to the server.
	c, err := client.New(address)
	if err != nil {
		log.Fatalf("Cannot create cfs client: %v", err)
	}
	return c
}
Exemple #11
0
func actionStartServer(c *cli.Context) error {
	suv, hdlr, err := newSupervisorHandler()
	if err != nil {
		log.Fatal(err)
	}
	auth := cfg.Server.HttpAuth
	if auth.Enabled {
		hdlr = httpauth.SimpleBasicAuth(auth.User, auth.Password)(hdlr)
	}
	http.Handle("/", hdlr)

	addr := cfg.Server.Addr
	if c.Bool("foreground") {
		suv.AutoStartPrograms()
		log.Printf("server listen on %v", addr)
		log.Fatal(http.ListenAndServe(addr, nil))
	} else {
		if checkServerStatus() == nil {
			fmt.Println("server is already running")
			return nil
		}
		logPath := filepath.Join(defaultConfigDir, "gosuv.log")
		logFd, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
		if err != nil {
			log.Fatalf("create file %s failed: %v", logPath, err)
		}
		cmd := exec.Command(os.Args[0], "start-server", "-f")
		cmd.Stdout = logFd
		cmd.Stderr = logFd
		err = cmd.Start()
		if err != nil {
			log.Fatal(err)
		}
		select {
		case err = <-GoFunc(cmd.Wait):
			log.Fatalf("server started failed, %v", err)
		case <-time.After(200 * time.Millisecond):
			showAddr := addr
			if strings.HasPrefix(addr, ":") {
				showAddr = "0.0.0.0" + addr
			}
			fmt.Printf("server started, listening on %s\n", showAddr)
		}
	}
	return nil
}
Exemple #12
0
func handleWrite(ctx context.Context, c *client.Client) error {
	n, err := c.Write(ctx, writeName, writeOffset, []byte(writeData), writeAppend)
	if err != nil {
		log.Fatalf("Write err (%v)", err)
	}
	log.Infof("%d bytes written to %s at offset %d", n, writeName, writeOffset)

	return nil
}
Exemple #13
0
func handleRename(ctx context.Context, c *client.Client) error {
	err := c.Rename(ctx, renameOld, renameNew)
	if err != nil {
		log.Fatalf("Rename err (%v)", err)
	}
	log.Infof("rename %s into %s", renameOld, renameNew)

	return nil
}
Exemple #14
0
func handleMkdir(ctx context.Context, c *client.Client) error {
	err := c.Mkdir(ctx, mkdirName, mkdirAll)
	if err != nil {
		log.Fatalf("Mkdir err (%v)", err)
	}

	fmt.Printf("mkdir %s succeeded\n", mkdirName)
	return nil
}
Exemple #15
0
func handleRead(ctx context.Context, c *client.Client) error {
	_, data, _, err := c.Read(ctx, readName, readOffset, readLen, readExpChecksum)
	if err != nil {
		log.Fatalf("Read err (%v)", err)
	}
	log.Info(string(data))

	return nil
}
Exemple #16
0
func handleRemove(ctx context.Context, c *client.Client) error {
	err := c.Remove(ctx, removeName, removeAll)
	if err != nil {
		log.Fatalf("Read err (%v)", err)
	}
	log.Info("remove succeeded")

	return nil
}
Exemple #17
0
func (f *FSM) AddHandler(state FSMState, event FSMEvent, hdlr FSMHandler) *FSM {
	_, ok := f.handlers[state]
	if !ok {
		f.handlers[state] = make(map[FSMEvent]FSMHandler)
	}
	if _, ok = f.handlers[state][event]; ok {
		log.Fatalf("set twice for state(%s) event(%s)", state, event)
	}
	f.handlers[state][event] = hdlr
	return f
}
Exemple #18
0
func handleReadDir(ctx context.Context, c *client.Client) error {
	fInfos, err := c.ReadDir(ctx, readDirName)
	if err != nil {
		log.Fatalf("ReadDir err (%v)", err)
	}

	for _, stats := range fInfos {
		fmt.Printf("%s: %d %t\n", stats.Name, stats.TotalSize, stats.IsDir == true)
	}

	return nil
}
Exemple #19
0
func NewConfigContext() {
	workDir, err := ExecDir()
	if err != nil {
		qlog.Fatalf("Fail to get work directory: %s\n", err)
	}

	cfgPath := filepath.Join(workDir, "conf/app.ini")
	Cfg, err = goconfig.LoadConfigFile(cfgPath)
	if err != nil {
		qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err)
	}
	Cfg.BlockMode = false

	cfgPaths := []string{os.Getenv("GOGS_CONFIG"), filepath.Join(workDir, "custom/conf/app.ini")}
	for _, cfgPath := range cfgPaths {
		if com.IsFile(cfgPath) {
			if err = Cfg.AppendFiles(cfgPath); err != nil {
				qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err)
			}
		}
	}

	AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service")
	AppLogo = Cfg.MustValue("", "APP_LOGO", "img/favicon.png")
	AppUrl = Cfg.MustValue("server", "ROOT_URL")
	Domain = Cfg.MustValue("server", "DOMAIN")
	OfflineMode = Cfg.MustBool("server", "OFFLINE_MODE", false)
	DisableRouterLog = Cfg.MustBool("server", "DISABLE_ROUTER_LOG", false)
	SecretKey = Cfg.MustValue("security", "SECRET_KEY")

	InstallLock = Cfg.MustBool("security", "INSTALL_LOCK", false)

	RunUser = Cfg.MustValue("", "RUN_USER")
	curUser := os.Getenv("USER")
	if len(curUser) == 0 {
		curUser = os.Getenv("USERNAME")
	}
	// Does not check run user when the install lock is off.
	if InstallLock && RunUser != curUser {
		qlog.Fatalf("Expect user(%s) but current user is: %s\n", RunUser, curUser)
	}

	LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS")
	CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME")
	CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME")

	PictureService = Cfg.MustValue("picture", "SERVICE")
	DisableGravatar = Cfg.MustBool("picture", "DISABLE_GRAVATAR", false)

	// Determine and create root git reposiroty path.
	homeDir, err := com.HomeDir()
	if err != nil {
		qlog.Fatalf("Fail to get home directory): %v\n", err)
	}
	RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories"))
	if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
		qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err)
	}
	ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash")
}
Exemple #20
0
func NewConfigContext() {
	//var err error
	workDir, err := ExecDir()
	if err != nil {
		qlog.Fatalf("Fail to get work directory: %s\n", err)
	}

	cfgPath := filepath.Join(workDir, "conf/app.ini")
	Cfg, err = goconfig.LoadConfigFile(cfgPath)
	if err != nil {
		qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err)
	}
	Cfg.BlockMode = false

	cfgPath = filepath.Join(workDir, "custom/conf/app.ini")
	if com.IsFile(cfgPath) {
		if err = Cfg.AppendFiles(cfgPath); err != nil {
			qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err)
		}
	}

	AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service")
	AppLogo = Cfg.MustValue("", "APP_LOGO", "img/favicon.png")
	AppUrl = Cfg.MustValue("server", "ROOT_URL")
	Domain = Cfg.MustValue("server", "DOMAIN")
	SecretKey = Cfg.MustValue("security", "SECRET_KEY")

	InstallLock = Cfg.MustBool("security", "INSTALL_LOCK", false)

	RunUser = Cfg.MustValue("", "RUN_USER")
	curUser := os.Getenv("USER")
	if len(curUser) == 0 {
		curUser = os.Getenv("USERNAME")
	}
	// Does not check run user when the install lock is off.
	if InstallLock && RunUser != curUser {
		qlog.Fatalf("Expect user(%s) but current user is: %s\n", RunUser, curUser)
	}

	LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS")
	CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME")
	CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME")

	// load LDAP authentication configuration if present
	LdapAuth = Cfg.MustBool("security", "LDAP_AUTH", false)
	if LdapAuth {
		log.Debug("LDAP AUTHENTICATION activated")
		nbsrc := 0
		for _, v := range Cfg.GetSectionList() {
			if matched, _ := regexp.MatchString("(?i)^LDAPSOURCE.*", v); matched {
				ldapname := Cfg.MustValue(v, "name", v)
				ldaphost := Cfg.MustValue(v, "host")
				ldapport := Cfg.MustInt(v, "port", 389)
				ldapbasedn := Cfg.MustValue(v, "basedn", "dc=*,dc=*")
				ldapattribute := Cfg.MustValue(v, "attribute", "mail")
				ldapfilter := Cfg.MustValue(v, "filter", "(*)")
				ldapmsadsaformat := Cfg.MustValue(v, "MSADSAFORMAT", "%s")
				ldap.AddSource(ldapname, ldaphost, ldapport, ldapbasedn, ldapattribute, ldapfilter, ldapmsadsaformat)
				nbsrc += 1
				log.Debug("%s added as LDAP source", ldapname)
			}
		}
		if nbsrc == 0 {
			log.Debug("No valide LDAP found, LDAP AUTHENTICATION NOT activated")
			LdapAuth = false
		}
	} else {
		log.Debug("LDAP AUTHENTICATION NOT activated")
	}

	PictureService = Cfg.MustValue("picture", "SERVICE")

	// Determine and create root git reposiroty path.
	homeDir, err := com.HomeDir()
	if err != nil {
		qlog.Fatalf("Fail to get home directory): %v\n", err)
	}
	RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories"))
	if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
		qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err)
	}
	ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash")
}
Exemple #21
0
func runServ(k *cli.Context) {
	execDir, _ := base.ExecDir()
	newLogger(execDir)

	base.NewConfigContext()
	models.LoadModelsConfig()

	if models.UseSQLite3 {
		os.Chdir(execDir)
	}

	models.SetEngine()

	keys := strings.Split(os.Args[2], "-")
	if len(keys) != 2 {
		println("auth file format error")
		qlog.Fatal("auth file format error")
	}

	keyId, err := strconv.ParseInt(keys[1], 10, 64)
	if err != nil {
		println("auth file format error")
		qlog.Fatal("auth file format error", err)
	}
	user, err := models.GetUserByKeyId(keyId)
	if err != nil {
		println("You have no right to access")
		qlog.Fatalf("SSH visit error: %v", err)
	}

	cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
	if cmd == "" {
		println("Hi", user.Name, "! You've successfully authenticated, but Gogs does not provide shell access.")
		return
	}

	verb, args := parseCmd(cmd)
	repoPath := strings.Trim(args, "'")
	rr := strings.SplitN(repoPath, "/", 2)
	if len(rr) != 2 {
		println("Unavailable repository", args)
		qlog.Fatalf("Unavailable repository %v", args)
	}
	repoUserName := rr[0]
	repoName := strings.TrimSuffix(rr[1], ".git")

	isWrite := In(verb, COMMANDS_WRITE)
	isRead := In(verb, COMMANDS_READONLY)

	repoUser, err := models.GetUserByName(repoUserName)
	if err != nil {
		println("You have no right to access")
		qlog.Fatal("Get user failed", err)
	}

	// access check
	switch {
	case isWrite:
		has, err := models.HasAccess(user.LowerName, path.Join(repoUserName, repoName), models.AU_WRITABLE)
		if err != nil {
			println("Internal error:", err)
			qlog.Fatal(err)
		} else if !has {
			println("You have no right to write this repository")
			qlog.Fatalf("User %s has no right to write repository %s", user.Name, repoPath)
		}
	case isRead:
		repo, err := models.GetRepositoryByName(repoUser.Id, repoName)
		if err != nil {
			println("Get repository error:", err)
			qlog.Fatal("Get repository error: " + err.Error())
		}

		if !repo.IsPrivate {
			break
		}

		has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_READABLE)
		if err != nil {
			println("Internal error")
			qlog.Fatal(err)
		}
		if !has {
			has, err = models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_WRITABLE)
			if err != nil {
				println("Internal error")
				qlog.Fatal(err)
			}
		}
		if !has {
			println("You have no right to access this repository")
			qlog.Fatal("You have no right to access this repository")
		}
	default:
		println("Unknown command")
		qlog.Fatal("Unknown command")
	}

	models.SetRepoEnvs(user.Id, user.Name, repoName, repoUserName)

	gitcmd := exec.Command(verb, repoPath)
	gitcmd.Dir = base.RepoRootPath
	gitcmd.Stdout = os.Stdout
	gitcmd.Stdin = os.Stdin
	gitcmd.Stderr = os.Stderr

	if err = gitcmd.Run(); err != nil {
		println("execute command error:", err.Error())
		qlog.Fatal("execute command error: " + err.Error())
	}

	//refName := os.Getenv("refName")
	//oldCommitId := os.Getenv("oldCommitId")
	//newCommitId := os.Getenv("newCommitId")

	//qlog.Error("get envs:", refName, oldCommitId, newCommitId)

	// update
	//models.Update(refName, oldCommitId, newCommitId, repoUserName, repoName, user.Id)
}
Exemple #22
0
func runWeb(*cli.Context) {
	routers.GlobalInit()

	m := newMartini()

	// Middlewares.
	m.Use(middleware.Renderer(middleware.RenderOptions{
		Funcs:      []template.FuncMap{base.TemplateFuncs},
		IndentJSON: true,
	}))
	m.Use(middleware.InitContext())

	reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
	ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: base.Service.RequireSignInView})
	ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})

	reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})

	bindIgnErr := binding.BindIgnErr

	// Routers.
	m.Get("/", ignSignIn, routers.Home)
	m.Get("/install", bindIgnErr(auth.InstallForm{}), routers.Install)
	m.Post("/install", bindIgnErr(auth.InstallForm{}), routers.InstallPost)
	m.Get("/issues", reqSignIn, user.Issues)
	m.Get("/pulls", reqSignIn, user.Pulls)
	m.Get("/stars", reqSignIn, user.Stars)
	m.Get("/help", routers.Help)

	m.Group("/api/v1", func(r martini.Router) {
		// Miscellaneous.
		r.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
		r.Post("/markdown/raw", v1.MarkdownRaw)

		// Users.
		r.Get("/users/search", v1.SearchUser)

		r.Any("**", func(ctx *middleware.Context) {
			ctx.JSON(404, &base.ApiJsonErr{"Not Found", v1.DOC_URL})
		})
	})

	avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
	os.MkdirAll("public/img/avatar/", os.ModePerm)
	m.Get("/avatar/:hash", avt.ServeHTTP)

	m.Group("/user", func(r martini.Router) {
		r.Get("/login", user.SignIn)
		r.Post("/login", bindIgnErr(auth.LogInForm{}), user.SignInPost)
		r.Get("/login/:name", user.SocialSignIn)
		r.Get("/sign_up", user.SignUp)
		r.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
		r.Get("/reset_password", user.ResetPasswd)
		r.Post("/reset_password", user.ResetPasswdPost)
	}, reqSignOut)
	m.Group("/user", func(r martini.Router) {
		r.Get("/delete", user.Delete)
		r.Post("/delete", user.DeletePost)
		r.Get("/settings", user.Setting)
		r.Post("/settings", bindIgnErr(auth.UpdateProfileForm{}), user.SettingPost)
	}, reqSignIn)
	m.Group("/user", func(r martini.Router) {
		r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
		r.Any("/activate", user.Activate)
		r.Get("/email2user", user.Email2User)
		r.Get("/forget_password", user.ForgotPasswd)
		r.Post("/forget_password", user.ForgotPasswdPost)
		r.Get("/logout", user.SignOut)
	})
	m.Group("/user/settings", func(r martini.Router) {
		r.Get("/social", user.SettingSocial)
		r.Get("/password", user.SettingPassword)
		r.Post("/password", bindIgnErr(auth.UpdatePasswdForm{}), user.SettingPasswordPost)
		r.Any("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingSSHKeys)
		r.Get("/notification", user.SettingNotification)
		r.Get("/security", user.SettingSecurity)
	}, reqSignIn)

	m.Get("/user/:username", ignSignIn, user.Profile)

	m.Group("/repo", func(r martini.Router) {
		r.Get("/create", repo.Create)
		r.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
		r.Get("/migrate", repo.Migrate)
		r.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
	}, reqSignIn)

	adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})

	m.Get("/admin", adminReq, admin.Dashboard)
	m.Group("/admin", func(r martini.Router) {
		r.Get("/users", admin.Users)
		r.Get("/repos", admin.Repositories)
		r.Get("/config", admin.Config)
		r.Get("/auths", admin.Auths)
	}, adminReq)
	m.Group("/admin/users", func(r martini.Router) {
		r.Get("/new", admin.NewUser)
		r.Post("/new", bindIgnErr(auth.RegisterForm{}), admin.NewUserPost)
		r.Get("/:userid", admin.EditUser)
		r.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
		r.Get("/:userid/delete", admin.DeleteUser)
	}, adminReq)

	m.Group("/admin/auths", func(r martini.Router) {
		r.Get("/new", admin.NewAuthSource)
		r.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
		r.Get("/:authid", admin.EditAuthSource)
		r.Post("/:authid", bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
		r.Get("/:authid/delete", admin.DeleteAuthSource)
	}, adminReq)

	if martini.Env == martini.Dev {
		m.Get("/template/**", dev.TemplatePreview)
	}

	reqOwner := middleware.RequireOwner()

	m.Group("/:username/:reponame", func(r martini.Router) {
		r.Get("/settings", repo.Setting)
		r.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingPost)
		r.Get("/settings/collaboration", repo.Collaboration)
		r.Post("/settings/collaboration", repo.CollaborationPost)
		r.Get("/settings/hooks", repo.WebHooks)
		r.Get("/settings/hooks/add", repo.WebHooksAdd)
		r.Post("/settings/hooks/add", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksAddPost)
		r.Get("/settings/hooks/:id", repo.WebHooksEdit)
		r.Post("/settings/hooks/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
	}, reqSignIn, middleware.RepoAssignment(true), reqOwner)

	m.Group("/:username/:reponame", func(r martini.Router) {
		r.Get("/action/:action", repo.Action)
		r.Get("/issues/new", repo.CreateIssue)
		r.Post("/issues/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost)
		r.Post("/issues/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
		r.Get("/issues/milestones", repo.Milestones)
		r.Get("/issues/milestones/new", repo.NewMilestones)
		r.Post("/comment/:action", repo.Comment)
		r.Get("/releases/new", repo.ReleasesNew)
	}, reqSignIn, middleware.RepoAssignment(true))

	m.Group("/:username/:reponame", func(r martini.Router) {
		r.Post("/releases/new", bindIgnErr(auth.NewReleaseForm{}), repo.ReleasesNewPost)
	}, reqSignIn, middleware.RepoAssignment(true, true))

	m.Group("/:username/:reponame", func(r martini.Router) {
		r.Get("/issues", repo.Issues)
		r.Get("/issues/:index", repo.ViewIssue)
		r.Get("/pulls", repo.Pulls)
		r.Get("/branches", repo.Branches)
	}, ignSignIn, middleware.RepoAssignment(true))

	m.Group("/:username/:reponame", func(r martini.Router) {
		r.Get("/src/:branchname", repo.Single)
		r.Get("/src/:branchname/**", repo.Single)
		r.Get("/raw/:branchname/**", repo.SingleDownload)
		r.Get("/commits/:branchname", repo.Commits)
		r.Get("/commits/:branchname/search", repo.SearchCommits)
		r.Get("/commit/:branchname", repo.Diff)
		r.Get("/commit/:branchname/**", repo.Diff)
		r.Get("/releases", repo.Releases)
		r.Get("/archive/:branchname/:reponame.zip", repo.ZipDownload)
	}, ignSignIn, middleware.RepoAssignment(true, true))

	m.Group("/:username", func(r martini.Router) {
		r.Get("/:reponame", middleware.RepoAssignment(true, true, true), repo.Single)
		r.Any("/:reponame/**", repo.Http)
	}, ignSignInAndCsrf)

	// Not found handler.
	m.NotFound(routers.NotFound)

	protocol := base.Cfg.MustValue("server", "PROTOCOL", "http")
	listenAddr := fmt.Sprintf("%s:%s",
		base.Cfg.MustValue("server", "HTTP_ADDR", "0.0.0.0"),
		base.Cfg.MustValue("server", "HTTP_PORT", "3000"))

	if protocol == "http" {
		log.Info("Listen: http://%s", listenAddr)
		if err := http.ListenAndServe(listenAddr, m); err != nil {
			qlog.Error(err.Error())
		}
	} else if protocol == "https" {
		log.Info("Listen: https://%s", listenAddr)
		if err := http.ListenAndServeTLS(listenAddr, base.Cfg.MustValue("server", "CERT_FILE"),
			base.Cfg.MustValue("server", "KEY_FILE"), m); err != nil {
			qlog.Error(err.Error())
		}
	}
	qlog.Fatalf("Invalid protocol: %s", protocol)
}
Exemple #23
0
func runServ(k *cli.Context) {
	setup(path.Join(setting.LogRootPath, "serv.log"))

	keys := strings.Split(os.Args[2], "-")
	if len(keys) != 2 {
		println("Gogs: auth file format error")
		qlog.Fatal("Invalid auth file format: %s", os.Args[2])
	}

	keyId, err := strconv.ParseInt(keys[1], 10, 64)
	if err != nil {
		println("Gogs: auth file format error")
		qlog.Fatalf("Invalid auth file format: %v", err)
	}
	user, err := models.GetUserByKeyId(keyId)
	if err != nil {
		if err == models.ErrUserNotKeyOwner {
			println("Gogs: you are not the owner of SSH key")
			qlog.Fatalf("Invalid owner of SSH key: %d", keyId)
		}
		println("Gogs: internal error:", err)
		qlog.Fatalf("Fail to get user by key ID(%d): %v", keyId, err)
	}

	cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
	if cmd == "" {
		println("Hi", user.Name, "! You've successfully authenticated, but Gogs does not provide shell access.")
		return
	}

	verb, args := parseCmd(cmd)
	repoPath := strings.Trim(args, "'")
	rr := strings.SplitN(repoPath, "/", 2)
	if len(rr) != 2 {
		println("Gogs: unavailable repository", args)
		qlog.Fatalf("Unavailable repository: %v", args)
	}
	repoUserName := rr[0]
	repoName := strings.TrimSuffix(rr[1], ".git")

	isWrite := In(verb, COMMANDS_WRITE)
	isRead := In(verb, COMMANDS_READONLY)

	repoUser, err := models.GetUserByName(repoUserName)
	if err != nil {
		if err == models.ErrUserNotExist {
			println("Gogs: given repository owner are not registered")
			qlog.Fatalf("Unregistered owner: %s", repoUserName)
		}
		println("Gogs: internal error:", err)
		qlog.Fatalf("Fail to get repository owner(%s): %v", repoUserName, err)
	}

	// Access check.
	switch {
	case isWrite:
		has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_WRITABLE)
		if err != nil {
			println("Gogs: internal error:", err)
			qlog.Fatal("Fail to check write access:", err)
		} else if !has {
			println("You have no right to write this repository")
			qlog.Fatalf("User %s has no right to write repository %s", user.Name, repoPath)
		}
	case isRead:
		repo, err := models.GetRepositoryByName(repoUser.Id, repoName)
		if err != nil {
			if err == models.ErrRepoNotExist {
				println("Gogs: given repository does not exist")
				qlog.Fatalf("Repository does not exist: %s/%s", repoUser.Name, repoName)
			}
			println("Gogs: internal error:", err)
			qlog.Fatalf("Fail to get repository: %v", err)
		}

		if !repo.IsPrivate {
			break
		}

		has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_READABLE)
		if err != nil {
			println("Gogs: internal error:", err)
			qlog.Fatal("Fail to check read access:", err)
		} else if !has {
			println("You have no right to access this repository")
			qlog.Fatalf("User %s has no right to read repository %s", user.Name, repoPath)
		}
	default:
		println("Unknown command")
		return
	}

	models.SetRepoEnvs(user.Id, user.Name, repoName, repoUserName)

	gitcmd := exec.Command(verb, repoPath)
	gitcmd.Dir = setting.RepoRootPath
	gitcmd.Stdout = os.Stdout
	gitcmd.Stdin = os.Stdin
	gitcmd.Stderr = os.Stderr

	if err = gitcmd.Run(); err != nil {
		println("Gogs: internal error:", err)
		qlog.Fatalf("Fail to execute git command: %v", err)
	}

	//refName := os.Getenv("refName")
	//oldCommitId := os.Getenv("oldCommitId")
	//newCommitId := os.Getenv("newCommitId")

	//qlog.Error("get envs:", refName, oldCommitId, newCommitId)

	// update
	//models.Update(refName, oldCommitId, newCommitId, repoUserName, repoName, user.Id)
}
func Update(refName, oldCommitId, newCommitId, userName, repoName string, userId int64) {
	isNew := strings.HasPrefix(oldCommitId, "0000000")
	if isNew &&
		strings.HasPrefix(newCommitId, "0000000") {
		qlog.Fatal("old rev and new rev both 000000")
	}

	f := RepoPath(userName, repoName)

	gitUpdate := exec.Command("git", "update-server-info")
	gitUpdate.Dir = f
	gitUpdate.Run()

	repo, err := git.OpenRepository(f)
	if err != nil {
		qlog.Fatalf("runUpdate.Open repoId: %v", err)
	}

	newCommit, err := repo.GetCommit(newCommitId)
	if err != nil {
		qlog.Fatalf("runUpdate GetCommit of newCommitId: %v", err)
		return
	}

	var l *list.List
	// if a new branch
	if isNew {
		l, err = newCommit.CommitsBefore()
		if err != nil {
			qlog.Fatalf("Find CommitsBefore erro: %v", err)
		}
	} else {
		l, err = newCommit.CommitsBeforeUntil(oldCommitId)
		if err != nil {
			qlog.Fatalf("Find CommitsBeforeUntil erro: %v", err)
			return
		}
	}

	if err != nil {
		qlog.Fatalf("runUpdate.Commit repoId: %v", err)
	}

	repos, err := GetRepositoryByName(userId, repoName)
	if err != nil {
		qlog.Fatalf("runUpdate.GetRepositoryByName userId: %v", err)
	}

	commits := make([]*base.PushCommit, 0)
	var maxCommits = 3
	var actEmail string
	for e := l.Front(); e != nil; e = e.Next() {
		commit := e.Value.(*git.Commit)
		if actEmail == "" {
			actEmail = commit.Committer.Email
		}
		commits = append(commits,
			&base.PushCommit{commit.Id.String(),
				commit.Message(),
				commit.Author.Email,
				commit.Author.Name})
		if len(commits) >= maxCommits {
			break
		}
	}

	//commits = append(commits, []string{lastCommit.Id().String(), lastCommit.Message()})
	if err = CommitRepoAction(userId, userName, actEmail,
		repos.Id, repoName, refName, &base.PushCommits{l.Len(), commits}); err != nil {
		qlog.Fatalf("runUpdate.models.CommitRepoAction: %v", err)
	}
}