Ejemplo n.º 1
0
            private void OnChatComing(ulong hSocket, tagChatRequestID chatRequestID, uint len)
            {
                uint        res;
                CSocketPeer sp = Seek(hSocket);

                if (sp == null)
                {
                    return;
                }
                sp.m_CurrReqID = (ushort)chatRequestID;
                CUQueue q = sp.m_qBuffer;

                q.SetSize(0);
                if (len > q.MaxBufferSize)
                {
                    q.Realloc(len);
                }
                unsafe
                {
                    fixed(byte *buffer = q.m_bytes)
                    {
                        res = ServerCoreLoader.RetrieveBuffer(hSocket, len, buffer, true);
                    }
                }
                System.Diagnostics.Debug.Assert(res == len);
                q.SetSize(res);
                sp.OnChatComing(chatRequestID);
            }
Ejemplo n.º 2
0
            private void OnSwitch(ulong hSocket, uint oldServiceId, uint newServiceId)
            {
                if (m_nMainThreads == uint.MaxValue)
                {
                    m_nMainThreads = ServerCoreLoader.GetMainThreads();
                }
                CBaseService bsOld;

                if (oldServiceId != BaseServiceID.sidStartup && (bsOld = SeekService(oldServiceId)) != null)
                {
                    bsOld.ReleasePeer(hSocket, false, newServiceId);
                }
                CBaseService bsNew = SeekService(newServiceId);

                if (bsNew != null)
                {
                    CSocketPeer sp = bsNew.CreatePeer(hSocket, newServiceId);
                    sp.m_bRandom = bsNew.ReturnRandom;
                    if (newServiceId == BaseServiceID.sidHTTP)
                    {
                        CHttpPeerBase hp = (CHttpPeerBase)sp;
                        hp.m_bHttpOk = false;
                    }
                    else
                    {
                        sp.m_os             = ServerCoreLoader.GetPeerOs(hSocket, ref sp.m_endian);
                        sp.m_qBuffer.OS     = sp.m_os;
                        sp.m_qBuffer.Endian = sp.m_endian;
                    }
                    sp.OnSwitch(oldServiceId);
                }
            }
Ejemplo n.º 3
0
                public static bool Publish(byte[] Message, params uint[] Groups)
                {
                    uint size;
                    uint len;

                    if (Groups == null)
                    {
                        len = 0;
                    }
                    else
                    {
                        len = (uint)Groups.Length;
                    }
                    if (Message == null)
                    {
                        size = 0;
                    }
                    else
                    {
                        size = (uint)Message.Length;
                    }
                    unsafe
                    {
                        fixed(byte *buffer = Message)
                        {
                            fixed(uint *p = Groups)
                            {
                                return(ServerCoreLoader.SpeakExPush(buffer, size, p, len));
                            }
                        }
                    }
                }
