/// <summary> /// 获取数据库连接信息 /// </summary> /// <returns>数据库连接信息</returns> public unsafe Sql.Connection Get() { ProviderAttribute provider = EnumAttribute <Provider, ProviderAttribute> .Array((byte)Provider); byte *buffer = AutoCSer.UnmanagedPool.Default.Get(); try { using (CharStream connectionStream = new CharStream((char *)buffer, AutoCSer.UnmanagedPool.DefaultSize >> 1)) { connectionStream.SimpleWriteNotNull("Provider="); connectionStream.Write(provider.Name); connectionStream.SimpleWriteNotNull(";Data Source="); connectionStream.Write(DataSource); if (Password != null) { connectionStream.WriteNotNull(";Database Password="******";Extended Properties='"); connectionStream.Write(provider.Excel); connectionStream.WriteNotNull(IsTitleColumn ? ";HDR=YES;IMEX=" : ";HDR=NO;IMEX="); AutoCSer.Extension.Number.ToString((byte)Intermixed, connectionStream); connectionStream.Write('\''); return(new Sql.Connection { Type = ClientType.Excel, ConnectionString = connectionStream.ToString() }); } } finally { AutoCSer.UnmanagedPool.Default.Push(buffer); } }
/// <summary> /// 获取数据库连接信息 /// </summary> /// <param name="isPool">是否启用数据库连接池</param> /// <returns>数据库连接信息</returns> public unsafe Sql.Connection Get(bool isPool = false) { ProviderAttribute provider = EnumAttribute <Provider, ProviderAttribute> .Array((byte)Provider); AutoCSer.Memory.Pointer buffer = UnmanagedPool.Default.GetPointer(); try { using (CharStream connectionStream = new CharStream(ref buffer)) { connectionStream.SimpleWrite("Provider="); connectionStream.Write(provider.Name); connectionStream.SimpleWrite(";Data Source="); connectionStream.Write(DataSource); if (Password != null) { connectionStream.Write(";Database Password="******";Extended Properties='"); connectionStream.Write(provider.Excel); connectionStream.Write(IsTitleColumn ? ";HDR=YES;IMEX=" : ";HDR=NO;IMEX="); AutoCSer.Extensions.NumberExtension.ToString((byte)Intermixed, connectionStream); connectionStream.Write('\''); return(new Sql.Connection { Type = ClientKind.Excel, ConnectionString = connectionStream.ToString(), IsPool = isPool }); } } finally { UnmanagedPool.Default.Push(ref buffer); } }
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); } } } }
/// <summary> /// CSharp代码生成器 /// </summary> /// <param name="parameter">安装参数</param> /// <param name="type">模板数据视图</param> /// <param name="language">语言</param> public Coder(ProjectParameter parameter, Type type, CodeLanguage language) : base(type, Messages.Add, Messages.Message) { this.parameter = parameter; extensionName = "." + EnumAttribute <CodeLanguage, CodeLanguageAttribute> .Array((int)(byte)language).ExtensionName; creators[Command.NOTE.ToString()] = note; creators[Command.LOOP.ToString()] = creators[Command.FOR.ToString()] = loop; creators[Command.AT.ToString()] = at; creators[Command.PUSH.ToString()] = push; creators[Command.IF.ToString()] = ifThen; creators[Command.NOT.ToString()] = not; creators[Command.NAME.ToString()] = name; creators[Command.FROMNAME.ToString()] = fromName; creators[Command.PART.ToString()] = part; }
/// <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; }
/// <summary> /// 创建错误输出数据 /// </summary> protected unsafe virtual void createErrorResponse() { KeyValue <Http.Response, Http.Response>[] errorResponses = new KeyValue <Http.Response, Http.Response> [EnumAttribute <Http.ResponseState> .GetMaxValue(-1) + 1]; int isResponse = 0; try { byte[] path = new byte[9]; fixed(byte *pathFixed = path) { *pathFixed = (byte)'/'; *(int *)(pathFixed + sizeof(int)) = '.' + ('h' << 8) + ('t' << 16) + ('m' << 24); *(pathFixed + sizeof(int) * 2) = (byte)'l'; foreach (Http.ResponseState type in System.Enum.GetValues(typeof(Http.ResponseState))) { Http.ResponseStateAttribute state = EnumAttribute <Http.ResponseState, Http.ResponseStateAttribute> .Array((int)type); if (state != null && state.IsError) { int stateValue = state.Number, value = stateValue / 100; *(pathFixed + 1) = (byte)(value + '0'); stateValue -= value * 100; *(pathFixed + 2) = (byte)((value = stateValue / 10) + '0'); *(pathFixed + 3) = (byte)((stateValue - value * 10) + '0'); Http.Response response = null; FileCache fileCache = file(path, default(SubArray <byte>), ref response, true); if (fileCache == null) { if (response != null) { response.CancelPool(); errorResponses[(int)type].Set(response, response); isResponse = 1; } } else { Http.Response gzipResponse; if ((response = fileCache.Response) == null) { response = Http.Response.New(); gzipResponse = Http.Response.New(); SubArray <byte> data = fileCache.Data, gzipData = fileCache.GZipData; if (FileCacheQueue.IsFileCacheHeader && data.Start == FileCache.HttpHeaderSize) { response.SetCanHeaderSize(ref data); gzipResponse.SetCanHeaderSize(ref gzipData); } else { response.SetBody(ref data); gzipResponse.SetBody(ref gzipData); } gzipResponse.SetContentEncoding(Http.Response.GZipEncoding); } else { gzipResponse = fileCache.GZipResponse ?? response; } response.SetState(type); gzipResponse.SetState(type); errorResponses[(int)type].Set(response, gzipResponse); isResponse = 1; } } } } } catch (Exception error) { RegisterServer.TcpServer.Log.Add(AutoCSer.Log.LogType.Error, error); } if (isResponse != 0) { this.errorResponses = errorResponses; } }
/// <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); }