Example #1
0
// SignedInId returns the id of signed in user.
func SignedInId(header http.Header, sess session.SessionStore) int64 {
	if !models.HasEngine {
		return 0
	}

	if setting.Service.EnableReverseProxyAuth {
		webAuthUser := header.Get(setting.ReverseProxyAuthUser)
		if len(webAuthUser) > 0 {
			u, err := models.GetUserByName(webAuthUser)
			if err != nil {
				if err != models.ErrUserNotExist {
					log.Error("auth.user.SignedInId(GetUserByName): %v", err)
				}
				return 0
			}
			return u.Id
		}
	}

	uid := sess.Get("userId")
	if uid == nil {
		return 0
	}
	if id, ok := uid.(int64); ok {
		if _, err := models.GetUserById(id); err != nil {
			if err != models.ErrUserNotExist {
				log.Error("auth.user.SignedInId(GetUserById): %v", err)
			}
			return 0
		}
		return id
	}
	return 0
}
Example #2
0
// CommitRepoAction adds new action for committing repository.
func CommitRepoAction(userId int64, userName, actEmail string,
	repoId int64, repoName string, refName string, commit *base.PushCommits) error {
	log.Trace("action.CommitRepoAction(start): %d/%s", userId, repoName)

	bs, err := json.Marshal(commit)
	if err != nil {
		log.Error("action.CommitRepoAction(json): %d/%s", userId, repoName)
		return err
	}

	if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, ActEmail: actEmail,
		OpType: OP_COMMIT_REPO, Content: string(bs), RepoId: repoId, RepoName: repoName, RefName: refName}); err != nil {
		log.Error("action.CommitRepoAction(notify watchers): %d/%s", userId, repoName)
		return err
	}

	// Change repository bare status and update last updated time.
	repo, err := GetRepositoryByName(userId, repoName)
	if err != nil {
		log.Error("action.CommitRepoAction(GetRepositoryByName): %d/%s", userId, repoName)
		return err
	}
	repo.IsBare = false
	if err = UpdateRepository(repo); err != nil {
		log.Error("action.CommitRepoAction(UpdateRepository): %d/%s", userId, repoName)
		return err
	}

	log.Trace("action.CommitRepoAction(end): %d/%s", userId, repoName)
	return nil
}
Example #3
0
File: issue.go Project: yweber/gogs
// NewIssue creates new issue with labels for repository.
func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	if err = newIssue(sess, repo, issue, labelIDs, uuids, false); err != nil {
		return fmt.Errorf("newIssue: %v", err)
	}

	if err = sess.Commit(); err != nil {
		return fmt.Errorf("Commit: %v", err)
	}

	// Notify watchers.
	act := &Action{
		ActUserID:    issue.Poster.ID,
		ActUserName:  issue.Poster.Name,
		ActEmail:     issue.Poster.Email,
		OpType:       ACTION_CREATE_ISSUE,
		Content:      fmt.Sprintf("%d|%s", issue.Index, issue.Name),
		RepoID:       repo.ID,
		RepoUserName: repo.Owner.Name,
		RepoName:     repo.Name,
		IsPrivate:    repo.IsPrivate,
	}
	if err = NotifyWatchers(act); err != nil {
		log.Error(4, "NotifyWatchers: %v", err)
	} else if err = issue.MailParticipants(); err != nil {
		log.Error(4, "MailParticipants: %v", err)
	}

	return nil
}
Example #4
0
// DeliverHooks checks and delivers undelivered hooks.
func DeliverHooks() {
	timeout := time.Duration(setting.WebhookDeliverTimeout) * time.Second
	x.Where("is_deliveried=?", false).Iterate(new(HookTask),
		func(idx int, bean interface{}) error {
			t := bean.(*HookTask)
			req := httplib.Post(t.Url).SetTimeout(timeout, timeout).
				Header("X-Gogs-Delivery", t.Uuid).
				Header("X-Gogs-Event", string(t.EventType))

			switch t.ContentType {
			case JSON:
				req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
			case FORM:
				req.Param("payload", t.PayloadContent)
			}

			t.IsDeliveried = true

			// TODO: record response.
			if _, err := req.Response(); err != nil {
				log.Error(4, "Delivery: %v", err)
			} else {
				t.IsSucceed = true
			}

			if err := UpdateHookTask(t); err != nil {
				log.Error(4, "UpdateHookTask: %v", err)
				return nil
			}

			log.Trace("Hook delivered(%s): %s", t.Uuid, t.PayloadContent)
			return nil
		})
}
Example #5
0
func (i *Issue) AfterSet(colName string, _ xorm.Cell) {
	var err error
	switch colName {
	case "id":
		i.Attachments, err = GetAttachmentsByIssueID(i.ID)
		if err != nil {
			log.Error(3, "GetAttachmentsByIssueID[%d]: %v", i.ID, err)
		}

		i.Comments, err = GetCommentsByIssueID(i.ID)
		if err != nil {
			log.Error(3, "GetCommentsByIssueID[%d]: %v", i.ID, err)
		}

	case "milestone_id":
		if i.MilestoneID == 0 {
			return
		}

		i.Milestone, err = GetMilestoneByID(i.MilestoneID)
		if err != nil {
			log.Error(3, "GetMilestoneById[%d]: %v", i.ID, err)
		}
	case "assignee_id":
		if i.AssigneeID == 0 {
			return
		}

		i.Assignee, err = GetUserByID(i.AssigneeID)
		if err != nil {
			log.Error(3, "GetUserByID[%d]: %v", i.ID, err)
		}
	}
}
Example #6
0
func listen(config *ssh.ServerConfig, port int) {
	listener, err := net.Listen("tcp", "0.0.0.0:"+com.ToStr(port))
	if err != nil {
		panic(err)
	}
	for {
		// Once a ServerConfig has been configured, connections can be accepted.
		conn, err := listener.Accept()
		if err != nil {
			log.Error(3, "Error accepting incoming connection: %v", err)
			continue
		}
		// Before use, a handshake must be performed on the incoming net.Conn.
		sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
		if err != nil {
			log.Error(3, "Error on handshaking: %v", err)
			continue
		}

		log.Trace("Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
		// The incoming Request channel must be serviced.
		go ssh.DiscardRequests(reqs)
		go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
	}
}
Example #7
0
// runSync returns true if sync finished without error.
func (m *Mirror) runSync() bool {
	repoPath := m.Repo.RepoPath()
	wikiPath := m.Repo.WikiPath()
	timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second

	gitArgs := []string{"remote", "update"}
	if m.EnablePrune {
		gitArgs = append(gitArgs, "--prune")
	}

	if _, stderr, err := process.ExecDir(
		timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
		"git", gitArgs...); err != nil {
		desc := fmt.Sprintf("Fail to update mirror repository '%s': %s", repoPath, stderr)
		log.Error(4, desc)
		if err = CreateRepositoryNotice(desc); err != nil {
			log.Error(4, "CreateRepositoryNotice: %v", err)
		}
		return false
	}
	if m.Repo.HasWiki() {
		if _, stderr, err := process.ExecDir(
			timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
			"git", "remote", "update", "--prune"); err != nil {
			desc := fmt.Sprintf("Fail to update mirror wiki repository '%s': %s", wikiPath, stderr)
			log.Error(4, desc)
			if err = CreateRepositoryNotice(desc); err != nil {
				log.Error(4, "CreateRepositoryNotice: %v", err)
			}
			return false
		}
	}

	return true
}
Example #8
0
File: repo.go Project: GoNuuts/gogs
func createRepo(ctx *middleware.Context, owner *models.User, opt api.CreateRepoOption) {
	repo, err := models.CreateRepository(owner, models.CreateRepoOptions{
		Name:        opt.Name,
		Description: opt.Description,
		Gitignores:  opt.Gitignores,
		License:     opt.License,
		Readme:      opt.Readme,
		IsPrivate:   opt.Private,
		AutoInit:    opt.AutoInit,
	})
	if err != nil {
		if models.IsErrRepoAlreadyExist(err) ||
			models.IsErrNameReserved(err) ||
			models.IsErrNamePatternNotAllowed(err) {
			ctx.JSON(422, &base.ApiJsonErr{err.Error(), base.DOC_URL})
		} else {
			log.Error(4, "CreateRepository: %v", err)
			if repo != nil {
				if err = models.DeleteRepository(ctx.User.Id, repo.ID); err != nil {
					log.Error(4, "DeleteRepository: %v", err)
				}
			}
			ctx.Error(500)
		}
		return
	}

	ctx.JSON(201, ToApiRepository(owner, repo, api.Permission{true, true, true}))
}
Example #9
0
func (t *HookTask) AfterSet(colName string, _ xorm.Cell) {
	var err error
	switch colName {
	case "delivered":
		t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")

	case "request_content":
		if len(t.RequestContent) == 0 {
			return
		}

		t.RequestInfo = &HookRequest{}
		if err = json.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
			log.Error(3, "Unmarshal[%d]: %v", t.ID, err)
		}

	case "response_content":
		if len(t.ResponseContent) == 0 {
			return
		}

		t.ResponseInfo = &HookResponse{}
		if err = json.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
			log.Error(3, "Unmarshal[%d]: %v", t.ID, err)
		}
	}
}
Example #10
0
// GitFsck calls 'git fsck' to check repository health.
func GitFsck() {
	if isGitFscking {
		return
	}
	isGitFscking = true
	defer func() { isGitFscking = false }()

	log.Trace("Doing: GitFsck")

	args := append([]string{"fsck"}, setting.Cron.RepoHealthCheck.Args...)
	if err := x.Where("id>0").Iterate(new(Repository),
		func(idx int, bean interface{}) error {
			repo := bean.(*Repository)
			repoPath, err := repo.RepoPath()
			if err != nil {
				return fmt.Errorf("RepoPath: %v", err)
			}

			_, _, err = process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
			if err != nil {
				desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
				log.Warn(desc)
				if err = CreateRepositoryNotice(desc); err != nil {
					log.Error(4, "CreateRepositoryNotice: %v", err)
				}
			}
			return nil
		}); err != nil {
		log.Error(4, "GitFsck: %v", err)
	}
}
Example #11
0
// TransferRepoAction adds new action for transfering repository.
func TransferRepoAction(u, newUser *User, repo *Repository) (err error) {
	action := &Action{
		ActUserId:    u.Id,
		ActUserName:  u.Name,
		ActEmail:     u.Email,
		OpType:       TRANSFER_REPO,
		RepoId:       repo.Id,
		RepoUserName: newUser.Name,
		RepoName:     repo.Name,
		IsPrivate:    repo.IsPrivate,
		Content:      path.Join(repo.Owner.LowerName, repo.LowerName),
	}
	if err = NotifyWatchers(action); err != nil {
		log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name)
		return err
	}

	// Remove watch for organization.
	if repo.Owner.IsOrganization() {
		if err = WatchRepo(repo.Owner.Id, repo.Id, false); err != nil {
			log.Error(4, "WatchRepo", err)
		}
	}

	log.Trace("action.TransferRepoAction: %s/%s", u.Name, repo.Name)
	return err
}
Example #12
0
func CheckRepoStats() {
	if isCheckingRepos {
		return
	}
	isCheckingRepos = true
	defer func() { isCheckingRepos = false }()

	// Check count watchers
	results_watch, err := x.Query("SELECT r.id FROM `repository` r WHERE r.num_watches!=(SELECT count(*) FROM `watch` WHERE repo_id=r.id)")
	if err != nil {
		log.Error(4, "select repository check 'watch': %v", err)
	}
	for _, repo_id := range results_watch {
		log.Info("updating repository count 'watch'")
		repoID := com.StrTo(repo_id["id"]).MustInt64()
		_, err := x.Exec("UPDATE `repository` SET num_watches=(SELECT count(*) FROM `watch` WHERE repo_id=?) WHERE id=?", repoID, repoID)
		if err != nil {
			log.Error(4, "update repository check 'watch', repo %v: %v", repo_id, err)
		}
	}

	// Check count stars
	results_star, err := x.Query("SELECT s.id FROM `repository` s WHERE s.num_stars!=(SELECT count(*) FROM `star` WHERE repo_id=s.id)")
	if err != nil {
		log.Error(4, "select repository check 'star': %v", err)
	}
	for _, repo_id := range results_star {
		log.Info("updating repository count 'star'")
		repoID := com.StrTo(repo_id["id"]).MustInt64()
		_, err := x.Exec("UPDATE `repository` SET .num_stars=(SELECT count(*) FROM `star` WHERE repo_id=?) WHERE id=?", repoID, repoID)
		if err != nil {
			log.Error(4, "update repository check 'star', repo %v: %v", repo_id, err)
		}
	}
}
Example #13
0
// GitFsck calls 'git fsck' to check repository health.
func GitFsck() {
	if isGitFscking {
		return
	}
	isGitFscking = true
	defer func() { isGitFscking = false }()

	args := append([]string{"fsck"}, setting.Git.Fsck.Args...)
	if err := x.Where("id > 0").Iterate(new(Repository),
		func(idx int, bean interface{}) error {
			repo := bean.(*Repository)
			if err := repo.GetOwner(); err != nil {
				return err
			}

			repoPath := RepoPath(repo.Owner.Name, repo.Name)
			_, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
			if err != nil {
				desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
				log.Warn(desc)
				if err = CreateRepositoryNotice(desc); err != nil {
					log.Error(4, "Fail to add notice: %v", err)
				}
			}
			return nil
		}); err != nil {
		log.Error(4, "repo.Fsck: %v", err)
	}
}
Example #14
0
// github && google && ...
func SocialSignIn(tokens oauth2.Tokens) {
	transport := &oauth.Transport{}
	transport.Token = &oauth.Token{
		AccessToken:  tokens.Access(),
		RefreshToken: tokens.Refresh(),
		Expiry:       tokens.ExpiryTime(),
		Extra:        tokens.ExtraData(),
	}

	// Github API refer: https://developer.github.com/v3/users/
	// FIXME: need to judge url
	type GithubUser struct {
		Id    int    `json:"id"`
		Name  string `json:"login"`
		Email string `json:"email"`
	}

	// Make the request.
	scope := "https://api.github.com/user"
	r, err := transport.Client().Get(scope)
	if err != nil {
		log.Error("connect with github error: %s", err)
		// FIXME: handle error page
		return
	}
	defer r.Body.Close()

	user := &GithubUser{}
	err = json.NewDecoder(r.Body).Decode(user)
	if err != nil {
		log.Error("Get: %s", err)
	}
	log.Info("login: %s", user.Name)
	// FIXME: login here, user email to check auth, if not registe, then generate a uniq username
}
Example #15
0
File: pull.go Project: john-hu/gogs
// Note: don't try to get Pull because will end up recursive querying.
func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
	var err error
	switch colName {
	case "head_repo_id":
		// FIXME: shouldn't show error if it's known that head repository has been removed.
		pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
		if err != nil {
			log.Error(3, "GetRepositoryByID[%d]: %v", pr.ID, err)
		}
	case "merger_id":
		if !pr.HasMerged {
			return
		}

		pr.Merger, err = GetUserByID(pr.MergerID)
		if err != nil {
			if IsErrUserNotExist(err) {
				pr.MergerID = -1
				pr.Merger = NewFakeUser()
			} else {
				log.Error(3, "GetUserByID[%d]: %v", pr.ID, err)
			}
		}
	case "merged":
		if !pr.HasMerged {
			return
		}

		pr.Merged = regulateTimeZone(pr.Merged)
	}
}
Example #16
0
func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
	var err error
	switch colName {
	case "id":
		c.Attachments, err = GetAttachmentsByCommentID(c.ID)
		if err != nil {
			log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
		}

	case "poster_id":
		c.Poster, err = GetUserByID(c.PosterID)
		if err != nil {
			if IsErrUserNotExist(err) {
				c.PosterID = -1
				c.Poster = NewGhostUser()
			} else {
				log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
			}
		}
	case "created_unix":
		c.Created = time.Unix(c.CreatedUnix, 0).Local()
	case "updated_unix":
		c.Updated = time.Unix(c.UpdatedUnix, 0).Local()
	}
}
Example #17
0
File: ldap.go Project: noikiy/gogs
// searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter
func (ls Ldapsource) SearchEntry(name, passwd string) (string, string, string, bool, bool) {
	userDN, found := ls.FindUserDN(name)
	if !found {
		return "", "", "", false, false
	}

	l, err := ldapDial(ls)
	if err != nil {
		log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err)
		ls.Enabled = false
		return "", "", "", false, false
	}

	defer l.Close()

	log.Trace("Binding with userDN: %s", userDN)
	err = l.Bind(userDN, passwd)
	if err != nil {
		log.Debug("LDAP auth. failed for %s, reason: %v", userDN, err)
		return "", "", "", false, false
	}

	log.Trace("Bound successfully with userDN: %s", userDN)
	userFilter := fmt.Sprintf(ls.Filter, name)
	search := ldap.NewSearchRequest(
		userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
		[]string{ls.AttributeName, ls.AttributeSurname, ls.AttributeMail},
		nil)

	sr, err := l.Search(search)
	if err != nil {
		log.Error(4, "LDAP Search failed unexpectedly! (%v)", err)
		return "", "", "", false, false
	} else if len(sr.Entries) < 1 {
		log.Error(4, "LDAP Search failed unexpectedly! (0 entries)")
		return "", "", "", false, false
	}

	name_attr := sr.Entries[0].GetAttributeValue(ls.AttributeName)
	sn_attr := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
	mail_attr := sr.Entries[0].GetAttributeValue(ls.AttributeMail)

	search = ldap.NewSearchRequest(
		userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
		[]string{ls.AttributeName},
		nil)

	sr, err = l.Search(search)
	admin_attr := false
	if err != nil {
		log.Error(4, "LDAP Admin Search failed unexpectedly! (%v)", err)
	} else if len(sr.Entries) < 1 {
		log.Error(4, "LDAP Admin Search failed")
	} else {
		admin_attr = true
	}

	return name_attr, sn_attr, mail_attr, admin_attr, true
}
Example #18
0
func (ls Ldapsource) FindUserDN(name, passwd string) (string, bool) {
	l, err := ldapDial(ls)
	if err != nil {
		log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err)
		ls.Enabled = false
		return "", false
	}
	defer l.Close()

	log.Trace("Search for LDAP user: %s", name)
	if ls.BindDN != "" {
		var bd, bp string
		// With palceholder in BindDN and no password,
		// It will bind as combination define in BindDN with login password
		if ls.BindPassword == "" {
			bd = strings.Replace(ls.BindDN, "<username>", name, -1)
			bp = passwd
		} else {
			bd = ls.BindDN
			bp = ls.BindPassword
		}
		err = l.Bind(bd, bp)
		if err != nil {
			log.Debug("Failed to bind as BindDN[%s]: %v", bd, err)
			return "", false
		}
		log.Trace("Bound as BindDN %s", bd)
	} else {
		log.Trace("Proceeding with anonymous LDAP search.")
	}

	// A search for the user.
	userFilter := fmt.Sprintf(ls.Filter, name)
	log.Trace("Searching using filter %s", userFilter)
	search := ldap.NewSearchRequest(
		ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
		false, userFilter, []string{}, nil)

	// Ensure we found a user
	sr, err := l.Search(search)
	if err != nil || len(sr.Entries) < 1 {
		log.Debug("Failed search using filter[%s]: %v", userFilter, err)
		return "", false
	} else if len(sr.Entries) > 1 {
		log.Debug("Filter '%s' returned more than one user.", userFilter)
		return "", false
	}

	userDN := sr.Entries[0].DN
	if userDN == "" {
		log.Error(4, "LDAP search was succesful, but found no DN!")
		return "", false
	}

	return userDN, true
}
Example #19
0
File: pull.go Project: yweber/gogs
// NewPullRequest creates new pull request with labels for repository.
func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	if err = newIssue(sess, repo, pull, labelIDs, uuids, true); err != nil {
		return fmt.Errorf("newIssue: %v", err)
	}

	// Notify watchers.
	act := &Action{
		ActUserID:    pull.Poster.ID,
		ActUserName:  pull.Poster.Name,
		ActEmail:     pull.Poster.Email,
		OpType:       ACTION_CREATE_PULL_REQUEST,
		Content:      fmt.Sprintf("%d|%s", pull.Index, pull.Name),
		RepoID:       repo.ID,
		RepoUserName: repo.Owner.Name,
		RepoName:     repo.Name,
		IsPrivate:    repo.IsPrivate,
	}

	pr.Index = pull.Index
	if err = repo.SavePatch(pr.Index, patch); err != nil {
		return fmt.Errorf("SavePatch: %v", err)
	}

	pr.BaseRepo = repo
	if err = pr.testPatch(); err != nil {
		return fmt.Errorf("testPatch: %v", err)
	}
	if pr.Status == PULL_REQUEST_STATUS_CHECKING {
		pr.Status = PULL_REQUEST_STATUS_MERGEABLE
	}

	pr.IssueID = pull.ID
	if _, err = sess.Insert(pr); err != nil {
		return fmt.Errorf("insert pull repo: %v", err)
	}

	if err = sess.Commit(); err != nil {
		return fmt.Errorf("Commit: %v", err)
	}

	if err = NotifyWatchers(act); err != nil {
		log.Error(4, "NotifyWatchers: %v", err)
	} else if err = pull.MailParticipants(); err != nil {
		log.Error(4, "MailParticipants: %v", err)
	}

	return nil
}
Example #20
0
File: ssh.go Project: nafrente/gogs
func handleServerConn(keyId string, chans <-chan ssh.NewChannel) {
	for newChan := range chans {
		if newChan.ChannelType() != "session" {
			newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
			continue
		}
		channel, requests, err := newChan.Accept()
		if err != nil {
			log.Error(3, "Could not accept channel: %v", err)
			continue
		}

		go func(in <-chan *ssh.Request) {
			defer channel.Close()
			for req := range in {
				ok, payload := false, strings.TrimLeft(string(req.Payload), "\x00&")
				fmt.Println("Request:", req.Type, req.WantReply, payload)
				if req.WantReply {
					fmt.Println(req.Reply(true, nil))
				}
				switch req.Type {
				case "env":
					args := strings.Split(strings.Replace(payload, "\x00", "", -1), "\v")
					if len(args) != 2 {
						break
					}
					args[0] = strings.TrimLeft(args[0], "\x04")
					_, _, err := com.ExecCmdBytes("env", args[0]+"="+args[1])
					if err != nil {
						log.Error(3, "env: %v", err)
						channel.Stderr().Write([]byte(err.Error()))
						break
					}
					ok = true
				case "exec":
					os.Setenv("SSH_ORIGINAL_COMMAND", strings.TrimLeft(payload, "'("))
					log.Info("Payload: %v", strings.TrimLeft(payload, "'("))
					cmd := exec.Command("/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/gogs", "serv", "key-"+keyId)
					cmd.Stdout = channel
					cmd.Stdin = channel
					cmd.Stderr = channel.Stderr()
					if err := cmd.Run(); err != nil {
						log.Error(3, "exec: %v", err)
					} else {
						ok = true
					}
				}
				fmt.Println("Done:", ok)
			}
			fmt.Println("Done!!!")
		}(requests)
	}
}
Example #21
0
File: webhook.go Project: gr4y/gogs
func deliverHook(t *HookTask) {
	timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
	req := httplib.Post(t.Url).SetTimeout(timeout, timeout).
		Header("X-Gogs-Delivery", t.Uuid).
		Header("X-Gogs-Event", string(t.EventType)).
		SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})

	switch t.ContentType {
	case JSON:
		req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
	case FORM:
		req.Param("payload", t.PayloadContent)
	}

	t.IsDelivered = true

	// FIXME: record response.
	switch t.Type {
	case GOGS:
		{
			if resp, err := req.Response(); err != nil {
				log.Error(5, "Delivery: %v", err)
			} else {
				resp.Body.Close()
				t.IsSucceed = true
			}
		}
	case SLACK:
		{
			if resp, err := req.Response(); err != nil {
				log.Error(5, "Delivery: %v", err)
			} else {
				defer resp.Body.Close()
				contents, err := ioutil.ReadAll(resp.Body)
				if err != nil {
					log.Error(5, "%s", err)
				} else {
					if string(contents) != "ok" {
						log.Error(5, "slack failed with: %s", string(contents))
					} else {
						t.IsSucceed = true
					}
				}
			}
		}
	}

	t.Delivered = time.Now().UTC().UnixNano()
	if t.IsSucceed {
		log.Trace("Hook delivered(%s): %s", t.Uuid, t.PayloadContent)
	}
}
Example #22
0
// SignedInID returns the id of signed in user.
func SignedInID(ctx *macaron.Context, sess session.Store) int64 {
	if !models.HasEngine {
		return 0
	}

	// Check access token.
	if IsAPIPath(ctx.Req.URL.Path) {
		tokenSHA := ctx.Query("token")
		if len(tokenSHA) == 0 {
			// Well, check with header again.
			auHead := ctx.Req.Header.Get("Authorization")
			if len(auHead) > 0 {
				auths := strings.Fields(auHead)
				if len(auths) == 2 && auths[0] == "token" {
					tokenSHA = auths[1]
				}
			}
		}

		// Let's see if token is valid.
		if len(tokenSHA) > 0 {
			t, err := models.GetAccessTokenBySHA(tokenSHA)
			if err != nil {
				if models.IsErrAccessTokenNotExist(err) {
					log.Error(4, "GetAccessTokenBySHA: %v", err)
				}
				return 0
			}
			t.Updated = time.Now()
			if err = models.UpdateAccessToekn(t); err != nil {
				log.Error(4, "UpdateAccessToekn: %v", err)
			}
			return t.UID
		}
	}

	uid := sess.Get("uid")
	if uid == nil {
		return 0
	}
	if id, ok := uid.(int64); ok {
		if _, err := models.GetUserByID(id); err != nil {
			if !models.IsErrUserNotExist(err) {
				log.Error(4, "GetUserById: %v", err)
			}
			return 0
		}
		return id
	}
	return 0
}
Example #23
0
func Action(ctx *middleware.Context) {
	var err error
	switch ctx.Params(":action") {
	case "watch":
		err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.Id, true)
	case "unwatch":
		err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.Id, false)
	case "star":
		err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.Id, true)
	case "unstar":
		err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.Id, false)
	case "fork":
		repo, err := models.ForkRepository(ctx.User, ctx.Repo.Repository)
		if err != nil {
			if err != models.ErrRepoAlreadyExist {
				log.Error(4, "Action(%s): %v", ctx.Params(":action"), err)
				ctx.JSON(200, map[string]interface{}{
					"ok":  false,
					"err": err.Error(),
				})
				return
			}
		}
		ctx.Redirect(setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name)
		return
	case "desc":
		if !ctx.Repo.IsOwner {
			ctx.Error(404)
			return
		}

		ctx.Repo.Repository.Description = ctx.Query("desc")
		ctx.Repo.Repository.Website = ctx.Query("site")
		err = models.UpdateRepository(ctx.Repo.Repository)
	}

	if err != nil {
		log.Error(4, "Action(%s): %v", ctx.Params(":action"), err)
		ctx.JSON(200, map[string]interface{}{
			"ok":  false,
			"err": err.Error(),
		})
		return
	}
	ctx.Redirect(ctx.Repo.RepoLink)
	return
	ctx.JSON(200, map[string]interface{}{
		"ok": true,
	})
}
Example #24
0
File: pull.go Project: yweber/gogs
func addHeadRepoTasks(prs []*PullRequest) {
	for _, pr := range prs {
		log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
		if err := pr.UpdatePatch(); err != nil {
			log.Error(4, "UpdatePatch: %v", err)
			continue
		} else if err := pr.PushToBaseRepo(); err != nil {
			log.Error(4, "PushToBaseRepo: %v", err)
			continue
		}

		pr.AddToTaskQueue()
	}
}
Example #25
0
func (ls *Source) FindUserDN(name string) (string, bool) {
	l, err := ldapDial(ls)
	if err != nil {
		log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err)
		ls.Enabled = false
		return "", false
	}
	defer l.Close()

	log.Trace("Search for LDAP user: %s", name)
	if ls.BindDN != "" && ls.BindPassword != "" {
		err = l.Bind(ls.BindDN, ls.BindPassword)
		if err != nil {
			log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err)
			return "", false
		}
		log.Trace("Bound as BindDN %s", ls.BindDN)
	} else {
		log.Trace("Proceeding with anonymous LDAP search.")
	}

	// A search for the user.
	userFilter, ok := ls.sanitizedUserQuery(name)
	if !ok {
		return "", false
	}

	log.Trace("Searching using filter %s", userFilter)
	search := ldap.NewSearchRequest(
		ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
		false, userFilter, []string{}, nil)

	// Ensure we found a user
	sr, err := l.Search(search)
	if err != nil || len(sr.Entries) < 1 {
		log.Debug("Failed search using filter[%s]: %v", userFilter, err)
		return "", false
	} else if len(sr.Entries) > 1 {
		log.Debug("Filter '%s' returned more than one user.", userFilter)
		return "", false
	}

	userDN := sr.Entries[0].DN
	if userDN == "" {
		log.Error(4, "LDAP search was successful, but found no DN!")
		return "", false
	}

	return userDN, true
}
Example #26
0
// MirrorUpdate checks and updates mirror repositories.
func MirrorUpdate() {
	if isMirrorUpdating {
		return
	}
	isMirrorUpdating = true
	defer func() { isMirrorUpdating = false }()

	log.Trace("Doing: MirrorUpdate")

	mirrors := make([]*Mirror, 0, 10)
	if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
		m := bean.(*Mirror)
		if m.NextUpdate.After(time.Now()) {
			return nil
		}

		if m.Repo == nil {
			log.Error(4, "Disconnected mirror repository found: %d", m.ID)
			return nil
		}

		repoPath, err := m.Repo.RepoPath()
		if err != nil {
			return fmt.Errorf("Repo.RepoPath: %v", err)
		}

		if _, stderr, err := process.ExecDir(10*time.Minute,
			repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
			"git", "remote", "update", "--prune"); err != nil {
			desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
			log.Error(4, desc)
			if err = CreateRepositoryNotice(desc); err != nil {
				log.Error(4, "CreateRepositoryNotice: %v", err)
			}
			return nil
		}

		m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
		mirrors = append(mirrors, m)
		return nil
	}); err != nil {
		log.Error(4, "MirrorUpdate: %v", err)
	}

	for i := range mirrors {
		if err := UpdateMirror(mirrors[i]); err != nil {
			log.Error(4, "UpdateMirror[%d]: %v", mirrors[i].ID, err)
		}
	}
}
Example #27
0
func repoStatsCheck(checker *repoChecker) {
	results, err := x.Query(checker.querySQL)
	if err != nil {
		log.Error(4, "Select %s: %v", checker.desc, err)
		return
	}
	for _, result := range results {
		id := com.StrTo(result["id"]).MustInt64()
		log.Trace("Updating %s: %d", checker.desc, id)
		_, err = x.Exec(checker.correctSQL, id, id)
		if err != nil {
			log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
		}
	}
}
Example #28
0
func (w *Webhook) GetSlackHook() *Slack {
	s := &Slack{}
	if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
		log.Error(4, "webhook.GetSlackHook(%d): %v", w.Id, err)
	}
	return s
}
Example #29
0
// IsWriterOfRepo returns true if user has write access to given repository.
func (u *User) IsWriterOfRepo(repo *Repository) bool {
	has, err := HasAccess(u, repo, ACCESS_MODE_WRITE)
	if err != nil {
		log.Error(3, "HasAccess: %v", err)
	}
	return has
}
Example #30
0
// IsAdminOfRepo returns true if user has admin or higher access of repository.
func (u *User) IsAdminOfRepo(repo *Repository) bool {
	has, err := HasAccess(u, repo, ACCESS_MODE_ADMIN)
	if err != nil {
		log.Error(3, "HasAccess: %v", err)
	}
	return has
}