Ejemplo n.º 4
0
        /// <summary>
        /// Download a stream from server to a client. Internally, it will also fake an empty request (CStreamSerializationHelper.idReadDataFromServerToClient) on behalf on the client
        /// </summary>
        /// <param name="PeerHandle">A peer socket handle to represent a client</param>
        /// <param name="source">A valid stream at server side</param>
        /// <param name="fileSize">File size in bytes. It will be -1 if there is error</param>
        /// <param name="errMsg">An error message. It will be empty string with zero length if no error is found</param>
        public static void Download(ulong PeerHandle, Stream source, out ulong fileSize, out string errMsg)
        {
            if (source == null)
            {
                fileSize = ulong.MaxValue;
                errMsg   = "Source stream not available";
                return;
            }
            else if (!source.CanRead)
            {
                fileSize = ulong.MaxValue;
                errMsg   = "Source stream not readable";
                return;
            }
            errMsg = "";
            try
            {
                fileSize = (ulong)source.Length;
            }
            catch (Exception)
            {
                fileSize = ulong.MaxValue;
            }

            unsafe
            {
                byte[] temp = null;
                fixed(byte *p = temp)
                {
                    ServerCoreLoader.MakeRequest(PeerHandle, CStreamSerializationHelper.idReadDataFromServerToClient, p, (uint)0);
                }
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Register a service
 /// </summary>
 /// <param name="svsId">A service id</param>
 /// <param name="ta">Thread apartment for windows default to tagThreadApartment.taNone. It is ignored on non-windows platforms</param>
 /// <returns>True if successful. Otherwise false if failed</returns>
 public virtual bool AddMe(uint svsId, tagThreadApartment ta)
 {
     m_sc.m_OnBaseRequestCame    = new DOnBaseRequestCame(OnBaseCame);
     m_sc.m_OnChatRequestCame    = new DOnChatRequestCame(OnChatCame);
     m_sc.m_OnChatRequestComing  = new DOnChatRequestComing(OnChatComing);
     m_sc.m_OnClose              = new DOnClose(OnClose);
     m_sc.m_OnFastRequestArrive  = new DOnFastRequestArrive(OnFast);
     m_sc.m_OnHttpAuthentication = new DOnHttpAuthentication(OnHttpAuthentication);
     m_sc.m_OnRequestArrive      = new DOnRequestArrive(OnReqArrive);
     m_sc.m_OnRequestProcessed   = new DOnRequestProcessed(OnSRProcessed);
     m_sc.m_OnSwitchTo           = new DOnSwitchTo(OnSwitch);
     m_sc.m_SlowProcess          = new DSLOW_PROCESS(OnSlow);
     m_sc.m_OnResultsSent        = new DOnResultsSent(OnResultsSent);
     m_sc.m_ta = ta;
     if (svsId > 0 && ServerCoreLoader.AddSvsContext(svsId, m_sc))
     {
         m_svsId = svsId;
         lock (m_csService)
         {
             if (!m_bRegEvent)
             {
                 ServerCoreLoader.SetThreadEvent(CSocketProServer.te);
                 m_bRegEvent = true;
             }
             m_lstService.Add(this);
         }
         return(true);
     }
     return(false);
 }
Ejemplo n.º 6
0
 public static void StopSPServer(out SqlInt32 res)
 {
     res = 0;
     using (SqlConnection conn = new SqlConnection("context connection=true"))
     {
         try
         {
             conn.Open();
             lock (m_cs)
             {
                 if (Plugin != null)
                 {
                     if (ServerCoreLoader.IsRunning())
                     {
                         ServerCoreLoader.SetOnIdle(null);
                         Plugin.StopSocketProServer();
                         res += 1;
                     }
                     Plugin.Dispose();
                     Plugin = null;
                     res   += 1;
                 }
             }
         }
         catch (Exception err)
         {
             UConfig.LogMsg(err.Message, "USqlStream::StopSPServer", 57); //line 57
         }
         finally
         {
             conn.Close();
         }
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Download a file from server to a client. Internally, it will also fake an empty request (CStreamSerializationHelper.idReadDataFromServerToClient) on behalf on the client
        /// </summary>
        /// <param name="PeerHandle">A peer socket handle to represent a client</param>
        /// <param name="RemoteFilePath">A path to a file</param>
        /// <param name="fileSize">File size in bytes. It will be -1 if there is error</param>
        /// <param name="errMsg">An error message. It will be empty string with zero length if no error is found</param>
        /// <returns>A file stream</returns>
        public static FileStream DownloadFile(ulong PeerHandle, string RemoteFilePath, out ulong fileSize, out string errMsg)
        {
            FileStream fs = null;

            try
            {
                fs       = new FileStream(RemoteFilePath, FileMode.Open);
                fileSize = (ulong)fs.Length;
                unsafe
                {
                    byte [] temp = null;
                    fixed(byte *p = temp)
                    {
                        ServerCoreLoader.MakeRequest(PeerHandle, CStreamSerializationHelper.idReadDataFromServerToClient, p, (uint)0);
                    }
                }
                errMsg = "";
            }
            catch (Exception err)
            {
                fileSize = ulong.MaxValue;
                errMsg   = err.Message;
            }
            return(fs);
        }
Ejemplo n.º 8
0
                public bool Publish(object Message, uint[] Groups)
                {
                    uint len;

                    if (Groups == null)
                    {
                        len = 0;
                    }
                    else
                    {
                        len = (uint)Groups.Length;
                    }
                    using (CScopeUQueue su = new CScopeUQueue())
                    {
                        CUQueue q = su.UQueue;
                        q.Save(Message);
                        unsafe
                        {
                            fixed(byte *buffer = q.m_bytes)
                            {
                                fixed(uint *p = Groups)
                                {
                                    return(ServerCoreLoader.Speak(m_sp.Handle, buffer, q.GetSize(), p, len));
                                }
                            }
                        }
                    }
                }
Ejemplo n.º 9
0
            public virtual bool Run(uint port, uint maxBacklog, bool v6Supported)
            {
                if (!OnSettingServer())
                {
                    return(false);
                }
                Type type = GetType();

                FieldInfo[] fis = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetField | BindingFlags.Static);
                foreach (FieldInfo fi in fis)
                {
                    ServiceAttr[] sas = (ServiceAttr[])fi.GetCustomAttributes(typeof(ServiceAttr), true);
                    if (sas != null && sas.Length > 0)
                    {
                        CBaseService bs = (CBaseService)fi.GetValue(this);
                        if (!bs.AddMe(sas[0].ServiceID, sas[0].ThreadApartment))
                        {
                            throw new InvalidOperationException("Failed in registering service = " + sas[0].ServiceID + ", and check if the service ID is duplicated with the previous one or if the service ID is less or equal to SocketProAdapter.BaseServiceID.sidReserved");
                        }
                    }
                }
                bool ok = ServerCoreLoader.StartSocketProServer(port, maxBacklog, v6Supported);

                CBaseService.m_nMainThreads = uint.MaxValue;
                return(ok);
            }
Ejemplo n.º 10
0
            public bool EnsureAppending(uint[] queueHandles)
            {
                if (!Available)
                {
                    return(false);
                }
                if (QueueStatus != tagQueueStatus.qsMergePushing)
                {
                    return(true);
                }
                if (queueHandles == null || queueHandles.Length == 0)
                {
                    return(true);
                }
                List <uint> vHandles = new List <uint>();

                foreach (uint h in queueHandles)
                {
                    if (ServerCoreLoader.GetServerQueueStatus(h) != tagQueueStatus.qsMergeComplete)
                    {
                        vHandles.Add(h);
                    }
                }
                if (vHandles.Count > 0)
                {
                    return(AppendTo(vHandles.ToArray()));
                }
                Reset();
                return(true);
            }
Ejemplo n.º 11
0
        /// <summary>
        /// Read data from a source stream at server side and send its content onto a client
        /// </summary>
        /// <param name="PeerHandle">A peer socket handle to represent a client</param>
        /// <param name="source">A stream to a source file or other object</param>
        /// <returns>The number of data sent in bytes</returns>
        public static ulong ReadDataFromServerToClient(ulong PeerHandle, Stream source)
        {
            uint  res;
            ulong sent = 0;

            using (CScopeUQueue su = new CScopeUQueue())
            {
                CUQueue q    = su.UQueue;
                uint    read = CStreamSerializationHelper.Read(source, q);
                while (read != 0)
                {
                    unsafe
                    {
                        fixed(byte *p = q.m_bytes)
                        {
                            res = ServerCoreLoader.SendReturnData(PeerHandle, CStreamSerializationHelper.idReadDataFromServerToClient, read, p);
                        }
                    }
                    if (res == CSocketPeer.REQUEST_CANCELED || res == CSocketPeer.SOCKET_NOT_FOUND)
                    {
                        break;
                    }
                    sent += res;
                    q.SetSize(0);
                    read = CStreamSerializationHelper.Read(source, q);
                }
            }
            return(sent);
        }
Ejemplo n.º 12
0
 public static void StopSPServer(out SqlInt32 res)
 {
     res = 0;
     using (SqlConnection conn = new SqlConnection("context connection=true"))
     {
         try
         {
             conn.Open();
             lock (m_cs)
             {
                 if (Plugin != null)
                 {
                     if (ServerCoreLoader.IsRunning())
                     {
                         ServerCoreLoader.SetOnIdle(null);
                         Plugin.StopSocketProServer();
                         res += 10;
                     }
                     Plugin.Dispose();
                     Plugin = null;
                     res   += 1;
                 }
             }
         }
         catch (Exception err)
         {
             LogError(conn, err.Message);
         }
         finally
         {
             conn.Close();
         }
     }
 }
Ejemplo n.º 13
0
 public void UseSSL(string certFile, string keyFile, string pwdForPrivateKeyFile, string dhFile)
 {
     ServerCoreLoader.SetCertFile(certFile);
     ServerCoreLoader.SetPrivateKeyFile(keyFile);
     ServerCoreLoader.SetPKFPassword(pwdForPrivateKeyFile);
     ServerCoreLoader.SetDHParmsFile(dhFile);
     ServerCoreLoader.SetDefaultEncryptionMethod(tagEncryptionMethod.TLSv1);
 }
Ejemplo n.º 14
0
 private void Clear()
 {
     if (m_ReqHeaders != null && !ServerCoreLoader.IsWebSocket(Handle))
     {
         m_ReqHeaders.Clear();
         m_ReqHeaders = null;
     }
 }
Ejemplo n.º 15
0
 public uint SendExceptionResult(string errMessage, string errWhere, uint errCode, ushort requestId, ulong reqIndex)
 {
     if (reqIndex == ulong.MaxValue)
     {
         return(ServerCoreLoader.SendExceptionResult(m_sh, errMessage, errWhere, requestId, errCode));
     }
     return(ServerCoreLoader.SendExceptionResultIndex(m_sh, reqIndex, errMessage, errWhere, requestId, errCode));
 }
Ejemplo n.º 16
0
 public void Dispose()
 {
     if (m_sps != null)
     {
         ServerCoreLoader.UninitSocketProServer();
         m_sps = null;
     }
 }
Ejemplo n.º 17
0
            public uint SendExceptionResult(string errMessage, string errWhere, uint errCode)
            {
                ulong reqIndex = CurrentRequestIndex;

                if (reqIndex == ulong.MaxValue)
                {
                    return(ServerCoreLoader.SendExceptionResult(m_sh, errMessage, errWhere, 0, errCode));
                }
                return(ServerCoreLoader.SendExceptionResultIndex(m_sh, reqIndex, errMessage, errWhere, 0, errCode));
            }
Ejemplo n.º 18
0
 public static void StartSPServer(out SqlInt32 res)
 {
     res = 0;
     using (SqlConnection conn = new SqlConnection("context connection=true"))
     {
         try
         {
             lock (m_cs)
             {
                 if (Plugin == null)
                 {
                     if (!Directory.Exists(SQLConfig.WorkingDirectory))
                     {
                         Directory.CreateDirectory(SQLConfig.WorkingDirectory);
                     }
                     Directory.SetCurrentDirectory(SQLConfig.WorkingDirectory);
                     Plugin = new CSqlPlugin(SQLConfig.Param);
                 }
                 if (!ServerCoreLoader.IsRunning())
                 {
                     res += 10;
                     if (SQLConfig.StoreOrPfx != null && SQLConfig.SubjectOrPassword != null && SQLConfig.StoreOrPfx.Length > 0 && SQLConfig.SubjectOrPassword.Length > 0)
                     {
                         if (SQLConfig.StoreOrPfx.IndexOf(".pfx") == -1)
                         {
                             //load cert and private key from windows system cert store
                             Plugin.UseSSL(SQLConfig.StoreOrPfx /*"my"*/, SQLConfig.SubjectOrPassword, "");
                         }
                         else
                         {
                             Plugin.UseSSL(SQLConfig.StoreOrPfx, "", SQLConfig.SubjectOrPassword);
                         }
                     }
                     Plugin.Run(SQLConfig.Port, 16, !SQLConfig.NoV6);
                 }
             }
         }
         catch (Exception err)
         {
             LogError(conn, err.Message);
         }
         finally
         {
             if (ServerCoreLoader.IsRunning())
             {
                 AppDomain.CurrentDomain.DomainUnload += (sender, args) => {
                     ServerCoreLoader.StopSocketProServer();
                     Plugin = null;
                 };
                 res += 1;
             }
             conn.Close();
         }
     }
 }
Ejemplo n.º 19
0
 public static string GetAChatGroup(uint groupId)
 {
     char[] des = new char[2048];
     unsafe
     {
         fixed(char *str = des)
         {
             ServerCoreLoader.GetAChatGroup(groupId, str, 2048);
         }
     }
     return(new string(des));
 }
Ejemplo n.º 20
0
 public void RemoveMe()
 {
     if (m_svsId > 0)
     {
         ServerCoreLoader.RemoveASvsContext(m_svsId);
         lock (m_csService)
         {
             m_lstService.Remove(this);
         }
         m_svsId = 0;
     }
 }
Ejemplo n.º 21
0
                public static string GetUserID(ulong hSocket)
                {
                    char[] id = new char[256];
                    unsafe
                    {
                        fixed(char *p = id)
                        {
                            uint res = ServerCoreLoader.GetUID(hSocket, p, 256);

                            return(new string(p));
                        }
                    }
                }
Ejemplo n.º 22
0
                public static string GetPassword(ulong hSocket)
                {
                    char[] pwd = new char[256];
                    unsafe
                    {
                        fixed(char *p = pwd)
                        {
                            uint res = ServerCoreLoader.GetPassword(hSocket, p, 256);

                            return(new string(p));
                        }
                    }
                }
Ejemplo n.º 23
0
            internal virtual void OnChatComing(tagChatRequestID chatRequestID)
            {
                uint    svsId = ServerCoreLoader.GetSvsID(m_sh);
                CUQueue q     = m_qBuffer;

                if (svsId != BaseServiceID.sidHTTP)
                {
                    bool endian           = false;
                    tagOperationSystem os = ServerCoreLoader.GetPeerOs(m_sh, ref endian);
                    q.Endian = endian;
                    q.OS     = os;
                }
                switch (chatRequestID)
                {
                case tagChatRequestID.idEnter:
                {
                    object objGroups;
                    q.Load(out objGroups);
                    OnSubscribe((uint[])objGroups);
                }
                break;

                case tagChatRequestID.idExit:
                {
                    OnUnsubscribe(ChatGroups);
                }
                break;

                case tagChatRequestID.idSendUserMessage:
                {
                    object msg;
                    string user;
                    q.Load(out user).Load(out msg);
                    OnSendUserMessage(user, msg);
                }
                break;

                case tagChatRequestID.idSpeak:
                {
                    object msg;
                    object groups;
                    q.Load(out groups).Load(out msg);
                    OnPublish(msg, (uint[])groups);
                }
                break;

                default:
                    ServerCoreLoader.SendExceptionResult(m_sh, "Unexpected chat request", Environment.StackTrace, (ushort)chatRequestID, 0);
                    break;
                }
            }
Ejemplo n.º 24
0
 public bool AppendTo(uint[] queueHandles)
 {
     if (queueHandles == null || queueHandles.Length == 0)
     {
         return(true);
     }
     unsafe
     {
         fixed(uint *p = queueHandles)
         {
             return(ServerCoreLoader.PushQueueTo(Handle, p, (uint)queueHandles.Length));
         }
     }
 }
Ejemplo n.º 25
0
 public virtual ulong Enqueue(ushort reqId, byte[] data, uint size)
 {
     if (data != null && size > (uint)data.Length)
     {
         size = (uint)data.Length;
     }
     unsafe
     {
         fixed(byte *buffer = data)
         {
             return(ServerCoreLoader.Enqueue(m_nHandle, reqId, buffer, size));
         }
     }
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Send a chunk of data after calling the method StartChunkResponse
 /// </summary>
 /// <param name="buffer">A buffer data</param>
 /// <returns>The data size in byte</returns>
 /// <remarks>You must call the method StartChunkResponse before calling this method</remarks>
 public uint SendChunk(byte[] buffer)
 {
     if (buffer == null || buffer.Length == 0)
     {
         return(0);
     }
     unsafe
     {
         fixed(byte *p = buffer)
         {
             return(ServerCoreLoader.SendHTTPChunk(Handle, p, (uint)buffer.Length));
         }
     }
 }
Ejemplo n.º 27
0
 public bool SendUserMessage(object Message, string UserId)
 {
     using (CScopeUQueue su = new CScopeUQueue())
     {
         CUQueue q = su.UQueue;
         q.Save(Message);
         unsafe
         {
             fixed(byte *p = q.m_bytes)
             {
                 return(ServerCoreLoader.SendUserMessage(m_sp.Handle, UserId, p, q.GetSize()));
             }
         }
     }
 }
Ejemplo n.º 28
0
 public virtual uint SendResult(string res)
 {
     Clear();
     if (res == null)
     {
         res = "";
     }
     byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(res);
     unsafe
     {
         fixed(byte *p = bytes)
         {
             return(ServerCoreLoader.SendHTTPReturnDataA(Handle, p, bytes.Length));
         }
     }
 }
Ejemplo n.º 29
0
            /// <summary>
            /// Use the method for debugging crash within cross development environments.
            /// </summary>
            /// <param name="str">A string will be sent to server core library to be output into a crash text file</param>
            public static void SetLastCallInfo(string str)
            {
                if (str == null)
                {
                    str = "";
                }
                unsafe
                {
                    fixed(byte *data = System.Text.Encoding.ASCII.GetBytes(str))
                    {
                        IntPtr p = new IntPtr(data);

                        ServerCoreLoader.SetLastCallInfo(p);
                    }
                }
            }
Ejemplo n.º 30
0
            static ServerCoreLoader()
            {
                switch (System.Environment.OSVersion.Platform)
                {
                case PlatformID.Win32S:
                case PlatformID.Win32NT:
                case PlatformID.Win32Windows:
                case PlatformID.WinCE:
                case PlatformID.Xbox:
                    break;

                default:
                    ServerCoreLoader.UseUTF16();
                    break;
                }
            }