Example #1
0
func (ctf *ConnectionThrottleFilter) OnSessionOpened(s *netlib.Session) bool {
	if !ctf.isConnectionOk(s) {
		s.Close()
		return false
	}
	return true
}
Example #2
0
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
}
Example #3
0
func (this *SessionHandlerServiceRegiste) OnSessionOpened(s *netlib.Session) {
	sc := s.GetSessionConfig()
	if sc.IsClient {
		/*报告自己的监听信息*/
		srvlib.ServiceMgr.ReportService(s)
	} else {
		s.SetAttribute(srvlib.SessionAttributeServiceFlag, 1)
	}
}
Example #4
0
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)
}
Example #5
0
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
}
Example #6
0
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
}
Example #7
0
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
}
Example #8
0
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)
}
Example #9
0
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)
	}
}
Example #10
0
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
}
Example #11
0
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
}
Example #12
0
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
}
Example #13
0
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
}
Example #14
0
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
}
Example #15
0
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)
					}
				}
			}
		}
	}
}
Example #16
0
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() })
}
Example #17
0
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
}
Example #18
0
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))
		}
	}
}
Example #19
0
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)
}
Example #20
0
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
}
Example #21
0
func (blf *BlackListFilter) blockSession(s *netlib.Session) {
	s.Close()
}
Example #22
0
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)
	}
}
Example #23
0
func (this *SessionHandlerServiceRegiste) OnSessionClosed(s *netlib.Session) {
	sc := s.GetSessionConfig()
	if !sc.IsClient {
		srvlib.ServiceMgr.ClearServiceBySession(s)
	}
}
Example #24
0
func (kf *KeepAliveFilter) OnSessionIdle(s *netlib.Session) bool {
	p := &protocol.SSPacketKeepAlive{Flag: proto.Int32(0)}
	proto.SetDefaults(p)
	s.Send(p)
	return true
}