Пример #1
0
        static SocketBase()
        {
            BufferPool = SubBuffer.Pool.GetPool((int)Config.BufferSize >= (int)Config.HeadSize ? Config.BufferSize : Config.HeadSize);

            int dateCacheSize = (Date.ToByteLength + 7) & (int.MaxValue - 7), AutoCSerServerSize = (AutoCSerServer.Length + 7) & (int.MaxValue - 7);

            dateCache = new Pointer {
                Data = Unmanaged.GetStatic64(dateCacheSize + AutoCSerServerSize, false)
            };
            responseServer = new Pointer {
                Data = dateCache.Byte + dateCacheSize
            };

            fixed(char *AutoCSerServerFixed = AutoCSerServer) StringExtension.WriteBytesNotNull(AutoCSerServerFixed, AutoCSerServer.Length, responseServer.Byte);

            byte[] responseServerEnd = (AutoCSerServer + @"Content-Length: 0

").getBytes();
            errorResponseDatas = new byte[EnumAttribute <ResponseState> .GetMaxValue(-1) + 1][];
            foreach (ResponseState type in System.Enum.GetValues(typeof(ResponseState)))
            {
                ResponseStateAttribute state = EnumAttribute <ResponseState, ResponseStateAttribute> .Array((int)type);

                if (state != null && state.IsError)
                {
                    string stateData    = state.Text;
                    byte[] responseData = new byte[httpVersionSize + stateData.Length + responseServerEnd.Length];
                    fixed(byte *responseDataFixed = responseData)
                    {
                        writeHttpVersion(responseDataFixed);
                        state.Write(responseDataFixed + httpVersionSize);
                    }

                    int index = httpVersionSize + stateData.Length;
                    System.Buffer.BlockCopy(responseServerEnd, 0, responseData, index, responseServerEnd.Length);
                    errorResponseDatas[(int)type] = responseData;
                    if (type == ResponseState.NotFound404)
                    {
                        byte[] html          = Encoding.UTF8.GetBytes("<html><head>" + AutoCSer.WebView.CharsetTypeAttribute.GetHtml(AutoCSer.WebView.CharsetType.Utf8) + "<title>404 Error, 请将链接中的 #! 或者 # 修改为 ?</title></head><body>404 Error, 请将链接中的 #! 或者 # 修改为 ?</body></html>");
                        byte[] contentLength = EncodingCache.Ascii.GetBytesNotEmpty(AutoCSerServer + "Content-Length: " + html.Length.toString() + @"

");
                        searchEngine404Data = new byte[httpVersionSize + stateData.Length + contentLength.Length + html.Length];
                        fixed(byte *responseDataFixed = searchEngine404Data)
                        {
                            writeHttpVersion(responseDataFixed);
                            state.Write(responseDataFixed + httpVersionSize);
                        }

                        System.Buffer.BlockCopy(contentLength, 0, searchEngine404Data, index = httpVersionSize + stateData.Length, contentLength.Length);
                        System.Buffer.BlockCopy(html, 0, searchEngine404Data, index         += contentLength.Length, html.Length);
                    }
                }
            }
        }
Пример #2
0
        /// <summary>
        /// HTTP 响应头部输出
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private bool responseHeader(ref Response response)
        {
            try
            {
                if (!response.IsFile)
                {
                    ResponseError(ResponseState.NotFound404);
                    return true;
                }
                System.Net.Sockets.Socket socket;
                ResponseFlag responseFlag = response.Flag;
                if (response.Body.Length != 0 && Header.IsKeepAlive != 0 && (responseFlag & ResponseFlag.HeaderSize) != 0 && Header.IsRange == 0 && Header.Method != MethodType.HEAD)
                {
                    if ((socket = Socket) == null) return false;
                    Data = response.Body;
                    Data.MoveStart(-response.HeaderSize);
                    SendType = SendType.Next;
                    Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                    SocketError socketError;
                    IAsyncResult async = socket.BeginSend(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                    if (socketError == SocketError.Success)
                    {
                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                        return true;
                    }
                    return false;
#else
                    sendAsyncLock.EnterSleepFlag();
                    sendAsyncEventArgs.SetBuffer(Data.Array, Data.Start, Data.Length);
                    if (socket.SendAsync(sendAsyncEventArgs))
                    {
                        sendAsyncLock.SleepFlag = 0;
                        Http.Header.ReceiveTimeout.Push(this, socket);
                        sendAsyncLock.Exit();
                        return true;
                    }
                    sendAsyncLock.ExitSleepFlag();
                    if (--sendDepth == 0)
                    {
                        sendDepth = maxSendDepth;
                        OnSendThreadArray.Default.CurrentThread.Add(this);
                        return true;
                    }
                    return onSend();
#endif
                }
                ResponseSize = response.BodySize;
                fixed (byte* headerBufferFixed = Header.Buffer.GetFixedBuffer())
                {
                    byte* responseSizeFixed = headerBufferFixed + (Header.Buffer.StartIndex + Http.Header.ReceiveBufferSize);
                    RangeLength responseSizeIndex, bodySizeIndex = new RangeLength(), rangeStartIndex = new RangeLength(), rangeEndIndex = new RangeLength();
                    ResponseState state = response.ResponseState;
                    if (Header.IsRange != 0 && (responseFlag & ResponseFlag.IsPool) != 0)
                    {
                        if (Header.IsFormatRange != 0 || Header.FormatRange(ResponseSize))
                        {
                            if (state == ResponseState.Ok200)
                            {
                                long rangeStart = Header.RangeStart, rangeEnd = Header.RangeEnd;
                                rangeStartIndex = NumberExtension.ToBytes((ulong)rangeStart, responseSizeFixed + 20 * 2);
                                rangeEndIndex = NumberExtension.ToBytes((ulong)rangeEnd, responseSizeFixed + 20 * 3);
                                bodySizeIndex = NumberExtension.ToBytes((ulong)ResponseSize, responseSizeFixed + 20);
                                response.State = state = ResponseState.PartialContent206;
                                ResponseSize = Header.RangeSize;
                            }
                        }
                        else
                        {
                            ResponseSize = 0;
                            ResponseError(ResponseState.RangeNotSatisfiable416);
                            return true;
                        }
                    }
                    if ((ulong)ResponseSize < 10)
                    {
                        *responseSizeFixed = (byte)((int)ResponseSize + '0');
                        responseSizeIndex = new RangeLength(0, 1);
                    }
                    else responseSizeIndex = NumberExtension.ToBytes((ulong)ResponseSize, responseSizeFixed);
                    ResponseStateAttribute stateAttribute = EnumAttribute<ResponseState, ResponseStateAttribute>.Array((byte)state);
                    if (stateAttribute == null) stateAttribute = EnumAttribute<ResponseState, ResponseStateAttribute>.Array((byte)ResponseState.ServerError500);
                    int index = httpVersionSize + stateAttribute.Text.Length + contentLengthSize + responseSizeIndex.Length + 2 + 2;
                    if (state == ResponseState.PartialContent206)
                    {
                        index += rangeSize + rangeStartIndex.Length + rangeEndIndex.Length + bodySizeIndex.Length + 2 + 2;
                    }
                    Cookie cookie = null;
                    SubBuffer.PoolBufferFull buffer = GetBuffer(index = GetResponseHeaderIndex(response, index, ref cookie));
                    fixed (byte* bufferFixed = buffer.GetFixedBuffer())
                    {
                        byte* bufferStart = bufferFixed + buffer.StartIndex, write = bufferStart + httpVersionSize;
                        writeHttpVersion(bufferStart);
                        stateAttribute.Write(write);
                        writeContentLength(write += stateAttribute.Text.Length);
                        AutoCSer.Memory.Common.SimpleCopyNotNull64(responseSizeFixed + responseSizeIndex.Start, write += contentLengthSize, responseSizeIndex.Length);
                        *(short*)(write += responseSizeIndex.Length) = 0x0a0d;
                        write += sizeof(short);
                        if (state == ResponseState.PartialContent206)
                        {
                            writeRange(write);
                            AutoCSer.Memory.Common.SimpleCopyNotNull64(responseSizeFixed + (rangeStartIndex.Start + 20 * 2), write += rangeSize, rangeStartIndex.Length);
                            *(write += rangeStartIndex.Length) = (byte)'-';
                            AutoCSer.Memory.Common.SimpleCopyNotNull64(responseSizeFixed + (rangeEndIndex.Start + 20 * 3), ++write, rangeEndIndex.Length);
                            *(write += rangeEndIndex.Length) = (byte)'/';
                            AutoCSer.Memory.Common.SimpleCopyNotNull64(responseSizeFixed + (bodySizeIndex.Start + 20), ++write, bodySizeIndex.Length);
                            *(short*)(write += bodySizeIndex.Length) = 0x0a0d;
                            write += sizeof(short);
                        }
                        index = (int)(CreateResponseHeader(response, cookie, write, index) - bufferStart);
                        //                    if (checkIndex != index)
                        //                    {
                        //                        Server.RegisterServer.TcpServer.Log.add(Log.Type.Fatal, "responseHeader checkIndex[" + checkIndex.toString() + "] != index[" + index.toString() + @"]
                        //" + System.Text.Encoding.ASCII.GetString(buffer.Buffer, buffer.StartIndex, index));
                        //                    }
                        if (ResponseSize != 0)
                        {
                            switch (response.Type)
                            {
                                case ResponseType.ByteArray:
                                    if (buffer.Length - index >= (int)ResponseSize)
                                    {
                                        System.Buffer.BlockCopy(response.Body.Array, state == ResponseState.PartialContent206 ? (int)Header.RangeStart : 0, buffer.Buffer, buffer.StartIndex + index, (int)ResponseSize);
                                        index += (int)ResponseSize;
                                        ResponseSize = 0;
                                    }
                                    break;
                                case ResponseType.SubByteArray:
                                    if (Header.IsKeepAlive != 0 && (responseFlag & ResponseFlag.CanHeaderSize) != 0 && index <= response.Body.Start && Header.IsRange == 0)
                                    {
                                        if ((socket = Socket) == null) return false;
                                        fixed (byte* bodyFixed = response.Body.GetFixedBuffer()) AutoCSer.Memory.Common.CopyNotNull(bufferStart, bodyFixed + response.Body.Start - index, index);
                                        response.SetHeaderSize(index);

                                        Data = response.Body;
                                        Data.MoveStart(-response.HeaderSize);
                                        SendType = SendType.Next;
                                        Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                                    SocketError socketError;
                                    IAsyncResult async = socket.BeginSend(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                                    if (socketError == SocketError.Success)
                                    {
                                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                        return true;
                                    }
                                    return false;
#else
                                        sendAsyncLock.EnterSleepFlag();
                                        sendAsyncEventArgs.SetBuffer(Data.Array, Data.Start, Data.Length);
                                        if (socket.SendAsync(sendAsyncEventArgs))
                                        {
                                            sendAsyncLock.SleepFlag = 0;
                                            Http.Header.ReceiveTimeout.Push(this, socket);
                                            sendAsyncLock.Exit();
                                            return true;
                                        }
                                        sendAsyncLock.ExitSleepFlag();
                                        if (--sendDepth == 0)
                                        {
                                            sendDepth = maxSendDepth;
                                            OnSendThreadArray.Default.CurrentThread.Add(this);
                                            return true;
                                        }
                                        return onSend();
#endif
                                    }
                                    goto COPY;
                                case ResponseType.SubBuffer:
                                    COPY:
                                    if (buffer.Length - index >= (int)ResponseSize)
                                    {
                                        System.Buffer.BlockCopy(response.Body.Array, state == ResponseState.PartialContent206 ? response.Body.Start + (int)Header.RangeStart : response.Body.Start, buffer.Buffer, buffer.StartIndex + index, (int)ResponseSize);
                                        index += (int)ResponseSize;
                                        ResponseSize = 0;
                                    }
                                    break;
                            }
                        }
                    }
                    if ((socket = Socket) != null)
                    {
                        if (ResponseSize == 0) SendType = SendType.Next;
                        else
                        {
                            this.HttpResponse = response;
                            SendType = SendType.Body;
                            response = null;
                        }
                        Data.Set(buffer.Buffer, buffer.StartIndex, index);
                        Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                    SocketError socketError;
                    IAsyncResult async = socket.BeginSend(Data.Array, Data.Start, index, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                    if (socketError == SocketError.Success)
                    {
                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                        return true;
                    }
                    return false;
#else
                        sendAsyncLock.EnterSleepFlag();
                        sendAsyncEventArgs.SetBuffer(Data.Array, Data.Start, index);
                        if (socket.SendAsync(sendAsyncEventArgs))
                        {
                            sendAsyncLock.SleepFlag = 0;
                            Http.Header.ReceiveTimeout.Push(this, socket);
                            sendAsyncLock.Exit();
                            return true;
                        }
                        sendAsyncLock.ExitSleepFlag();
                        if (--sendDepth == 0)
                        {
                            sendDepth = maxSendDepth;
                            OnSendThreadArray.Default.CurrentThread.Add(this);
                            return true;
                        }
                        return onSend();
#endif
                    }
                }
            }
            catch (Exception error)
            {
                Server.RegisterServer.TcpServer.Log.Exception(error, null, LogLevel.Exception | LogLevel.AutoCSer);
            }
            finally { Http.Response.Push(ref response); }
            return false;
        }
Пример #3
0
        /// <summary>
        /// HTTP 响应头部输出
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private bool responseHeader(ref Response response)
        {
            try
            {
                if (!response.IsFile)
                {
                    ResponseError(ResponseState.NotFound404);
                    return(true);
                }
                System.Net.Sockets.Socket socket;
                ResponseFlag responseFlag = response.Flag;
                if (response.Body.Length != 0 && Header.IsKeepAlive != 0 && (responseFlag & ResponseFlag.HeaderSize) != 0 && Header.IsRange == 0 && Header.Method != MethodType.HEAD)
                {
                    if ((socket = Socket) == null)
                    {
                        return(false);
                    }
                    Data = response.Body;
                    Data.MoveStart(-response.HeaderSize);
                    SendType = SendType.Next;
                    ushort timeoutCount;
                    Timeout = Config.GetTimeout(Data.Length, out timeoutCount);
                    if (!SslStream.BeginWrite(Data.Array, Data.Start, Data.Length, sendCallback, this).CompletedSynchronously)
                    {
                        Http.Header.ReceiveTimeout.Push(this, socket, timeoutCount);
                    }
                    return(true);
                }
                ResponseSize = response.BodySize;
                fixed(byte *headerBufferFixed = Header.Buffer.Buffer)
                {
                    byte *        responseSizeFixed = headerBufferFixed + (Header.Buffer.StartIndex + Http.Header.ReceiveBufferSize);
                    RangeLength   responseSizeIndex, bodySizeIndex = new RangeLength(), rangeStartIndex = new RangeLength(), rangeEndIndex = new RangeLength();
                    ResponseState state = response.ResponseState;

                    if (Header.IsRange != 0 && (responseFlag & ResponseFlag.IsPool) != 0)
                    {
                        if (Header.IsFormatRange != 0 || Header.FormatRange(ResponseSize))
                        {
                            if (state == ResponseState.Ok200)
                            {
                                long rangeStart = Header.RangeStart, rangeEnd = Header.RangeEnd;
                                rangeStartIndex = Number.ToBytes((ulong)rangeStart, responseSizeFixed + 20 * 2);
                                rangeEndIndex   = Number.ToBytes((ulong)rangeEnd, responseSizeFixed + 20 * 3);
                                bodySizeIndex   = Number.ToBytes((ulong)ResponseSize, responseSizeFixed + 20);
                                response.State  = state = ResponseState.PartialContent206;
                                ResponseSize    = Header.RangeSize;
                            }
                        }
                        else
                        {
                            ResponseSize = 0;
                            ResponseError(ResponseState.RangeNotSatisfiable416);
                            return(true);
                        }
                    }
                    if ((ulong)ResponseSize < 10)
                    {
                        *responseSizeFixed = (byte)((int)ResponseSize + '0');
                        responseSizeIndex = new RangeLength(0, 1);
                    }
                    else
                    {
                        responseSizeIndex = Number.ToBytes((ulong)ResponseSize, responseSizeFixed);
                    }
                    ResponseStateAttribute stateAttribute = EnumAttribute <ResponseState, ResponseStateAttribute> .Array((byte)state);

                    if (stateAttribute == null)
                    {
                        stateAttribute = EnumAttribute <ResponseState, ResponseStateAttribute> .Array((byte)ResponseState.ServerError500);
                    }
                    int index = httpVersionSize + stateAttribute.Text.Length + contentLengthSize + responseSizeIndex.Length + 2 + 2;

                    if (state == ResponseState.PartialContent206)
                    {
                        index += rangeSize + rangeStartIndex.Length + rangeEndIndex.Length + bodySizeIndex.Length + 2 + 2;
                    }
                    Cookie cookie = null;

                    SubBuffer.PoolBufferFull buffer = GetBuffer(index = GetResponseHeaderIndex(response, index, ref cookie));
                    fixed(byte *bufferFixed = buffer.Buffer)
                    {
                        byte *bufferStart = bufferFixed + buffer.StartIndex, write = bufferStart + httpVersionSize;

                        writeHttpVersion(bufferStart);
                        stateAttribute.Write(write);
                        writeContentLength(write += stateAttribute.Text.Length);
                        Memory.SimpleCopyNotNull64(responseSizeFixed + responseSizeIndex.Start, write += contentLengthSize, responseSizeIndex.Length);
                        *(short *)(write += responseSizeIndex.Length) = 0x0a0d;
                        write += sizeof(short);
                        if (state == ResponseState.PartialContent206)
                        {
                            writeRange(write);
                            Memory.SimpleCopyNotNull64(responseSizeFixed + (rangeStartIndex.Start + 20 * 2), write += rangeSize, rangeStartIndex.Length);
                            *(write += rangeStartIndex.Length) = (byte)'-';
                            Memory.SimpleCopyNotNull64(responseSizeFixed + (rangeEndIndex.Start + 20 * 3), ++write, rangeEndIndex.Length);
                            *(write += rangeEndIndex.Length) = (byte)'/';
                            Memory.SimpleCopyNotNull64(responseSizeFixed + (bodySizeIndex.Start + 20), ++write, bodySizeIndex.Length);
                            *(short *)(write += bodySizeIndex.Length) = 0x0a0d;
                            write += sizeof(short);
                        }
                        index = (int)(CreateResponseHeader(response, cookie, write, index) - bufferStart);
                        //                    if (checkIndex != index)
                        //                    {
                        //                        Server.RegisterServer.TcpServer.Log.add(Log.Type.Fatal, "responseHeader checkIndex[" + checkIndex.toString() + "] != index[" + index.toString() + @"]
                        //" + System.Text.Encoding.ASCII.GetString(buffer.Buffer, buffer.StartIndex, index));
                        //                    }
                        if (ResponseSize != 0)
                        {
                            switch (response.Type)
                            {
                            case ResponseType.ByteArray:
                                if (buffer.Length - index >= (int)ResponseSize)
                                {
                                    System.Buffer.BlockCopy(response.Body.Array, state == ResponseState.PartialContent206 ? (int)Header.RangeStart : 0, buffer.Buffer, buffer.StartIndex + index, (int)ResponseSize);
                                    index       += (int)ResponseSize;
                                    ResponseSize = 0;
                                }
                                break;

                            case ResponseType.SubByteArray:
                                if (Header.IsKeepAlive != 0 && (responseFlag & ResponseFlag.CanHeaderSize) != 0 && index <= response.Body.Start && Header.IsRange == 0)
                                {
                                    if ((socket = Socket) == null)
                                    {
                                        return(false);

                                        fixed(byte *bodyFixed = response.Body.Array) Memory.CopyNotNull(bufferStart, bodyFixed + response.Body.Start - index, index);

                                        response.SetHeaderSize(index);

                                        Data = response.Body;
                                        Data.MoveStart(-response.HeaderSize);
                                        SendType = SendType.Next;
                                        ushort timeoutCount;
                                        Timeout = Config.GetTimeout(Data.Length, out timeoutCount);
                                        if (!SslStream.BeginWrite(Data.Array, Data.Start, Data.Length, sendCallback, this).CompletedSynchronously)
                                        {
                                            Http.Header.ReceiveTimeout.Push(this, socket, timeoutCount);
                                        }
                                        return(true);
                                }
                                goto COPY;

                            case ResponseType.SubBuffer:
COPY:
                                if (buffer.Length - index >= (int)ResponseSize)
                                {
                                    System.Buffer.BlockCopy(response.Body.Array, state == ResponseState.PartialContent206 ? response.Body.Start + (int)Header.RangeStart : response.Body.Start, buffer.Buffer, buffer.StartIndex + index, (int)ResponseSize);
                                    index       += (int)ResponseSize;
                                    ResponseSize = 0;
                                }
                                break;
                            }
                        }
                    }
                    if ((socket = Socket) != null)
                    {
                        if (ResponseSize == 0)
                        {
                            SendType = SendType.Next;
                        }
                        else
                        {
                            this.HttpResponse = response;
                            SendType          = SendType.Body;
                            response          = null;
                        }
                        Timeout = Config.GetTimeout(index);
                        if (!SslStream.BeginWrite(buffer.Buffer, buffer.StartIndex, index, sendCallback, this).CompletedSynchronously)
                        {
                            Http.Header.ReceiveTimeout.Push(this, socket);
                        }
                        return(true);
                    }
                }
            }
            catch (Exception error)
            {
                Server.RegisterServer.TcpServer.Log.Add(Log.LogType.Error, error);
            }
            finally { Http.Response.Push(ref response); }
            return(false);
        }