func (ctf *ConnectionThrottleFilter) OnSessionOpened(s *netlib.Session) bool { if !ctf.isConnectionOk(s) { s.Close() return false } return true }
func (ssm *ServerSessionMgr) RegisteSession(s *netlib.Session) bool { attr := s.GetAttribute(SessionAttributeServerInfo) if attr != nil { if srvInfo, ok := attr.(*protocol.SSSrvRegiste); ok && srvInfo != nil { logger.Tracef("ServerSessionMgr.RegisteSession %v", srvInfo) areaId := int(srvInfo.GetAreaId()) srvType := int(srvInfo.GetType()) srvId := int(srvInfo.GetId()) if a, exist := ssm.sessions[areaId]; !exist { ssm.sessions[areaId] = make(map[int]map[int]*netlib.Session) a = ssm.sessions[areaId] a[srvType] = make(map[int]*netlib.Session) } else { if _, exist := a[srvType]; !exist { a[srvType] = make(map[int]*netlib.Session) } } ssm.sessions[areaId][srvType][srvId] = s if ssm.listener != nil { ssm.listener.OnRegiste(s) } } } else { logger.Tracef("ServerSessionMgr.RegisteSession SessionAttributeServerInfo=nil") } return true }
func (this *SessionHandlerServiceRegiste) OnSessionOpened(s *netlib.Session) { sc := s.GetSessionConfig() if sc.IsClient { /*报告自己的监听信息*/ srvlib.ServiceMgr.ReportService(s) } else { s.SetAttribute(srvlib.SessionAttributeServiceFlag, 1) } }
func (sfl *SessionHandlerSrvRegiste) OnSessionOpened(s *netlib.Session) { registePacket := &protocol.SSSrvRegiste{ Id: proto.Int(netlib.Config.SrvInfo.Id), Type: proto.Int(netlib.Config.SrvInfo.Type), AreaId: proto.Int(netlib.Config.SrvInfo.AreaID), Name: proto.String(netlib.Config.SrvInfo.Name), } proto.SetDefaults(registePacket) s.Send(registePacket) }
func (csm *ClientSessionMgr) RegisteSession(s *netlib.Session) bool { attr := s.GetAttribute(SessionAttributeClientSession) if attr == nil { sid := NewSessionId(s) s.SetAttribute(SessionAttributeClientSession, sid) csm.sessions[sid.Get()] = s logger.Tracef("client session %v registe", sid.Get()) } return true }
func (csm *ClientSessionMgr) UnregisteSession(s *netlib.Session) bool { attr := s.GetAttribute(SessionAttributeClientSession) if attr != nil { if sid, ok := attr.(SessionId); ok { delete(csm.sessions, sid.Get()) logger.Tracef("client session %v unregiste", sid.Get()) } } return true }
func (this *SCPacketPongHandler) Process(session *netlib.Session, data interface{}) error { if pong, ok := data.(*protocol.SCPacketPong); ok { ping := &protocol.CSPacketPing{ TimeStamb: proto.Int64(time.Now().Unix()), Message: pong.GetMessage(), } proto.SetDefaults(ping) session.Send(ping) } return nil }
func (sfcl *SessionHandlerClientLoad) reportLoad(s *netlib.Session) { sc := s.GetSessionConfig() pack := &protocol.ServerLoad{ SrvType: proto.Int32(int32(sc.Type)), SrvId: proto.Int32(int32(sc.Id)), CurLoad: proto.Int32(int32(srvlib.ClientSessionMgrSington.Count())), } proto.SetDefaults(pack) srvlib.ServerSessionMgrSington.Broadcast(pack, netlib.Config.SrvInfo.AreaID, srvlib.BalanceServerType) logger.Tracef("SessionHandlerClientLoad.reportLoad %v", pack) }
func (this *serviceMgr) ClearServiceBySession(s *netlib.Session) { attr := s.GetAttribute(SessionAttributeServiceInfo) if attr != nil { if services, ok := attr.([]*protocol.ServiceInfo); ok { for _, service := range services { this.UnregisteService(service) } } s.RemoveAttribute(SessionAttributeServiceInfo) } }
func (af *AuthenticationFilter) OnSessionOpened(s *netlib.Session) bool { timestamp := time.Now().Unix() h := md5.New() sc := s.GetSessionConfig() h.Write([]byte(fmt.Sprintf("%v;%v", timestamp, sc.AuthKey))) authPack := &protocol.SSPacketAuth{ Timestamp: proto.Int64(timestamp), AuthKey: proto.String(hex.EncodeToString(h.Sum(nil))), } proto.SetDefaults(authPack) s.Send(authPack) return true }
func (this *MulticastHandler) Process(s *netlib.Session, data interface{}) error { if mp, ok := data.(*protocol.SSPacketMulticast); ok { pd := mp.GetData() sis := mp.GetSessions() for _, si := range sis { ns := this.getSession(si) if ns != nil { ns.Send(pd, s.GetSessionConfig().IsInnerLink) } } } return nil }
func (blf *BlackListFilter) isBlock(s *netlib.Session) bool { host, _, err := net.SplitHostPort(s.RemoteAddr()) if err != nil { return true } ip := net.ParseIP(host) blf.lock.RLock() defer blf.lock.RUnlock() for e := blf.blacklist.Front(); e != nil; e = e.Next() { if e.Value.(*net.IPNet).Contains(ip) { return true } } return false }
func (ctf *ConnectionThrottleFilter) isConnectionOk(s *netlib.Session) bool { host, _, err := net.SplitHostPort(s.RemoteAddr()) if err != nil { return false } tNow := time.Now() value := ctf.clients.Get(host) if value != nil { tLast := value.(time.Time) if tNow.Sub(tLast) < time.Duration(ctf.AllowedInterval)*time.Millisecond { ctf.clients.Set(host, tNow) return false } } ctf.clients.Set(host, tNow) return true }
func (ssm *ServerSessionMgr) UnregisteSession(s *netlib.Session) bool { attr := s.GetAttribute(SessionAttributeServerInfo) if attr != nil { if srvInfo, ok := attr.(*protocol.SSSrvRegiste); ok && srvInfo != nil { logger.Tracef("ServerSessionMgr.UnregisteSession %v", srvInfo) areaId := int(srvInfo.GetAreaId()) srvType := int(srvInfo.GetType()) srvId := int(srvInfo.GetId()) if a, exist := ssm.sessions[areaId]; exist { if b, exist := a[srvType]; exist { delete(b, srvId) if ssm.listener != nil { ssm.listener.OnUnregiste(s) } } } } } return true }
func (this *serviceMgr) OnRegiste(s *netlib.Session) { if this == nil || s == nil { return } if s.GetAttribute(SessionAttributeServiceFlag) == nil { return } attr := s.GetAttribute(SessionAttributeServerInfo) if attr != nil { if srvInfo, ok := attr.(*protocol.SSSrvRegiste); ok && srvInfo != nil { services := GetCareServicesBySession(srvInfo.GetType()) for _, v1 := range services { if v2, has := this.servicesPool[v1]; has { for _, v3 := range v2 { func(si *protocol.ServiceInfo, sInfo *protocol.SSSrvRegiste) { pack := &protocol.SSServiceInfo{} proto.SetDefaults(pack) pack.Service = si logger.Trace("serviceMgr.OnRegiste Server Type=", sInfo.GetType(), " Id=", sInfo.GetId(), " Name=", sInfo.GetName(), " careful => Service=", si) s.Send(pack) }(v3, srvInfo) } } } } } }
func (sfcb *SessionHandlerClientBalance) OnSessionOpened(s *netlib.Session) { logger.Trace("SessionHandlerClientBalance.OnSessionOpened") services := srvlib.ServiceMgr.GetServices(srvlib.ClientServiceType) if services != nil { /*清理掉线的gate*/ for k, _ := range sfcb.gates { if _, has := services[k]; !has { delete(sfcb.gates, k) } } /*补充新上线的gate*/ for k, v := range services { if _, has := sfcb.gates[k]; !has { sfcb.gates[k] = &gateService{ServiceInfo: v, active: true} } } } /*查找最小负载的gate*/ var mls *libproto.ServiceInfo var min = 100000 for _, v := range sfcb.gates { if v.active && v.load < min { mls = v.ServiceInfo } } pack := &protocol.SCGateInfo{} if mls != nil { pack.SrvType = proto.Int32(mls.GetSrvType()) pack.SrvId = proto.Int32(mls.GetSrvId()) pack.AuthKey = proto.String(mls.GetAuthKey()) pack.Ip = proto.String(mls.GetIp()) pack.Port = proto.Int32(mls.GetPort()) } proto.SetDefaults(pack) s.Send(pack) time.AfterFunc(time.Second*5, func() { s.Close() }) }
func (this *PacketSlicesHandler) Process(s *netlib.Session, data interface{}) error { if packetslices, ok := data.(*protocol.SSPacketSlices); ok { seqNo := int(packetslices.GetSeqNo()) if seqNo < 1 { return errors.New("PacketSlicesHandler unexpect packet seq:" + strconv.Itoa(seqNo)) } totalSize := int(packetslices.GetTotalSize()) if totalSize > s.GetSessionConfig().MaxPacket { return errors.New("PacketSlicesHandler exceed MaxPacket size:" + strconv.Itoa(s.GetSessionConfig().MaxPacket) + " size=" + strconv.Itoa(totalSize)) } attr := s.GetAttribute(SessionAttributeBigBuf) if seqNo == 1 { if attr == nil { attr = bytes.NewBuffer(make([]byte, 0, packetslices.GetTotalSize())) s.SetAttribute(SessionAttributeBigBuf, attr) } } if seqNo > 1 { if attr == nil { return errors.New("PacketSlicesHandler Incorrect packet seq, expect seq=1") } } else if attr == nil { return errors.New("PacketSlicesHandler get bytesbuf failed") } buf := attr.(*bytes.Buffer) if seqNo == 1 { buf.Reset() } if buf.Len() != int(packetslices.GetOffset()) { return errors.New("PacketSlicesHandler get next packet offset error") } buf.Write(packetslices.GetPacketData()) if buf.Len() == totalSize { packetid, pck, err := netlib.UnmarshalPacket(buf.Bytes()) if err != nil { return err } h := netlib.GetHandler(packetid) if h != nil { h.Process(s, pck) } } } return nil }
func (this *serviceMgr) RegisteService(s *netlib.Session, services []*protocol.ServiceInfo) { if this == nil || services == nil || len(services) == 0 { return } s.SetAttribute(SessionAttributeServiceInfo, services) for _, service := range services { srvid := service.GetSrvId() srvtype := service.GetSrvType() if _, has := this.servicesPool[srvtype]; !has { this.servicesPool[srvtype] = make(map[int32]*protocol.ServiceInfo) } this.servicesPool[srvtype][srvid] = service pack := &protocol.SSServiceInfo{} pack.Service = service proto.SetDefaults(pack) sessiontypes := GetCareSessionsByService(service.GetSrvType()) areaId := service.GetAreaId() for _, v1 := range sessiontypes { ServerSessionMgrSington.Broadcast(pack, int(areaId), int(v1)) } } }
func NewSessionId(s *netlib.Session) SessionId { sc := s.GetSessionConfig() id := int64(sc.AreaId)<<SessionIdSrvAreaOffset | int64(sc.Type)<<SessionIdSrvTypeOffset | int64(sc.Id)<<SessionIdSrvIdOffset | int64(s.Id) return SessionId(id) }
func (af *AuthenticationFilter) OnPacketReceived(s *netlib.Session, packetid int, packet interface{}) bool { if s.GetAttribute(SessionAttributeAuth) == nil { if auth, ok := packet.(*protocol.SSPacketAuth); ok { h := md5.New() rawText := fmt.Sprintf("%v;%v", auth.GetTimestamp(), s.GetSessionConfig().AuthKey) logger.Tracef("AuthenticationFilter rawtext=%v IsInnerLink(%v)", rawText, s.GetSessionConfig().IsInnerLink) h.Write([]byte(rawText)) expectKey := hex.EncodeToString(h.Sum(nil)) if expectKey != auth.GetAuthKey() { if af.SessionAuthHandler != nil { af.SessionAuthHandler(s, false) } s.Close() logger.Tracef("AuthenticationFilter AuthKey error[expect:%v get:%v]", expectKey, auth.GetAuthKey()) return false } s.SetAttribute(SessionAttributeAuth, true) if af.SessionAuthHandler != nil { af.SessionAuthHandler(s, true) } return false } else { s.Close() logger.Warn("AuthenticationFilter packet not expect") return false } } return true }
func (blf *BlackListFilter) blockSession(s *netlib.Session) { s.Close() }
func (this *serviceMgr) ReportService(s *netlib.Session) { acceptors := netlib.GetAcceptors() cnt := len(acceptors) if cnt > 0 { pack := &protocol.SSServiceRegiste{ Services: make([]*protocol.ServiceInfo, 0, cnt), } proto.SetDefaults(pack) for _, v := range acceptors { addr := v.Addr() if addr == nil { continue } network := addr.Network() s := addr.String() ipAndPort := strings.Split(s, ":") if len(ipAndPort) < 2 { continue } port, err := strconv.Atoi(ipAndPort[len(ipAndPort)-1]) if err != nil { continue } sc := v.GetSessionConfig() si := &protocol.ServiceInfo{ AreaId: proto.Int32(int32(sc.AreaId)), SrvId: proto.Int32(int32(sc.Id)), SrvType: proto.Int32(int32(sc.Type)), SrvPID: proto.Int32(int32(os.Getpid())), SrvName: proto.String(sc.Name), NetworkType: proto.String(network), Ip: proto.String(sc.Ip), Port: proto.Int32(int32(port)), WriteTimeOut: proto.Int32(int32(sc.WriteTimeout / time.Second)), ReadTimeOut: proto.Int32(int32(sc.ReadTimeout / time.Second)), IdleTimeOut: proto.Int32(int32(sc.IdleTimeout / time.Second)), MaxDone: proto.Int32(int32(sc.MaxDone)), MaxPend: proto.Int32(int32(sc.MaxPend)), MaxPacket: proto.Int32(int32(sc.MaxPacket)), RcvBuff: proto.Int32(int32(sc.RcvBuff)), SndBuff: proto.Int32(int32(sc.SndBuff)), SoLinger: proto.Int32(int32(sc.SoLinger)), KeepAlive: proto.Bool(sc.KeepAlive), NoDelay: proto.Bool(sc.NoDelay), IsAutoReconn: proto.Bool(sc.IsAutoReconn), IsInnerLink: proto.Bool(sc.IsInnerLink), SupportFragment: proto.Bool(sc.SupportFragment), AllowMultiConn: proto.Bool(sc.AllowMultiConn), AuthKey: proto.String(sc.AuthKey), EncoderName: proto.String(sc.EncoderName), DecoderName: proto.String(sc.DecoderName), FilterChain: sc.FilterChain, HandlerChain: sc.HandlerChain, Protocol: proto.String(sc.Protocol), Path: proto.String(sc.Path), } pack.Services = append(pack.Services, si) } s.Send(pack) } }
func (this *SessionHandlerServiceRegiste) OnSessionClosed(s *netlib.Session) { sc := s.GetSessionConfig() if !sc.IsClient { srvlib.ServiceMgr.ClearServiceBySession(s) } }
func (kf *KeepAliveFilter) OnSessionIdle(s *netlib.Session) bool { p := &protocol.SSPacketKeepAlive{Flag: proto.Int32(0)} proto.SetDefaults(p) s.Send(p) return true }