public ReceivedChannelModeEventArgs(ServerBase server, ChannelBase channel, UserBase user, string argument) { Server = server; Channel = channel; User = user; Argument = argument; }
public Server(DomainManager domains, ServerBase cloneBase) : base(domains, cloneBase) { if (cloneBase is Server) { Server clone = (Server)cloneBase; Cache = clone.Cache; DirectRemotes = clone.DirectRemotes; RemoteInfo = clone.RemoteInfo; Remotes = clone.Remotes; Lines = clone.Lines; NetworkEstablished = clone.NetworkEstablished; Listeners = clone.Listeners; if (clone.SaveTimer.Change(Timeout.Infinite, Timeout.Infinite)) { clone.SaveTimer.Dispose(); } } SaveTimer = new Timer(SaveProc); Initialize(); }
public void ChannelReceiveMessage(ServerBase server, PacketRecieveMessagerArgs e) { try { HttpHeader hader = (HttpHeader)e.Message; Properties ps = new Properties(); ps.FromHeaders(hader.Properties); switch (hader.RequestType) { case Protocol.COMMAND_GET: OnGet(e.Channel, hader.Url, ps); break; case Protocol.COMMAND_GETINFO: OnGetInfo(e.Channel, hader.Url, ps); break; case Protocol.COMMAND_REGISTER: OnRegister(e.Channel, hader.Url, ps); break; default: break; } } catch (Exception e_) { Utils.Error<TrackerServer>("<{0}> message process error {1}", e.Message, e_.Message); HttpHeader header = Protocol.GetResponse(new Properties()); header.Action = "500 " + e_.Message; e.Channel.Send(header); } }
protected override void UpdateThis(ServerBase server) { base.UpdateThis(server); var details = server as Server; if (details == null) return; DiskConfig = details.DiskConfig; PowerState = details.PowerState; TaskState = details.TaskState; VMState = details.VMState; AccessIPv4 = details.AccessIPv4; AccessIPv6 = details.AccessIPv6; UserId = details.UserId; Image = details.Image; Status = details.Status; Flavor = details.Flavor; Addresses = details.Addresses; Created = details.Created; HostId = details.HostId; Progress = details.Progress; Bandwidth = details.Bandwidth; TenantId = details.TenantId; Updated = details.Updated; }
/// <summary> /// Override from ServerBase, to make sure we create the proper connection object for inbound connections. /// If we don't override this method, a generic InboundConnection class will be instantiated. /// </summary> protected override InboundConnection CreateInboundConnection(Socket s, ServerBase server, int serviceID, bool isBlocking) { if (serviceID == 7) { return new ZeusInboundConnection(s, server, isBlocking); } return new LSInboundConnection(s, server, isBlocking); }
/// <summary> /// Initializes the endpoint with a server instead of a host. /// </summary> protected EndpointBase(ServerBase server) { if (server == null) throw new ArgumentNullException("server"); m_host = null; m_server = server; SupportedServices = new Dictionary<ExpandedNodeId, ServiceDefinition>(); }
public void ChannelError(ServerBase server, ChannelErrorEventArgs e) { if (e.Exception.InnerException != null) { Log.ErrorFormat("{0} channel error {1} inner error {2}", e.Channel.EndPoint, e.Exception.Message, e.Exception.InnerException.Message); } else { Log.ErrorFormat("{0} channel error {1} ", e.Channel.EndPoint, e.Exception.Message); } }
protected override void UpdateThis(ServerBase server) { base.UpdateThis(server); var details = server as SimpleServer; if (details == null) return; Name = details.Name; }
/// <inheritdoc/> protected void UpdateThis(ServerBase server) { if (server == null) throw new ArgumentNullException("server"); var details = server as SimpleServer; if (details == null) return; Name = details.Name; }
protected override void UpdateThis(ServerBase server) { base.UpdateThis(server); var details = server as NewServer; if (details == null) return; DiskConfig = details.DiskConfig; AdminPassword = details.AdminPassword; }
/// <inheritdoc/> protected override void UpdateThis(ServerBase server) { if (server == null) throw new ArgumentNullException("server"); base.UpdateThis(server); var details = server as NewServer; if (details == null) return; DiskConfig = details.DiskConfig; AdminPassword = details.AdminPassword; }
/// <summary> /// Override from ServerBase, to make sure we create the proper connection object for inbound connections. /// If we don't override this method, a generic InboundConnection class will be instantiated. /// </summary> protected override InboundConnection CreateInboundConnection(Socket s, ServerBase server, int serviceID) { return new ZeusInboundConnection(s, server); }
public void OnDockServer(ServerBase server) { }
/// <summary> /// Override from ServerBase, to make sure we create the proper connection object for outgoing connections. /// If we don't override this method, a generic OutboundServerConnection class will be instantiated. /// </summary> public override OutboundServerConnection CreateOutboundServerConnection(string name, ServerBase server, string reportedIP, int serviceID) { return(new ZeusOutboundConnection(name, server, reportedIP)); }
/// <summary> /// Initializes a new instance of the <see cref="WindowsService"/> class. /// </summary> /// <param name="server">The server.</param> /// <param name="configSectionName">Name of the config section.</param> /// <param name="applicationType">Type of the application.</param> /// <param name="configurationType">Type of the configuration.</param> public WindowsService(ServerBase server, string configSectionName, ApplicationType applicationType, Type configurationType) { m_server = server; m_configSectionName = configSectionName; m_applicationType = applicationType; m_configurationType = configurationType; }
/// <summary> /// this method calll when client want to download file or stream from your server /// </summary> /// <param name="stream">client stream</param> /// <param name="client">client</param> private static async Task UploadStreamToClient(ClientInfo client, ServerBase serverBase) { MethodCallbackInfo callback = null; IStreamInfo streamInfo = null; PipeNetworkStream userStream = null; PipeNetworkStream stream = client.ClientStream; bool isCallbackSended = false; try { byte[] bytes = await client.StreamHelper.ReadBlockToEndAsync(client.ClientStream, CompressMode.None, serverBase.ProviderSetting.MaximumReceiveStreamHeaderBlock); string json = Encoding.UTF8.GetString(bytes); MethodCallInfo callInfo = ServerSerializationHelper.Deserialize <MethodCallInfo>(json, serverBase); CallMethodResultInfo <OperationContext> result = await CallMethod(callInfo.ServiceName, callInfo.Guid, callInfo.MethodName, callInfo.Parameters, null, client, null, serverBase, null, null); callback = result.CallbackInfo; streamInfo = result.StreamInfo; userStream = streamInfo.Stream; long len = streamInfo.Length.GetValueOrDefault(); await SendCallbackData(callback, client, serverBase); isCallbackSended = true; long writeLen = 0; while (writeLen < len) { bytes = new byte[1024 * 100]; int readCount = await userStream.ReadAsync(bytes, bytes.Length); byte[] sendBytes = bytes.Take(readCount).ToArray(); await stream.WriteAsync(sendBytes, 0, sendBytes.Length); writeLen += readCount; } userStream.Dispose(); Console.WriteLine("user stream finished"); stream.Dispose(); } catch (Exception ex) { if (streamInfo != null) { streamInfo.Dispose(); } stream.Dispose(); if (userStream != null) { userStream.Dispose(); Console.WriteLine("user stream disposed"); } if (!isCallbackSended && !client.ClientStream.IsClosed) { if (callback == null) { callback = new MethodCallbackInfo(); } callback.IsException = true; callback.Data = ServerSerializationHelper.SerializeObject(ex); await SendCallbackData(callback, client, serverBase); } } finally { //MethodsCallHandler.EndStreamCallAction?.Invoke(client, guid, serviceName, methodName, values, jsonResult, exception); } }
public WorldClient(ServerBase srv) : base(srv) { this.rServer = srv; }
public void ChannelCreated(ServerBase server, ChannelEventArgs e) { Utils.GetLog<TrackerServer>().InfoFormat("{0} Connected TrackerServer", e.Channel.EndPoint); }
/// <summary> /// Initializes a new instance of the <see cref="DiscoveryEndpoint"/> class. /// </summary> /// <param name="server">The server.</param> public DiscoveryEndpoint(ServerBase server) : base(server) { this.CreateKnownTypes(); }
public SignalGoOwinMiddleware(OwinMiddleware owinMiddleware, ServerBase serverBase) : base(owinMiddleware) { CurrentServerBase = serverBase; }
public CentralLobbyInboundLoginConnection(Socket s, ServerBase server, bool isBlocking) : base(s, server, isBlocking) { }
public void OnDockServer(ServerBase server) { MessageBox.Show("OnDockServer", "Plugin.Sample event", MessageBoxButtons.OK, MessageBoxIcon.Information); }
/// <summary> /// </summary> /// <param name="server"> /// </param> /// <param name="messageSerializer"> /// </param> /// <param name="bus"> /// </param> public Client(ServerBase server, IMessageSerializer messageSerializer, IBus bus) : base(server) { this.messageSerializer = messageSerializer; this.bus = bus; }
/// <inheritdoc/> /// <summary> /// Create a new service host for UA HTTPS. /// </summary> public List <EndpointDescription> CreateServiceHost( ServerBase serverBase, IDictionary <string, ServiceHost> hosts, ApplicationConfiguration configuration, IList <string> baseAddresses, ApplicationDescription serverDescription, List <ServerSecurityPolicy> securityPolicies, X509Certificate2 instanceCertificate, X509Certificate2Collection instanceCertificateChain ) { // generate a unique host name. string hostName = hostName = "/Https"; if (hosts.ContainsKey(hostName)) { hostName += Utils.Format("/{0}", hosts.Count); } // build list of uris. List <Uri> uris = new List <Uri>(); EndpointDescriptionCollection endpoints = new EndpointDescriptionCollection(); // create the endpoint configuration to use. EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration); string computerName = Utils.GetHostName(); for (int ii = 0; ii < baseAddresses.Count; ii++) { if (!baseAddresses[ii].StartsWith(Utils.UriSchemeHttps, StringComparison.Ordinal)) { continue; } UriBuilder uri = new UriBuilder(baseAddresses[ii]); if (uri.Path[uri.Path.Length - 1] != '/') { uri.Path += "/"; } if (String.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) { uri.Host = computerName; } uris.Add(uri.Uri); if (uri.Scheme == Utils.UriSchemeHttps) { // Can only support one policy with HTTPS // So pick the first policy with security mode sign and encrypt ServerSecurityPolicy bestPolicy = null; foreach (ServerSecurityPolicy policy in securityPolicies) { if (policy.SecurityMode != MessageSecurityMode.SignAndEncrypt) { continue; } bestPolicy = policy; break; } // Pick the first policy from the list if no policies with sign and encrypt defined if (bestPolicy == null) { bestPolicy = securityPolicies[0]; } EndpointDescription description = new EndpointDescription(); description.EndpointUrl = uri.ToString(); description.Server = serverDescription; if (instanceCertificate != null) { description.ServerCertificate = instanceCertificate.RawData; // check if complete chain should be sent. if (configuration.SecurityConfiguration.SendCertificateChain && instanceCertificateChain != null && instanceCertificateChain.Count > 0) { List <byte> serverCertificateChain = new List <byte>(); for (int i = 0; i < instanceCertificateChain.Count; i++) { serverCertificateChain.AddRange(instanceCertificateChain[i].RawData); } description.ServerCertificate = serverCertificateChain.ToArray(); } } description.SecurityMode = bestPolicy.SecurityMode; description.SecurityPolicyUri = bestPolicy.SecurityPolicyUri; description.SecurityLevel = ServerSecurityPolicy.CalculateSecurityLevel(bestPolicy.SecurityMode, bestPolicy.SecurityPolicyUri); description.UserIdentityTokens = serverBase.GetUserTokenPolicies(configuration, description); description.TransportProfileUri = Profiles.HttpsBinaryTransport; ITransportListener listener = Create(); if (listener != null) { endpoints.Add(description); serverBase.CreateServiceHostEndpoint(uri.Uri, endpoints, endpointConfiguration, listener, configuration.CertificateValidator.GetChannelValidator()); } else { Utils.LogError("Failed to create endpoint {0} because the transport profile is unsupported.", uri); } } // create the host. ServiceHost serviceHost = serverBase.CreateServiceHost(serverBase, uris.ToArray()); hosts[hostName] = serviceHost; } return(endpoints); }
public void ChannelError(ServerBase server, ChannelErrorEventArgs e) { Utils.Error<TrackerServer>(e.Exception, "TrackerServer Channel {1} Error {0}", e.Exception.Message, e.Channel.EndPoint); }
public void ChannelDisconnect(ServerBase server, ChannelDisposedEventArgs e) { Utils.GetLog<TrackerServer>().InfoFormat("{0} Discontected TrackerServer", e.Channel.EndPoint); }
public ZeusPatchInboundZeusConnection(Socket s, ServerBase server, bool isBlocking) : base(s, server, isBlocking) { // Register Packet handlers that should be accepted for all connection, regardless if they are authenticated or not. // use "RegisterPacketHandler(..." }
public static T Deserialize <T>(this string json, ServerBase serverBase = null) { return((T)Deserialize(json, typeof(T), serverBase)); }
/// <summary> /// Returns an instance of the endpoint to use. /// </summary> protected virtual EndpointBase GetEndpointInstance(ServerBase server) { return null; }
public static object Deserialize(this string json, ServerBase serverBase = null) { return(Deserialize <object>(json, serverBase)); }
/// <summary> /// Override from ServerBase, to make sure we create the proper connection object for outgoing connections. /// If we don't override this method, a generic OutboundServerConnection class will be instantiated. /// </summary> public override OutboundServerConnection CreateOutboundServerConnection(string name, ServerBase server, string reportedIP, int serviceID, bool isBlocking) { return new LSOutboundConnection(name, server, reportedIP, isBlocking); }
public static async Task StartToReadingClientData(TcpClient tcpClient, ServerBase serverBase, PipeNetworkStream reader, StringBuilder builder) { //Console.WriteLine($"Http Client Connected: {((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString().Replace("::ffff:", "")}"); ClientInfo client = null; try { while (true) { string line = await reader.ReadLineAsync(); builder.Append(line); if (line == TextHelper.NewLine) { break; } } string requestHeaders = builder.ToString(); if (requestHeaders.Contains("Sec-WebSocket-Key")) { tcpClient.ReceiveTimeout = -1; tcpClient.SendTimeout = -1; client = serverBase.ServerDataProvider.CreateClientInfo(false, tcpClient, reader); client.ProtocolType = ClientProtocolType.WebSocket; client.IsWebSocket = true; string key = requestHeaders.Replace("ey:", "`").Split('`')[1].Replace("\r", "").Split('\n')[0].Trim(); string acceptKey = AcceptKey(ref key); string newLine = TextHelper.NewLine; //var response = "HTTP/1.1 101 Switching Protocols" + newLine string response = "HTTP/1.0 101 Switching Protocols" + newLine + "Upgrade: websocket" + newLine + "Connection: Upgrade" + newLine + "Sec-WebSocket-Accept: " + acceptKey + newLine + newLine; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(response); await client.ClientStream.WriteAsync(bytes, 0, bytes.Length); client.StreamHelper = SignalGoStreamBase.CurrentBase; client.ClientStream = new PipeNetworkStream(new WebSocketStream(client.TcpClient.GetStream())); if (requestHeaders.Contains("SignalgoDuplexWebSocket")) { await SignalGoDuplexServiceProvider.StartToReadingClientData(client, serverBase); } else { //client.StreamHelper = SignalGoStreamWebSocketLlight.CurrentWebSocket; //client.ClientStream = new PipeNetworkStream(new WebSocketStream(client.TcpClient.GetStream())); //await WebSocketProvider.StartToReadingClientData(client, serverBase); await HttpProvider.AddWebSocketHttpClient(client, serverBase); } } else if (requestHeaders.Contains("SignalGoHttpDuplex")) { client = serverBase.ServerDataProvider.CreateClientInfo(false, tcpClient, reader); client.ProtocolType = ClientProtocolType.HttpDuplex; client.StreamHelper = SignalGoStreamBase.CurrentBase; await SignalGoDuplexServiceProvider.StartToReadingClientData(client, serverBase); } else { try { //serverBase.TaskOfClientInfoes client = (HttpClientInfo)serverBase.ServerDataProvider.CreateClientInfo(true, tcpClient, reader); client.ProtocolType = ClientProtocolType.Http; client.StreamHelper = SignalGoStreamBase.CurrentBase; string[] lines = null; if (requestHeaders.Contains(TextHelper.NewLine + TextHelper.NewLine)) { lines = requestHeaders.Substring(0, requestHeaders.IndexOf(TextHelper.NewLine + TextHelper.NewLine)).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); } else { lines = requestHeaders.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); } if (lines.Length > 0) { string methodName = GetHttpMethodName(lines[0]); string address = GetHttpAddress(lines[0]); if (requestHeaders != null) { ((HttpClientInfo)client).RequestHeaders = SignalGo.Shared.Http.WebHeaderCollection.GetHttpHeaders(lines.Skip(1).ToArray()); } await HandleHttpRequest(methodName, address, serverBase, (HttpClientInfo)client); } else { serverBase.DisposeClient(client, tcpClient, "HttpProvider StartToReadingClientData no line detected"); } } catch { serverBase.DisposeClient(client, tcpClient, "HttpProvider StartToReadingClientData exception"); } } } catch (Exception ex) { //if (client != null) //serverBase.AutoLogger.LogError(ex, $"{client.IPAddress} {client.ClientId} ServerBase HttpProvider StartToReadingClientData"); serverBase.DisposeClient(client, tcpClient, "HttpProvider StartToReadingClientData exception 2"); } }
internal string SendMethodParameterDetail(Type serviceType, MethodParameterDetails detail, ServerBase serverBase) { string json = null; foreach (MethodInfo method in serviceType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)) { if (method.IsSpecialName && (method.Name.StartsWith("set_") || method.Name.StartsWith("get_"))) { continue; } if (method.Name == detail.MethodName && detail.ParametersCount == method.GetParameters().Length) { Type parameterType = method.GetParameters()[detail.ParameterIndex].ParameterType; if (detail.IsFull) { json = TypeToJsonString(parameterType); } else { json = SimpleTypeToJsonString(parameterType); } break; } } if (json == null) { throw new Exception("method or parameter not found"); } return(json); }
public static Task AddHttpClient(HttpClientInfo client, ServerBase serverBase, string address, string methodName, IDictionary <string, string[]> requestHeaders, IDictionary <string, string[]> responseHeaders)
/// <summary> /// Override from ServerBase, to make sure we create the proper connection object for inbound connections. /// If we don't override this method, a generic InboundConnection class will be instantiated. /// </summary> protected override InboundConnection CreateInboundConnection(Socket s, ServerBase server, int serviceID) { return(new ZeusInboundConnection(s, server)); }
public static Task AddSignalGoWebSocketHttpClient(ClientInfo client, ServerBase serverBase)
/// <summary> /// Starts the UA server. /// </summary> /// <param name="server">The server.</param> public async Task Start(ServerBase server) { m_server = server; if (m_applicationConfiguration == null) { await LoadApplicationConfiguration(false); } if (m_applicationConfiguration.SecurityConfiguration != null && m_applicationConfiguration.SecurityConfiguration.AutoAcceptUntrustedCertificates) { m_applicationConfiguration.CertificateValidator.CertificateValidation += CertificateValidator_CertificateValidation; } server.Start(m_applicationConfiguration); }
public WispServiceOutboundServerConnection(string name, ServerBase server, string reportedIP, bool isBlocking) : base(name, server, reportedIP, isBlocking) { }
/// <summary> /// Override from ServerBase, to make sure we create the proper connection object for outgoing connections. /// If we don't override this method, a generic OutboundServerConnection class will be instantiated. /// </summary> public override OutboundServerConnection CreateOutboundServerConnection(string name, ServerBase server, string reportedIP, int serviceID) { return new ZeusOutboundConnection(name, server, reportedIP); }
/// <summary> /// Validates the identity token supplied by the client. /// </summary> private UserIdentityToken ValidateUserIdentityToken( ExtensionObject identityToken, SignatureData userTokenSignature, out UserTokenPolicy policy) { policy = null; // check for empty token. if (identityToken == null || identityToken.Body == null) { // not changing the token if already activated. if (m_activated) { return(null); } // check if an anonymous login is permitted. if (m_endpoint.UserIdentityTokens != null && m_endpoint.UserIdentityTokens.Count > 0) { bool found = false; for (int ii = 0; ii < m_endpoint.UserIdentityTokens.Count; ii++) { if (m_endpoint.UserIdentityTokens[ii].TokenType == UserTokenType.Anonymous) { found = true; policy = m_endpoint.UserIdentityTokens[ii]; break; } } if (!found) { throw ServiceResultException.Create(StatusCodes.BadUserAccessDenied, "Anonymous user token policy not supported."); } } // create an anonymous token to use for subsequent validation. AnonymousIdentityToken anonymousToken = new AnonymousIdentityToken(); anonymousToken.PolicyId = policy.PolicyId; return(anonymousToken); } UserIdentityToken token = null; // check for unrecognized token. if (!typeof(UserIdentityToken).IsInstanceOfType(identityToken.Body)) { //handle the use case when the UserIdentityToken is binary encoded over xml message encoding if (identityToken.Encoding == ExtensionObjectEncoding.Binary && typeof(byte[]).IsInstanceOfType(identityToken.Body)) { UserIdentityToken newToken = BaseVariableState.DecodeExtensionObject(null, typeof(UserIdentityToken), identityToken, false) as UserIdentityToken; if (newToken == null) { throw ServiceResultException.Create(StatusCodes.BadUserAccessDenied, "Invalid user identity token provided."); } policy = m_endpoint.FindUserTokenPolicy(newToken.PolicyId); if (policy == null) { throw ServiceResultException.Create(StatusCodes.BadUserAccessDenied, "User token policy not supported.", "Opc.Ua.Server.Session.ValidateUserIdentityToken"); } switch (policy.TokenType) { case UserTokenType.Anonymous: token = BaseVariableState.DecodeExtensionObject(null, typeof(AnonymousIdentityToken), identityToken, true) as AnonymousIdentityToken; break; case UserTokenType.UserName: token = BaseVariableState.DecodeExtensionObject(null, typeof(UserNameIdentityToken), identityToken, true) as UserNameIdentityToken; break; case UserTokenType.Certificate: token = BaseVariableState.DecodeExtensionObject(null, typeof(X509IdentityToken), identityToken, true) as X509IdentityToken; break; case UserTokenType.IssuedToken: token = BaseVariableState.DecodeExtensionObject(null, typeof(IssuedIdentityToken), identityToken, true) as IssuedIdentityToken; break; default: throw ServiceResultException.Create(StatusCodes.BadUserAccessDenied, "Invalid user identity token provided."); } } else { throw ServiceResultException.Create(StatusCodes.BadUserAccessDenied, "Invalid user identity token provided."); } } else { // get the token. token = (UserIdentityToken)identityToken.Body; } // find the user token policy. policy = m_endpoint.FindUserTokenPolicy(token.PolicyId); if (policy == null) { throw ServiceResultException.Create(StatusCodes.BadIdentityTokenInvalid, "User token policy not supported."); } // determine the security policy uri. string securityPolicyUri = policy.SecurityPolicyUri; if (String.IsNullOrEmpty(securityPolicyUri)) { securityPolicyUri = m_endpoint.SecurityPolicyUri; } if (ServerBase.RequireEncryption(m_endpoint)) { // decrypt the token. if (m_serverCertificate == null) { m_serverCertificate = CertificateFactory.Create(m_endpoint.ServerCertificate, true); // check for valid certificate. if (m_serverCertificate == null) { throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate cannot be found."); } } try { token.Decrypt(m_serverCertificate, m_serverNonce, securityPolicyUri); } catch (Exception e) { if (e is ServiceResultException) { throw; } throw ServiceResultException.Create(StatusCodes.BadIdentityTokenInvalid, e, "Could not decrypt identity token."); } // verify the signature. if (securityPolicyUri != SecurityPolicies.None) { byte[] dataToSign = Utils.Append(m_serverCertificate.RawData, m_serverNonce); if (!token.Verify(dataToSign, userTokenSignature, securityPolicyUri)) { throw new ServiceResultException(StatusCodes.BadUserSignatureInvalid, "Invalid user signature!"); } } } // validate user identity token. return(token); }
public static async Task StartToReadingClientData(ClientInfo client, ServerBase serverBase) { try { Console.WriteLine($"Duplex Client Connected: {client.IPAddress}"); PipeNetworkStream stream = client.ClientStream; while (true) { byte oneByteOfDataType = await client.StreamHelper.ReadOneByteAsync(stream); //type of data DataType dataType = (DataType)oneByteOfDataType; if (dataType == DataType.PingPong) { await client.StreamHelper.WriteToStreamAsync(client.ClientStream, new byte[] { 5 }); continue; } //compress mode of data CompressMode compressMode = (CompressMode)await client.StreamHelper.ReadOneByteAsync(stream); //a server service method called from client if (dataType == DataType.CallMethod) { byte[] bytes = await client.StreamHelper.ReadBlockToEndAsync(stream, compressMode, serverBase.ProviderSetting.MaximumReceiveDataBlock); //if (ClientsSettings.ContainsKey(client)) // bytes = DecryptBytes(bytes, client); string json = Encoding.UTF8.GetString(bytes); MethodCallInfo callInfo = ServerSerializationHelper.Deserialize <MethodCallInfo>(json, serverBase); if (callInfo.PartNumber != 0) { SegmentManager segmentManager = new SegmentManager(); ISegment result = segmentManager.GenerateAndMixSegments(callInfo); if (result != null) { callInfo = (MethodCallInfo)result; } else { continue; } } Task <MethodCallbackInfo> callbackResult = CallMethod(callInfo, client, json, serverBase); SendCallbackDataAsync(callbackResult, client, serverBase); } //reponse of client method that server called to client else if (dataType == DataType.ResponseCallMethod) { byte[] bytes = await client.StreamHelper.ReadBlockToEndAsync(stream, compressMode, serverBase.ProviderSetting.MaximumReceiveDataBlock); //if (ClientsSettings.ContainsKey(client)) // bytes = DecryptBytes(bytes, client); string json = Encoding.UTF8.GetString(bytes); MethodCallbackInfo callback = ServerSerializationHelper.Deserialize <MethodCallbackInfo>(json, serverBase); if (callback == null) { serverBase.AutoLogger.LogText($"{client.IPAddress} {client.ClientId} callback is null:" + json); } if (callback.PartNumber != 0) { SegmentManager segmentManager = new SegmentManager(); ISegment result = segmentManager.GenerateAndMixSegments(callback); if (result != null) { callback = (MethodCallbackInfo)result; } else { continue; } } if (serverBase.ClientServiceCallMethodsResult.TryGetValue(callback.Guid, out KeyValue <Type, object> resultTask)) { if (callback.IsException) { resultTask.Value.GetType().FindMethod("SetException").Invoke(resultTask.Value, new object[] { new Exception(callback.Data) }); } else { resultTask.Value.GetType().FindMethod("SetResult").Invoke(resultTask.Value, new object[] { ServerSerializationHelper.Deserialize(callback.Data, resultTask.Key, serverBase) }); } } } else if (dataType == DataType.GetServiceDetails) { byte[] bytes = await client.StreamHelper.ReadBlockToEndAsync(stream, compressMode, serverBase.ProviderSetting.MaximumReceiveDataBlock); //if (ClientsSettings.ContainsKey(client)) // bytes = DecryptBytes(bytes, client); string json = Encoding.UTF8.GetString(bytes); string hostUrl = ServerSerializationHelper.Deserialize <string>(json, serverBase); ServerServicesManager serverServicesManager = new ServerServicesManager(); ProviderDetailsInfo detail = serverServicesManager.SendServiceDetail(hostUrl, serverBase); json = ServerSerializationHelper.SerializeObject(detail, serverBase); List <byte> resultBytes = new List <byte> { (byte)DataType.GetServiceDetails, (byte)CompressMode.None }; byte[] jsonBytes = Encoding.UTF8.GetBytes(json); byte[] dataLen = BitConverter.GetBytes(jsonBytes.Length); resultBytes.AddRange(dataLen); resultBytes.AddRange(jsonBytes); await client.StreamHelper.WriteToStreamAsync(client.ClientStream, resultBytes.ToArray()); } else if (dataType == DataType.GetMethodParameterDetails) { byte[] bytes = await client.StreamHelper.ReadBlockToEndAsync(stream, compressMode, serverBase.ProviderSetting.MaximumReceiveDataBlock); //if (ClientsSettings.ContainsKey(client)) // bytes = DecryptBytes(bytes, client); string json = Encoding.UTF8.GetString(bytes); MethodParameterDetails detail = ServerSerializationHelper.Deserialize <MethodParameterDetails>(json, serverBase); if (!serverBase.RegisteredServiceTypes.TryGetValue(detail.ServiceName, out Type serviceType)) { throw new Exception($"{client.IPAddress} {client.ClientId} Service {detail.ServiceName} not found"); } if (serviceType == null) { throw new Exception($"{client.IPAddress} {client.ClientId} serviceType {detail.ServiceName} not found"); } ServerServicesManager serverServicesManager = new ServerServicesManager(); json = serverServicesManager.SendMethodParameterDetail(serviceType, detail, serverBase); List <byte> resultBytes = new List <byte> { (byte)DataType.GetMethodParameterDetails, (byte)CompressMode.None }; byte[] jsonBytes = Encoding.UTF8.GetBytes(json); byte[] dataLen = BitConverter.GetBytes(jsonBytes.Length); resultBytes.AddRange(dataLen); resultBytes.AddRange(jsonBytes); await client.StreamHelper.WriteToStreamAsync(client.ClientStream, resultBytes.ToArray()); } else if (dataType == DataType.GetClientId) { byte[] bytes = Encoding.UTF8.GetBytes(client.ClientId); //if (ClientsSettings.ContainsKey(client)) // bytes = EncryptBytes(bytes, client); byte[] len = BitConverter.GetBytes(bytes.Length); List <byte> data = new List <byte> { (byte)DataType.GetClientId, (byte)CompressMode.None }; data.AddRange(len); data.AddRange(bytes); if (data.Count > serverBase.ProviderSetting.MaximumSendDataBlock) { throw new Exception($"{client.IPAddress} {client.ClientId} GetClientId data length exceeds MaximumSendDataBlock"); } await client.StreamHelper.WriteToStreamAsync(client.ClientStream, data.ToArray()); } else { //throw new Exception($"Correct DataType Data {dataType}"); serverBase.AutoLogger.LogText($"Correct DataType Data {oneByteOfDataType} {client.ClientId} {client.IPAddress}"); break; } } serverBase.DisposeClient(client, null, "StartToReadingClientData while break"); } catch (Exception ex) { serverBase.AutoLogger.LogError(ex, $"{client.IPAddress} {client.ClientId} ServerBase SignalGoDuplexServiceProvider StartToReadingClientData"); serverBase.DisposeClient(client, null, "SignalGoDuplexServiceProvider StartToReadingClientData exception"); } }
/// <inheritdoc/> public ApplicationConfiguration CreateServer(IEnumerable <int> ports, out ServerBase server) { server = new Server(LogStatus, _nodes, _logger); return(Server.CreateServerConfiguration(ports)); }
/// <summary> /// Create a connection object for an incoming connections. Should be overridden. /// </summary> protected virtual InboundConnection CreateInboundConnection(Socket s, ServerBase server, int serviceID, bool isBlocking) { if (serviceID == 7) // 7eus { ZeusInboundConnection zcon = new ZeusInboundConnection(s, server, isBlocking); return zcon; } InboundConnection newClient = new InboundConnection(s, server, isBlocking); return newClient; }
/// <inheritdoc/> protected override void UpdateThis(ServerBase server) { if (server == null) throw new ArgumentNullException("server"); base.UpdateThis(server); var details = server as Server; if (details == null) return; DiskConfig = details.DiskConfig; PowerState = details.PowerState; TaskState = details.TaskState; VMState = details.VMState; AccessIPv4 = details.AccessIPv4; AccessIPv6 = details.AccessIPv6; UserId = details.UserId; Image = details.Image; Status = details.Status; Flavor = details.Flavor; Addresses = details.Addresses; Created = details.Created; HostId = details.HostId; Progress = details.Progress; TenantId = details.TenantId; Updated = details.Updated; }
public ProxyDynamicFactory(Type type) { chan = Build(type) as ServerBase; }
/// <summary> /// Initializes a new instance of the <see cref="RequestQueue"/> class. /// </summary> /// <param name="server">The server.</param> /// <param name="minThreadCount">The minimum number of threads in the pool.</param> /// <param name="maxThreadCount">The maximum number of threads in the pool.</param> /// <param name="maxRequestCount">The maximum number of requests that will placed in the queue.</param> public RequestQueue(ServerBase server, int minThreadCount, int maxThreadCount, int maxRequestCount) { m_server = server; m_queue = new Queue<IEndpointIncomingRequest>(); m_minThreadCount = minThreadCount; m_maxThreadCount = maxThreadCount; m_maxRequestCount = maxRequestCount; m_totalThreadCount = 0; m_activeThreadCount = 0; m_stopped = false; }
public void Init(IServer server, IProtoSerializer serializer) { m_serializer = serializer; m_server = server as ServerBase; m_server.onReceived = OnReceived; }
/// <summary> /// Override this method to create the correct connection object for connecting to another server in the Hive /// given the service request ID listed in the App.Config. /// Once the appropriate connection is created, it takes over the handshaking and communication. /// </summary> public override OutboundServerConnection CreateOutboundServerConnection(string name, ServerBase server, string reportedIP, int serviceID, bool isBlocking) { switch (serviceID) { default: return(new BeholderOutboundServerConnection(name, server, reportedIP, isBlocking)); } }
private static bool _IsHandlingException; // Make sure we don't go recursive on ourself //could move our main function into OpenSimMain and kill this class public static void BaseMain(string[] args) { // First line, hook the appdomain to the crash reporter AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Add the arguments supplied when running the application to the configuration ArgvConfigSource configSource = new ArgvConfigSource(args); // Decide if we're in server mode ISimulationBase simBase; string defaultIniFile; configSource.AddSwitch("Startup","server"); if (configSource.Configs["Startup"].Contains("server")) { simBase = new ServerBase(); defaultIniFile = "Aurora.Server.ini"; } else { simBase = new SimulationBase(); defaultIniFile = "Aurora.ini"; } // Configure Log4Net configSource.AddSwitch("Startup", "logconfig"); string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty); if (logConfigFile != String.Empty) XmlConfigurator.Configure(new FileInfo(logConfigFile)); else XmlConfigurator.Configure(); // Increase the number of IOCP threads available. Mono defaults to a tragically low number int workerThreads, iocpThreads; ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); //MainConsole.Instance.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} worker threads and {1} IOCP threads", workerThreads, iocpThreads); if (workerThreads < 500 || iocpThreads < 1000) { workerThreads = 500; iocpThreads = 1000; //MainConsole.Instance.Info("[OPENSIM MAIN]: Bumping up to 500 worker threads and 1000 IOCP threads"); ThreadPool.SetMaxThreads(workerThreads, iocpThreads); } // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met //MainConsole.Instance.Info("[Setup]: Performing compatibility checks... \n"); string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { int minWorker, minIOC; // Get the current settings. ThreadPool.GetMinThreads(out minWorker, out minIOC); //MainConsole.Instance.InfoFormat("[Setup]: Environment is compatible. Thread Workers: {0}, IO Workers {1}\n", minWorker, minIOC); } else { MainConsole.Instance.Warn("[Setup]: Environment is unsupported (" + supported + ")\n"); #if BlockUnsupportedVersions Thread.Sleep(10000); //Sleep 10 seconds return; #endif } BinMigratorService service = new BinMigratorService(); service.MigrateBin(); // Configure nIni aliases and localles Culture.SetCurrentCulture(); configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); ///Command line switches configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inigrid"); configSource.AddSwitch("Startup", "inisim"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "oldoptions"); configSource.AddSwitch("Startup", "inishowfileloading"); configSource.AddSwitch("Startup", "mainIniDirectory"); configSource.AddSwitch("Startup", "mainIniFileName"); configSource.AddSwitch("Startup", "secondaryIniFileName"); configSource.AddConfig("Network"); IConfigSource m_configSource = Configuration(configSource, defaultIniFile); // Check if we're saving crashes m_saveCrashDumps = m_configSource.Configs["Startup"].GetBoolean("save_crashes", m_saveCrashDumps); // load Crash directory config m_crashDir = m_configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); // check auto restart bool AutoRestart = m_configSource.Configs["Startup"].GetBoolean("AutoRestartOnCrash", true); //Set up the error reporting if (m_configSource.Configs["ErrorReporting"] != null) { m_sendErrorReport = m_configSource.Configs["ErrorReporting"].GetBoolean("SendErrorReports", true); m_urlToPostErrors = m_configSource.Configs["ErrorReporting"].GetString("ErrorReportingURL", m_urlToPostErrors); } bool Running = true; //If auto restart is set, then we always run. // otherwise, just run the first time that Running == true while (AutoRestart || Running) { //Always run once, then disable this Running = false; //Initialize the sim base now Startup(configSource, m_configSource, simBase.Copy(), args); } }
/// <summary> /// Override from ServerBase, to make sure we create the proper connection object for inbound connections. /// If we don't override this method, a generic InboundConnection class will be instantiated. /// </summary> protected override InboundConnection CreateInboundConnection(Socket s, ServerBase server, int serviceID, bool isBlocking) { return(new ZeusInboundZeusConnection(s, server, isBlocking)); }
/// <summary> /// Creates an instance of the service host. /// </summary> protected virtual ServiceHost CreateServiceHost(ServerBase server, params Uri[] addresses) { return null; }
protected ChannelBase(ServerBase server, string name, string id) : base(name, id) { Server = server; Users = new Dictionary<string, UserBase>(); }
/// <summary> /// Returns an instance of the endpoint to use. /// </summary> protected override EndpointBase GetEndpointInstance(ServerBase server) { return new SessionEndpoint(server); }
public IUserInterface(KernelContext context) { _commonServer = new ServerBase(context, "CommonServer"); }
/// <summary> /// Initializes a new instance of the <see cref="SessionEndpoint"/> class. /// </summary> /// <param name="server">The server.</param> public SessionEndpoint(ServerBase server) : base(server) { this.CreateKnownTypes(); }
/// <summary> /// Starts the UA server as a Windows Service. /// </summary> /// <param name="server">The server.</param> public void StartAsService(ServerBase server) { throw new NotImplementedException(".NetStandard Opc.Ua libraries do not support to start as a windows service"); }
internal ProviderDetailsInfo SendServiceDetail(string hostUrl, ServerBase serverBase) { //try //{ if (!hostUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { hostUrl += "http://"; } if (Uri.TryCreate(hostUrl, UriKind.Absolute, out Uri uri)) { hostUrl = uri.Host + ":" + uri.Port; } using (XmlCommentLoader xmlCommentLoader = new XmlCommentLoader()) { List <Type> modelTypes = new List <Type>(); int id = 1; ProviderDetailsInfo result = new ProviderDetailsInfo() { Id = id }; foreach (KeyValuePair <string, Type> service in serverBase.RegisteredServiceTypes.Where(x => x.Value.IsServerService())) { id++; ServiceDetailsInfo serviceDetail = new ServiceDetailsInfo() { ServiceName = service.Key, FullNameSpace = service.Value.FullName, NameSpace = service.Value.Name, Id = id }; result.Services.Add(serviceDetail); List <Type> types = new List <Type>(); types.Add(service.Value); foreach (Type item in CSCodeInjection.GetListOfTypes(service.Value)) { if (item.GetCustomAttributes <ServiceContractAttribute>(false).Length > 0 && !types.Contains(item)) { types.Add(item); types.AddRange(CSCodeInjection.GetListOfTypes(service.Value).Where(x => !types.Contains(x))); } } foreach (Type serviceType in types) { if (serviceType == typeof(object)) { continue; } List <MethodInfo> methods = serviceType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).Where(x => !(x.IsSpecialName && (x.Name.StartsWith("set_") || x.Name.StartsWith("get_"))) && x.DeclaringType != typeof(object)).ToList(); if (methods.Count == 0) { continue; } CommentOfClassInfo comment = xmlCommentLoader.GetComment(serviceType); id++; ServiceDetailsInterface interfaceInfo = new ServiceDetailsInterface() { NameSpace = serviceType.Name, FullNameSpace = serviceType.FullName, Comment = comment?.Summery, Id = id }; serviceDetail.Services.Add(interfaceInfo); List <ServiceDetailsMethod> serviceMethods = new List <ServiceDetailsMethod>(); foreach (MethodInfo method in methods) { SerializeObjectType pType = SerializeHelper.GetTypeCodeOfObject(method.ReturnType); if (pType == SerializeObjectType.Enum) { AddEnumAndNewModels(ref id, method.ReturnType, result, SerializeObjectType.Enum, xmlCommentLoader); } CommentOfMethodInfo methodComment = comment == null ? null : (from x in comment.Methods where x.Name == method.Name && x.Parameters.Count == method.GetParameters().Length select x).FirstOrDefault(); string exceptions = ""; if (methodComment?.Exceptions != null && methodComment?.Exceptions.Count > 0) { foreach (CommentOfExceptionInfo ex in methodComment.Exceptions) { try { if (ex.RefrenceType.LastIndexOf('.') != -1) { string baseNameOfEnum = ex.RefrenceType.Substring(0, ex.RefrenceType.LastIndexOf('.')); Type type = GetEnumType(baseNameOfEnum); #if (NETSTANDARD1_6 || NETCOREAPP1_1) if (type != null && type.GetTypeInfo().IsEnum) #else if (type != null && type.IsEnum) #endif { object value = Enum.Parse(type, ex.RefrenceType.Substring(ex.RefrenceType.LastIndexOf('.') + 1, ex.RefrenceType.Length - ex.RefrenceType.LastIndexOf('.') - 1)); int exNumber = (int)value; exceptions += ex.RefrenceType + $" ({exNumber}) : " + ex.Comment + TextHelper.NewLine; continue; } } } catch { } exceptions += ex.RefrenceType + ":" + ex.Comment + TextHelper.NewLine; } } id++; ServiceDetailsMethod info = new ServiceDetailsMethod() { MethodName = method.Name, #if (!NET35) Requests = new System.Collections.ObjectModel.ObservableCollection <ServiceDetailsRequestInfo>() { new ServiceDetailsRequestInfo() { Name = "Default", Parameters = new List <ServiceDetailsParameterInfo>(), IsSelected = true } }, #endif ReturnType = method.ReturnType.GetFriendlyName(), Comment = methodComment?.Summery, ReturnComment = methodComment?.Returns, ExceptionsComment = exceptions, Id = id }; RuntimeTypeHelper.GetListOfUsedTypes(method.ReturnType, ref modelTypes); foreach (System.Reflection.ParameterInfo paramInfo in method.GetParameters()) { pType = SerializeHelper.GetTypeCodeOfObject(paramInfo.ParameterType); if (pType == SerializeObjectType.Enum) { AddEnumAndNewModels(ref id, paramInfo.ParameterType, result, SerializeObjectType.Enum, xmlCommentLoader); } string parameterComment = ""; if (methodComment != null) { parameterComment = (from x in methodComment.Parameters where x.Name == paramInfo.Name select x.Comment).FirstOrDefault(); } id++; ServiceDetailsParameterInfo p = new ServiceDetailsParameterInfo() { Name = paramInfo.Name, Type = paramInfo.ParameterType.GetFriendlyName(), FullTypeName = paramInfo.ParameterType.FullName, Comment = parameterComment, Id = id }; #if (!NET35) info.Requests.First().Parameters.Add(p); #endif RuntimeTypeHelper.GetListOfUsedTypes(paramInfo.ParameterType, ref modelTypes); } serviceMethods.Add(info); } interfaceInfo.Methods.AddRange(serviceMethods); } } foreach (KeyValuePair <string, Type> service in serverBase.RegisteredServiceTypes.Where(x => x.Value.IsClientService())) { id++; CallbackServiceDetailsInfo serviceDetail = new CallbackServiceDetailsInfo() { ServiceName = service.Key, FullNameSpace = service.Value.FullName, NameSpace = service.Value.Name, Id = id }; result.Callbacks.Add(serviceDetail); List <Type> types = new List <Type>(); types.Add(service.Value); foreach (Type item in CSCodeInjection.GetListOfTypes(service.Value)) { if (item.GetCustomAttributes <ServiceContractAttribute>(false).Length > 0 && !types.Contains(item)) { types.Add(item); types.AddRange(CSCodeInjection.GetListOfTypes(service.Value).Where(x => !types.Contains(x))); } } List <MethodInfo> methods = service.Value.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).Where(x => !(x.IsSpecialName && (x.Name.StartsWith("set_") || x.Name.StartsWith("get_"))) && x.DeclaringType != typeof(object)).ToList(); if (methods.Count == 0) { continue; } CommentOfClassInfo comment = xmlCommentLoader.GetComment(service.Value); List <ServiceDetailsMethod> serviceMethods = new List <ServiceDetailsMethod>(); foreach (MethodInfo method in methods) { SerializeObjectType pType = SerializeHelper.GetTypeCodeOfObject(method.ReturnType); if (pType == SerializeObjectType.Enum) { AddEnumAndNewModels(ref id, method.ReturnType, result, SerializeObjectType.Enum, xmlCommentLoader); } CommentOfMethodInfo methodComment = comment == null ? null : (from x in comment.Methods where x.Name == method.Name && x.Parameters.Count == method.GetParameters().Length select x).FirstOrDefault(); string exceptions = ""; if (methodComment?.Exceptions != null && methodComment?.Exceptions.Count > 0) { foreach (CommentOfExceptionInfo ex in methodComment.Exceptions) { try { if (ex.RefrenceType.LastIndexOf('.') != -1) { string baseNameOfEnum = ex.RefrenceType.Substring(0, ex.RefrenceType.LastIndexOf('.')); Type type = GetEnumType(baseNameOfEnum); #if (NETSTANDARD1_6 || NETCOREAPP1_1) if (type != null && type.GetTypeInfo().IsEnum) #else if (type != null && type.IsEnum) #endif { object value = Enum.Parse(type, ex.RefrenceType.Substring(ex.RefrenceType.LastIndexOf('.') + 1, ex.RefrenceType.Length - ex.RefrenceType.LastIndexOf('.') - 1)); int exNumber = (int)value; exceptions += ex.RefrenceType + $" ({exNumber}) : " + ex.Comment + TextHelper.NewLine; continue; } } } catch { } exceptions += ex.RefrenceType + ":" + ex.Comment + TextHelper.NewLine; } } id++; ServiceDetailsMethod info = new ServiceDetailsMethod() { MethodName = method.Name, #if (!NET35) Requests = new System.Collections.ObjectModel.ObservableCollection <ServiceDetailsRequestInfo>() { new ServiceDetailsRequestInfo() { Name = "Default", Parameters = new List <ServiceDetailsParameterInfo>(), IsSelected = true } }, #endif ReturnType = method.ReturnType.GetFriendlyName(), Comment = methodComment?.Summery, ReturnComment = methodComment?.Returns, ExceptionsComment = exceptions, Id = id }; RuntimeTypeHelper.GetListOfUsedTypes(method.ReturnType, ref modelTypes); foreach (System.Reflection.ParameterInfo paramInfo in method.GetParameters()) { pType = SerializeHelper.GetTypeCodeOfObject(paramInfo.ParameterType); if (pType == SerializeObjectType.Enum) { AddEnumAndNewModels(ref id, paramInfo.ParameterType, result, SerializeObjectType.Enum, xmlCommentLoader); } string parameterComment = ""; if (methodComment != null) { parameterComment = (from x in methodComment.Parameters where x.Name == paramInfo.Name select x.Comment).FirstOrDefault(); } id++; ServiceDetailsParameterInfo p = new ServiceDetailsParameterInfo() { Name = paramInfo.Name, Type = paramInfo.ParameterType.GetFriendlyName(), FullTypeName = paramInfo.ParameterType.FullName, Comment = parameterComment, Id = id }; #if (!NET35) info.Requests.First().Parameters.Add(p); #endif RuntimeTypeHelper.GetListOfUsedTypes(paramInfo.ParameterType, ref modelTypes); } serviceMethods.Add(info); } serviceDetail.Methods.AddRange(serviceMethods); } foreach (KeyValuePair <string, Type> httpServiceType in serverBase.RegisteredServiceTypes.Where(x => x.Value.IsHttpService())) { id++; HttpControllerDetailsInfo controller = new HttpControllerDetailsInfo() { Id = id, Url = httpServiceType.Value.GetCustomAttributes <ServiceContractAttribute>(true).Length > 0 ? httpServiceType.Value.GetCustomAttributes <ServiceContractAttribute>(true)[0].Name : httpServiceType.Key, }; id++; result.WebApiDetailsInfo.Id = id; result.WebApiDetailsInfo.HttpControllers.Add(controller); List <MethodInfo> methods = httpServiceType.Value.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).Where(x => !(x.IsSpecialName && (x.Name.StartsWith("set_") || x.Name.StartsWith("get_"))) && x.DeclaringType != typeof(object)).ToList(); if (methods.Count == 0) { continue; } CommentOfClassInfo comment = xmlCommentLoader.GetComment(httpServiceType.Value); List <ServiceDetailsMethod> serviceMethods = new List <ServiceDetailsMethod>(); foreach (MethodInfo method in methods) { SerializeObjectType pType = SerializeHelper.GetTypeCodeOfObject(method.ReturnType); if (pType == SerializeObjectType.Enum) { AddEnumAndNewModels(ref id, method.ReturnType, result, SerializeObjectType.Enum, xmlCommentLoader); } CommentOfMethodInfo methodComment = comment == null ? null : (from x in comment.Methods where x.Name == method.Name && x.Parameters.Count == method.GetParameters().Length select x).FirstOrDefault(); string exceptions = ""; if (methodComment?.Exceptions != null && methodComment?.Exceptions.Count > 0) { foreach (CommentOfExceptionInfo ex in methodComment.Exceptions) { try { if (ex.RefrenceType.LastIndexOf('.') != -1) { string baseNameOfEnum = ex.RefrenceType.Substring(0, ex.RefrenceType.LastIndexOf('.')); Type type = GetEnumType(baseNameOfEnum); #if (NETSTANDARD1_6 || NETCOREAPP1_1) if (type != null && type.GetTypeInfo().IsEnum) #else if (type != null && type.IsEnum) #endif { object value = Enum.Parse(type, ex.RefrenceType.Substring(ex.RefrenceType.LastIndexOf('.') + 1, ex.RefrenceType.Length - ex.RefrenceType.LastIndexOf('.') - 1)); int exNumber = (int)value; exceptions += ex.RefrenceType + $" ({exNumber}) : " + ex.Comment + TextHelper.NewLine; continue; } } } catch { } exceptions += ex.RefrenceType + ":" + ex.Comment + TextHelper.NewLine; } } id++; ServiceDetailsMethod info = new ServiceDetailsMethod() { Id = id, MethodName = method.Name, #if (!NET35) Requests = new System.Collections.ObjectModel.ObservableCollection <ServiceDetailsRequestInfo>() { new ServiceDetailsRequestInfo() { Name = "Default", Parameters = new List <ServiceDetailsParameterInfo>(), IsSelected = true } }, #endif ReturnType = method.ReturnType.GetFriendlyName(), Comment = methodComment?.Summery, ReturnComment = methodComment?.Returns, ExceptionsComment = exceptions, TestExample = hostUrl + "/" + controller.Url + "/" + method.Name }; RuntimeTypeHelper.GetListOfUsedTypes(method.ReturnType, ref modelTypes); string testExampleParams = ""; foreach (System.Reflection.ParameterInfo paramInfo in method.GetParameters()) { pType = SerializeHelper.GetTypeCodeOfObject(paramInfo.ParameterType); if (pType == SerializeObjectType.Enum) { AddEnumAndNewModels(ref id, paramInfo.ParameterType, result, SerializeObjectType.Enum, xmlCommentLoader); } string parameterComment = ""; if (methodComment != null) { parameterComment = (from x in methodComment.Parameters where x.Name == paramInfo.Name select x.Comment).FirstOrDefault(); } id++; ServiceDetailsParameterInfo p = new ServiceDetailsParameterInfo() { Id = id, Name = paramInfo.Name, Type = paramInfo.ParameterType.Name, FullTypeName = paramInfo.ParameterType.FullName, Comment = parameterComment }; #if (!NET35) info.Requests.First().Parameters.Add(p); #endif if (string.IsNullOrEmpty(testExampleParams)) { testExampleParams += "?"; } else { testExampleParams += "&"; } testExampleParams += paramInfo.Name + "=" + DataExchangeConverter.GetDefault(paramInfo.ParameterType) ?? "null"; RuntimeTypeHelper.GetListOfUsedTypes(paramInfo.ParameterType, ref modelTypes); } info.TestExample += testExampleParams; serviceMethods.Add(info); } controller.Methods = serviceMethods; } foreach (Type type in modelTypes) { try { SerializeObjectType pType = SerializeHelper.GetTypeCodeOfObject(type); AddEnumAndNewModels(ref id, type, result, pType, xmlCommentLoader); // var mode = SerializeHelper.GetTypeCodeOfObject(type); // if (mode == SerializeObjectType.Object) // { // if (type.Name.Contains("`") || type == typeof(CustomAttributeTypedArgument) || type == typeof(CustomAttributeNamedArgument) || //#if (NETSTANDARD1_6 || NETCOREAPP1_1) // type.GetTypeInfo().BaseType == typeof(Attribute)) //#else // type.BaseType == typeof(Attribute)) //#endif // continue; // var instance = Activator.CreateInstance(type); // string jsonResult = JsonConvert.SerializeObject(instance, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include }); // var refactorResult = (JObject)JsonConvert.DeserializeObject(jsonResult); // foreach (var item in refactorResult.Properties()) // { // var find = type.GetProperties().FirstOrDefault(x => x.Name == item.Name); // refactorResult[item.Name] = find.PropertyType.FullName; // } // jsonResult = JsonConvert.SerializeObject(refactorResult, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include }); // if (jsonResult == "{}" || jsonResult == "[]") // continue; // var comment = xmlCommentLoader.GetComment(type); // id++; // result.ProjectDomainDetailsInfo.Id = id; // id++; // result.ProjectDomainDetailsInfo.Models.Add(new ModelDetailsInfo() // { // Id = id, // Comment = comment?.Summery, // Name = type.Name, // FullNameSpace = type.FullName, // ObjectType = mode, // JsonTemplate = jsonResult // }); // foreach (var property in type.GetProperties()) // { // var pType = SerializeHelper.GetTypeCodeOfObject(property.PropertyType); // if (pType == SerializeObjectType.Enum) // { // AddEnumAndNewModels(ref id, property.PropertyType, result, SerializeObjectType.Enum, xmlCommentLoader); // } // } // } } catch (Exception ex) { serverBase.AutoLogger.LogError(ex, "Model Type Add error: " + ex.ToString()); } } return(result); //string json = ServerSerializationHelper.SerializeObject(result, serverBase); //List<byte> bytes = new List<byte> // { // (byte)DataType.GetServiceDetails, // (byte)CompressMode.None // }; //byte[] jsonBytes = Encoding.UTF8.GetBytes(json); //byte[] dataLen = BitConverter.GetBytes(jsonBytes.Length); //bytes.AddRange(dataLen); //bytes.AddRange(jsonBytes); //await client.StreamHelper.WriteToStreamAsync(client.ClientStream, bytes.ToArray()); } //} //catch (Exception ex) //{ // try // { // string json = ServerSerializationHelper.SerializeObject(new Exception(ex.ToString()), serverBase); // List<byte> bytes = new List<byte> // { // (byte)DataType.GetServiceDetails, // (byte)CompressMode.None // }; // byte[] jsonBytes = Encoding.UTF8.GetBytes(json); // byte[] dataLen = BitConverter.GetBytes(jsonBytes.Length); // bytes.AddRange(dataLen); // bytes.AddRange(jsonBytes); // await client.StreamHelper.WriteToStreamAsync(client.ClientStream, bytes.ToArray()); // } // catch (Exception) // { // } // serverBase.AutoLogger.LogError(ex, $"{client.IPAddress} {client.ClientId} ServerBase CallMethod"); //} //finally //{ // skippedTypes.Clear(); //} void AddEnumAndNewModels(ref int id, Type type, ProviderDetailsInfo result, SerializeObjectType objType, XmlCommentLoader xmlCommentLoader) { if (result.ProjectDomainDetailsInfo.Models.Any(x => x.FullNameSpace == type.FullName) || skippedTypes.Contains(type)) { return; } id++; result.ProjectDomainDetailsInfo.Id = id; id++; if (objType == SerializeObjectType.Enum) { List <string> items = new List <string>(); foreach (Enum obj in Enum.GetValues(type)) { int x = Convert.ToInt32(obj); // x is the integer value of enum items.Add(obj.ToString() + " = " + x); } result.ProjectDomainDetailsInfo.Models.Add(new ModelDetailsInfo() { Id = id, Name = type.Name, FullNameSpace = type.FullName, ObjectType = objType, JsonTemplate = JsonConvert.SerializeObject(items, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include }) }); } else { try { if (type.Name.Contains("`") || type == typeof(CustomAttributeTypedArgument) || type == typeof(CustomAttributeNamedArgument) || #if (NETSTANDARD1_6 || NETCOREAPP1_1) type.GetTypeInfo().BaseType == typeof(Attribute) || type.GetTypeInfo().BaseType == null) #else type.BaseType == typeof(Attribute) || type.BaseType == null) #endif { skippedTypes.Add(type); return; } object instance = Activator.CreateInstance(type); string jsonResult = JsonConvert.SerializeObject(instance, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include }); JObject refactorResult = (JObject)JsonConvert.DeserializeObject(jsonResult); foreach (JProperty item in refactorResult.Properties()) { PropertyInfo find = type.GetProperties().FirstOrDefault(x => x.Name == item.Name); refactorResult[item.Name] = find.PropertyType.GetFriendlyName(); } jsonResult = JsonConvert.SerializeObject(refactorResult, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include }); if (jsonResult == "{}" || jsonResult == "[]") { skippedTypes.Add(type); return; } CommentOfClassInfo comment = xmlCommentLoader.GetComment(type); id++; result.ProjectDomainDetailsInfo.Id = id; id++; result.ProjectDomainDetailsInfo.Models.Add(new ModelDetailsInfo() { Id = id, Comment = comment?.Summery, Name = type.Name, FullNameSpace = type.FullName, ObjectType = objType, JsonTemplate = jsonResult }); } catch { skippedTypes.Add(type); } } foreach (Type item in type.GetListOfGenericArguments()) { SerializeObjectType pType = SerializeHelper.GetTypeCodeOfObject(item); AddEnumAndNewModels(ref id, item, result, pType, xmlCommentLoader); } foreach (Type item in type.GetListOfInterfaces()) { SerializeObjectType pType = SerializeHelper.GetTypeCodeOfObject(item); AddEnumAndNewModels(ref id, item, result, pType, xmlCommentLoader); } foreach (Type item in type.GetListOfNestedTypes()) { SerializeObjectType pType = SerializeHelper.GetTypeCodeOfObject(item); AddEnumAndNewModels(ref id, item, result, pType, xmlCommentLoader); } foreach (Type item in type.GetListOfBaseTypes()) { SerializeObjectType pType = SerializeHelper.GetTypeCodeOfObject(item); AddEnumAndNewModels(ref id, item, result, pType, xmlCommentLoader); } foreach (PropertyInfo property in type.GetProperties()) { SerializeObjectType pType = SerializeHelper.GetTypeCodeOfObject(property.PropertyType); AddEnumAndNewModels(ref id, property.PropertyType, result, pType, xmlCommentLoader); } } }
public GSInboundPlayerConnection(Socket s, ServerBase server, bool isBlocking) : base(s, server, isBlocking) { }
/// <inheritdoc/> /// <summary> /// Create a new service host for UA TCP. /// </summary> public List <EndpointDescription> CreateServiceHost( ServerBase serverBase, IDictionary <string, ServiceHost> hosts, ApplicationConfiguration configuration, IList <string> baseAddresses, ApplicationDescription serverDescription, List <ServerSecurityPolicy> securityPolicies, X509Certificate2 instanceCertificate, X509Certificate2Collection instanceCertificateChain) { // generate a unique host name. string hostName = "/Tcp"; if (hosts.ContainsKey(hostName)) { hostName += Utils.Format("/{0}", hosts.Count); } // build list of uris. List <Uri> uris = new List <Uri>(); EndpointDescriptionCollection endpoints = new EndpointDescriptionCollection(); // create the endpoint configuration to use. EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration); string computerName = Utils.GetHostName(); for (int ii = 0; ii < baseAddresses.Count; ii++) { // UA TCP and HTTPS endpoints support multiple policies. if (!baseAddresses[ii].StartsWith(Utils.UriSchemeOpcTcp, StringComparison.Ordinal)) { continue; } UriBuilder uri = new UriBuilder(baseAddresses[ii]); if (String.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) { uri.Host = computerName; } ITransportListener listener = this.Create(); if (listener != null) { EndpointDescriptionCollection listenerEndpoints = new EndpointDescriptionCollection(); uris.Add(uri.Uri); foreach (ServerSecurityPolicy policy in securityPolicies) { // create the endpoint description. EndpointDescription description = new EndpointDescription(); description.EndpointUrl = uri.ToString(); description.Server = serverDescription; description.SecurityMode = policy.SecurityMode; description.SecurityPolicyUri = policy.SecurityPolicyUri; description.SecurityLevel = ServerSecurityPolicy.CalculateSecurityLevel(policy.SecurityMode, policy.SecurityPolicyUri); description.UserIdentityTokens = serverBase.GetUserTokenPolicies(configuration, description); description.TransportProfileUri = Profiles.UaTcpTransport; bool requireEncryption = ServerBase.RequireEncryption(description); if (requireEncryption) { description.ServerCertificate = instanceCertificate.RawData; // check if complete chain should be sent. if (configuration.SecurityConfiguration.SendCertificateChain && instanceCertificateChain != null && instanceCertificateChain.Count > 0) { List <byte> serverCertificateChain = new List <byte>(); for (int i = 0; i < instanceCertificateChain.Count; i++) { serverCertificateChain.AddRange(instanceCertificateChain[i].RawData); } description.ServerCertificate = serverCertificateChain.ToArray(); } } listenerEndpoints.Add(description); } serverBase.CreateServiceHostEndpoint(uri.Uri, listenerEndpoints, endpointConfiguration, listener, configuration.CertificateValidator.GetChannelValidator()); endpoints.AddRange(listenerEndpoints); } else { Utils.LogError("Failed to create endpoint {0} because the transport profile is unsupported.", uri); } } hosts[hostName] = serverBase.CreateServiceHost(serverBase, uris.ToArray()); return(endpoints); }
/// <summary> /// Override from ServerBase, to make sure we create the proper connection object for outbound connections. /// If we don't override this method, a generic OutboundServerConnection class will be instantiated. /// </summary> public override OutboundServerConnection CreateOutboundServerConnection(string name, ServerBase server, string reportedIP, int serviceID, bool isBlocking) { // we need to define a new class and instantiate it here for any outbound connections. currently, the game lobby server // should have no outbound connections. If it tries to create some (i.e. this exception has been thrown), there is likely // an outbound connection defined in your App.Config file that probably shouldn't be there. throw new NotImplementedException("No outbound connections object have been defined for GameServer_Lobby"); }