func CreateSession(PId string) (SId string, err error) { pl := GetPlayer(PId, false) if pl == nil { return "", errInvPlayer } SId = util.RandString(32) pl.SId = SId cnt, err := tblPlayer.Table.UpdateSingle("SId", pl) if err != nil { return } if cnt <= 0 { err = errors.New("db_failure") return } //update cache inplace tblPlayer.Cache.Lock() defer tblPlayer.Cache.Unlock() v, _ := tblPlayer.Cache.GetUnsafe(pl.PId) if v == nil { //alredy deleted return } plCached := v.(*Player) plCached.SId = SId return }
//modify password func ChangePwd(email, newPwd string) (err error) { salt := util.RandString(8) pwd := util.Md5(salt + newPwd) model.UserC.Do(func(c *mgo.Collection) { err = c.Update(bson.M{"email": email}, bson.M{"$set": bson.M{"salt": salt, "password": pwd}}) }) return }
//create an user, with dup_key error for email or nickname. func AddUser(email, nickname, password string) error { salt := util.RandString(8) password = util.Md5(salt + password) u := &User{Id: bson.NewObjectId(), Email: email, NickName: nickname, Salt: salt, Password: password, CreateTime: time.Now()} var err error model.UserC.Do(func(c *mgo.Collection) { err = c.Insert(u) if err != nil && !mgo.IsDup(err) { model.ErrorLog(model.UserC, err, u) } }) return err }
// Function that handles the callback from the Google server func (h *AuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { //Get the code from the response code := r.FormValue("code") t := &oauth.Transport{Config: oauthCfg} // Exchange the received code for a token t.Exchange(code) //now get user data based on the Transport which has the token resp, err := t.Client().Get(profileInfoURL) if err != nil { http.Redirect(w, r, "/", http.StatusFound) return } //buf := make([]byte, 1024) //resp.Body.Read(buf) buf, _ := ioutil.ReadAll(resp.Body) var oa OAuth json.Unmarshal(buf, &oa) //log.Printf("Results: %v\n", oa) if len(oa.OId) < 4 || len(oa.Name) < 1 { userFailTemplate.Execute(w, string(buf)) return } oa.Token = util.RandString(32) table.InsertOrReplace(oa) authCache.Set(oa.OId, &oa) session := seshcookie.Session.Get(r) session["oaid"] = oa.OId session["sestok"] = oa.Token //session["oauth"] = map[string]string{"OId": oa.OId, "Name": oa.Name} log.Println("Login:"******"/", http.StatusFound) }
func ServerStart() (err error) { if srvCmd != nil { return errors.New("already_running") } srvToken = util.RandString(16) srvCmd = exec.Command("../gamesrv/gamesrv", "-token="+srvToken) stderr, _ := srvCmd.StderrPipe() err = srvCmd.Start() if err != nil { srvCmd = nil return errors.New("startup_error:" + err.Error()) } srvStart = time.Now() srvQuit = make(chan bool) log.Println("Startet:", srvStart) cfgCtrl := srv.Cfg().Get("server") srvPort = cfgCtrl.Get("gameport").String() logfile := "../gamesrv/log/log.txt" for i := 0; i < 400; i++ { time.Sleep(10 * time.Millisecond) srvLogFile, err = os.Open(logfile) if err == nil { break } } if err != nil { log.Println("error opening logfile: ", err) srvCmd.Process.Signal(os.Kill) srvCmd = nil return errors.New("startup_error:" + err.Error()) } go func() { srvRunning = true srvWait.Add(1) //wait for logfile defer srvWait.Done() pp := perf.NewProcPerf(srvCmd.Process) fi := bufio.NewReader(srvLogFile) er := bufio.NewReader(stderr) pr := srvCmd.Process tickLog := time.NewTicker(250 * time.Millisecond) tickPro := time.NewTicker(1000 * time.Millisecond) tickSta := time.NewTicker(5000 * time.Millisecond) defer tickLog.Stop() defer tickPro.Stop() defer tickSta.Stop() statsPending := false go func() { for { ln, err := er.ReadString('\n') if err == io.EOF { log.Println("err closed by server") break } if err != nil { log.Println("err closed by server:", err) break } if len(ln) > 0 && ln[len(ln)-1] == '\n' { ln = ln[:len(ln)-1] } //log.Print(ln) srv.PushLog("e==> " + ln) } }() for { select { case <-tickLog.C: for { ln, err := fi.ReadString('\n') if err == io.EOF { break } if err != nil { log.Println("log closed by server:", err) fi = nil srvRunning = false return } if len(ln) > 0 && ln[len(ln)-1] == '\n' { ln = ln[:len(ln)-1] } //log.Print(ln) srv.PushLog("l==> " + ln) } if pr != nil && srvCmd != nil { e, err := perf.GetExitCodeProcess(pr) if err != nil || e != 259 { log.Println("exit:", e, err) pr = nil go ServerStop() if GetAutoRestart() { go func() { time.Sleep(time.Millisecond * 8000) log.Println("auto restart") ServerStart() }() } continue } } case <-tickSta.C: go func() { if statsPending { return } statsPending = true stats, _ := ServerStats() statsPending = false if stats != nil && stats["requestCount"] != nil { srvRequestCount = int64(stats["requestCount"].(float64)) srvRequestErr = int64(stats["requestErr"].(float64)) srvRequestDuration = int64(stats["requestDuration"].(float64)) srv.SrvRequestCount = srvRequestCount srv.SrvRequestDur = srvRequestDuration } }() case <-tickPro.C: err = pp.Get() srvLoadSys = pp.LoadSys srvLoadTotal = pp.LoadTotal srvWorkingSet = pp.WorkingSet case <-srvQuit: //fmt.Println("quit") s := srvLogFile.Name() srvLogFile.Close() srvLogFile = nil os.Remove(s) log.Println("log closed") } } }() return nil }
func rpcHandler(w http.ResponseWriter, r *http.Request) { sURL := r.URL.Path[5:] //log.Println("rpc:", sURL) mParams := r.URL.Query() //adminsrv control commands if sURL == "shutdown" { token := mParams.Get("token") log.Println("Shutdown:", adminToken, token) if adminToken != token { return } DoShutdown() return } if sURL == "stats" { token := mParams.Get("token") if adminToken != token { return } var result = map[string]interface{}{} result["requestCount"] = requestCount result["requestErr"] = requestErr result["requestDuration"] = requestDuration msg, _ := json.Marshal(result) w.Write(msg) return } if sURL == "flushcache" { token := mParams.Get("token") if adminToken != token { return } FlushCaches() return } timeNow := time.Now().UnixNano() requestCount++ var err error var data interface{} defer func() { timeDone := time.Now().UnixNano() requestDuration += timeDone - timeNow var result = map[string]interface{}{} result["ts"] = ((timeDone + timeNow) / 2) / 1000000 result["tc"] = mParams.Get("tc") if err == nil { result["result"] = true } else { requestErr++ log.Println("rpc error:", sURL, err, data) result["result"] = false result["error"] = err.Error() } if data != nil { result["data"] = data } msg, _ := json.Marshal(result) w.Write(msg) }() //test login for unity editor, possible security issue!!! if sURL == "login_password" { pid := mParams.Get("pid") pass := mParams.Get("pass") pid, err = ValidatePassword(pid, pass) if err != nil { return } data, err = CreateSession(pid) return } if sURL == "login_google" { token := mParams.Get("token") var pid string pid, err = ValidateToken(token) if err != nil { return } var sid string sid, err = CreateSession(pid) if err != nil { for i := 0; i < 10; i++ { name := "player_" + util.RandString(5) var ok bool ok, err = CreatePlayer(pid, name, "") if ok { sid, err = CreateSession(pid) break } } } data = map[string]interface{}{"pid": pid, "sid": sid} return } if sURL == "createplayer" { pid := mParams.Get("pid") name := mParams.Get("name") pass := mParams.Get("pass") _, err = CreatePlayer(pid, name, pass) return } //validate user session pid := mParams.Get("pid") sid := mParams.Get("sid") var ok bool ok, err = ValidateSession(pid, sid) if !ok { return } player := GetPlayer(pid, true) if player == nil { err = errors.New("invalid_player") return } player.ResolveTechTree() //player specific rpc's go here if sURL == "pinfo" { pother := mParams.Get("pinfo") version := mParams.Get("v") fversion := mParams.Get("fv") cversion := mParams.Get("cv") if len(pother) > 0 { apother := strings.Split(pother, ",") var adata = make([]interface{}, len(apother)) for i := 0; i < len(apother); i++ { pl := GetPlayer(apother[i], false) if pl != nil { adata[i], _ = pl.RPC_GetInfo() } } data = adata } else { iPV, _ := strconv.ParseInt(version, 10, 64) iFV, _ := strconv.ParseInt(fversion, 10, 64) iCV, _ := strconv.ParseInt(cversion, 10, 64) fight := player.GetFight() fver := 0 if fight != nil { fver = fight.Version() } fight.Unlock() cver := int64(0) cr := GetCreature(player.CurCreature) if cr != nil { cver = cr.Version } if iPV == player.Version && fver == int(iFV) && cver == iCV { data = "nochange" return } data, err = player.RPC_GetInfo() } return } if sURL == "gettechtree" { data, err = RPC_GetTechTree() return } if sURL == "nameplayer" { name := mParams.Get("name") err = player.NamePlayer(name) data = err == nil return } if sURL == "pquery" { data, err = player.RPC_PQuery() return } if sURL == "setpos" { lat, _ := strconv.ParseFloat(mParams.Get("lat"), 64) lon, _ := strconv.ParseFloat(mParams.Get("lon"), 64) err = player.RPC_SetPos(lat, lon) data = err == nil return } if sURL == "setbasepos" { baselat, _ := strconv.ParseFloat(mParams.Get("lat"), 64) baselon, _ := strconv.ParseFloat(mParams.Get("lon"), 64) err = player.RPC_SetBasePos(baselat, baselon) data = err == nil return } if sURL == "exchange" { element, _ := strconv.Atoi(mParams.Get("element")) level, _ := strconv.Atoi(mParams.Get("level")) count, _ := strconv.Atoi(mParams.Get("count")) exchangeMode, _ := strconv.Atoi(mParams.Get("exchangeMode")) lvldiff, _ := strconv.Atoi(mParams.Get("lvldiff")) err = player.RPC_RscExchange(element, level, count, exchangeMode, lvldiff) data = err != nil return } if sURL == "crcr" { element, _ := strconv.Atoi(mParams.Get("element")) data, err = player.RPC_CreateCreature(int64(element), int64(0), int64(rand.Intn(2))) return } if sURL == "namecr" { cid, _ := strconv.Atoi(mParams.Get("cid")) name := mParams.Get("name") data, err = player.NameCreature(int64(cid), name) return } if sURL == "getcrs" { data, err = player.RPC_GetCreatures() return } if sURL == "switchcurcr" { cid, _ := strconv.Atoi(mParams.Get("cid")) err = player.SwitchCurrentCreature(int64(cid)) return } if sURL == "addcrsl" { cid, _ := strconv.Atoi(mParams.Get("cid")) data, err = player.RPC_AddCreatureSlot(int64(cid)) return } if sURL == "upgradecrsl" { cid, _ := strconv.Atoi(mParams.Get("cid")) slotid, _ := strconv.Atoi(mParams.Get("slotid")) element, _ := strconv.Atoi(mParams.Get("element")) data, err = player.RPC_UpgradeCreatureSlot(int64(cid), int64(slotid), int64(element)) return } if sURL == "equipcrsl" { cid, _ := strconv.Atoi(mParams.Get("cid")) slotid, _ := strconv.Atoi(mParams.Get("slotid")) element, _ := strconv.Atoi(mParams.Get("element")) level, _ := strconv.Atoi(mParams.Get("level")) data, err = player.RPC_EquipCreatureSlot(int64(cid), int64(slotid), int64(element), int64(level)) return } if sURL == "unequipcrsl" { cid, _ := strconv.Atoi(mParams.Get("cid")) slotid, _ := strconv.Atoi(mParams.Get("slotid")) data, err = player.RPC_UnEquipCreatureSlot(int64(cid), int64(slotid)) return } if sURL == "poifarm" { data, err = player.RPC_PoiFarm(mParams.Get("mappos"), mParams.Get("poiid")) return } if sURL == "startspecialfight" { xp, _ := strconv.Atoi(mParams.Get("xp")) element, _ := strconv.Atoi(mParams.Get("element")) mid, _ := strconv.Atoi(mParams.Get("mid")) data, err = player.RPC_SpecialFight(int64(xp), int64(element), int64(mid)) return } if sURL == "fightcreate" { pother := mParams.Get("enemy") err = player.RPC_FightCreate(pother) data = err == nil return } if sURL == "accepted" { err = player.RPC_ChallengeAccepted() data = err == nil return } if sURL == "declined" { err = player.RPC_ChallengeDeclined() data = err == nil return } if sURL == "fightdelete" { err = player.RPC_FightDelete() data = err == nil return } if sURL == "fightpostmsg" { msg := mParams.Get("msg") err = player.RPC_FightPostMsg(msg) data = err == nil return } if sURL == "fightgetinfo" { msgsSince, _ := strconv.ParseInt(mParams.Get("msgsSince"), 10, 64) data, err = player.RPC_FightGetInfo(msgsSince) return } if sURL == "fightenemyturn" { playerTurn := false playerTurn, err = player.RPC_FightEnemyTurn() if playerTurn { data, _ = player.RPC_GetInfo() } else { data = false } return } if sURL == "fightplayerturn" { s0, _ := strconv.Atoi(mParams.Get("s0")) s1, _ := strconv.Atoi(mParams.Get("s1")) s2, _ := strconv.Atoi(mParams.Get("s2")) s3, _ := strconv.Atoi(mParams.Get("s3")) _, err = player.RPC_FightPlayerTurn(s0, s1, s2, s3) data, _ = player.RPC_GetInfo() return } if sURL == "catchcr" { level, _ := strconv.Atoi(mParams.Get("level")) _, err = player.RPC_CatchCreature(level) data = err != nil return } if sURL == "escape" { err = player.RPC_Escape() data = err != nil return } if sURL == "crtoven" { cid, _ := strconv.Atoi(mParams.Get("cid")) err = player.RPC_SendCreatureToVengea(cid) data = err != nil return } if sURL == "addxp" { xp, _ := strconv.ParseInt(mParams.Get("xp"), 10, 64) err = player.RPC_AddXP(xp) data = err != nil return } if sURL == "getpois" { lat, _ := strconv.ParseFloat(mParams.Get("lat"), 64) lon, _ := strconv.ParseFloat(mParams.Get("lon"), 64) data, err = player.RPC_GetPOIs(lat, lon) return } if sURL == "setinitsteps" { iSteps, _ := strconv.ParseInt(mParams.Get("v"), 10, 64) err = player.RPC_SetInitSteps(iSteps) data = err != nil return } if sURL == "settutorial" { tut, _ := strconv.ParseInt(mParams.Get("tut"), 10, 64) err = player.RPC_SetTutorial(tut) data = err != nil return } if sURL == "switchfaction" { err = player.RPC_Faction() data = err != nil return } if sURL == "setfaction" { fac, _ := strconv.ParseInt(mParams.Get("fac"), 10, 64) err = player.RPC_SetFaction(fac) data = err != nil return } if sURL == "setFirewall" { fiwa, _ := strconv.ParseBool(mParams.Get("fiwa")) err = player.RPC_SetFirewall(fiwa) data = err != nil return } if sURL == "base" { err := player.RPC_Base() data = err != nil return } err = errors.New("invalid_rpc") data = sURL }