unit UMacron;

interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Forms, ScktComp,
  WinSock, EncdDecd, Graphics, JPEG;

const
  CRLF = #13#10;
  HASH_MAX=255;
  POST_MAX=$00100000;
type

  TCommandMode=(cmGet, cmPost, cmHead, cmError);
  TServerInfo=procedure(Sender:TObject; Info:string) of object;
  TMacronThreadEvent=procedure(Sender:TObject; Socket: TCustomWinSocket) of object;

  TNameValue=record
    Name:string;
    Value:string;
  end;

  TDocument=record
    Size:int64;
    Buffer:array of Byte;
  end;

  TRequest=record
    CommandMode:TCommandMode;
    Path:string;
    Parameters:string;
    Version:string;
    Host:string;
    Accept:string;
    AcceptLanguage:string;
    AcceptEncoding:string;
    UserAgent:string;
    Referer:string;
    ContentType:string;
    ContentLength:string;
    Connection:string;
    CacheControl:string;
    Cookie:string;
  end;

  TMacronItem=record
    Handle: THandle;
    Head:Boolean;
    HeadString:string;
    Request:TRequest;
    BodyLength:Int64;
    BodyReceived:Int64;
    Stream:TMemoryStream;
  end;



  PHashItem=^THashItem;
  THashItem=record
    Handle:THandle;
    Next:PHashItem;
    Item:TMacronItem;
  end;

  THash=class
  private
    FBuckets: array of THashItem;
    FList:TList;
    function GetCount:longInt;
  protected

    function Find(const Socket: THandle): PHashItem;
    function HashOf(const Socket: THandle): Cardinal;
  public
    constructor Create();
    destructor Destroy();override;
    procedure Clear();
    procedure Add(AItem: TMacronItem);
    procedure Remove(Socket: THandle);
    procedure Update(Socket: THandle; AItem: TmacronItem);
    function  GetItem(Socket: THandle):TMacronItem;overload;
    function  GetItem(AIndex: longInt; Head:Boolean):TMacronItem;overload;
    function  Debug:WideString;
    property  Count:longInt read GetCount;
  end;

  TMacronSendThread=class(TThread)
  private
    FSocket:TCustomWinSocket;
    FStream:TMemoryStream;
    FStatus:Integer;
    FOnThreadEvent:TMacronThreadEvent;
  public
    constructor Create(Socket:TCustomWinSocket; Status:Integer; Stream:TMemoryStream; Event:TMacronThreadEvent);
    destructor Destroy();override;
    procedure Execute();override;
  end;

  TMacronReceiveThread=class(TThread)
  private
    FSocket:TCustomWinSocket;
    FStream:TMemoryStream;
    FStatus:Integer;
    FOnThreadDone:TMacronThreadEvent;
  public
    constructor Create(Socket:TCustomWinSocket; Status:Integer; Stream:TMemoryStream);
    destructor Destroy();override;
    procedure Execute();override;
  end;

  TMacron=class         //ʱPOSTPOST <500K
  private
    FServer:TServerSocket;
    FOnServerInfo: TServerInfo;
    FHash:THash;

    FDefaultPage:string;
    FDocument:TDocument;
    FRoot:string;
    FTypeList:TStrings;
    procedure SetRoot(const Value: string);

    procedure SetDefaultPage(const Value: string);

    function  Receiveln(Socket:TCustomWinSocket): string;
//    function  GetValue(ALine,AKey:string):string;
    function  GetNameValue(ALine:string):TNameValue;

    procedure DoServerInfo(AValue:string);
    procedure SetOnServerInfo(const Value: TServerInfo);
    procedure SetActive(const Value: Boolean);
    function  GetActive():Boolean;

    procedure DoRequest(Socket:TCustomWinSocket; Request:TRequest);
    procedure DoGet(Socket:TCustomWinSocket; Request:TRequest);

    procedure LoadDefault(Socket:TCustomWinSocket);

    procedure BuildFileType();
    function  BuildHead(AResult:string; ASize:int64; AType:string; ACookie:string):string;

    procedure ShowCode(Socket: TCustomWinSocket; ACode: string);
    procedure ShowRootFile(Socket:TCustomWinSocket; Request:TRequest);
    procedure ShowServerError(Socket:TCustomWinSocket; ACode:Integer);

    //Server Event
    procedure OnServerListen(Sender:TObject; Socket:TCustomWinSocket);
    procedure OnClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
    procedure OnServerAccept(Sender:TObject; Socket:TCustomWinSocket);
    procedure OnClientRead(Sender:TObject; Socket:TCustomWinSocket);
    procedure OnClientDisconnect(Sender:TObject; Socket:TCustomWinSocket);

    //Thread Event
    procedure OnMacronThreadEvent(Sender:TObject; Socket: TCustomWinSocket);

  public
    constructor Create();
    destructor Destroy();override;

    procedure Open(APort:longInt=80);
    procedure Close();

    function  RndString(iLength:longInt):string;
    function  RndNumString(iLength:longInt):string;
    function  ParseHead(AHeadString:string):TRequest;
    function  BuildReuqest(ANameValue:TNameValue; var ARequest:TRequest):Boolean;
    function  PosEx(AString:string; ASub:string; AStartIndex:longInt):longInt;
    function  Replace(ASource, AOld, ANew: string): string;

    function  AddressEncode(const S: string; const InQueryString: Boolean):string;
    function  AddressDecode(AValue : string):string;

    function  StatusExt(StatusCode:Integer):string;

    property  Active:Boolean read GetActive write SetActive;
    property  OnServerInfo:TServerInfo read FOnServerInfo write SetOnServerInfo;
    property  DefaultPage:string read FDefaultPage write SetDefaultPage;
    property  Root:string read FRoot write SetRoot;
  end;



implementation

{ TMacron }

constructor TMacron.Create;
var
  NewOpenType:Integer;
  nLen:Integer;
begin
  FHash:=THash.Create;
  FServer:=TServerSocket.Create(nil);
  FServer.OnListen:=Self.OnServerListen;
  FServer.OnClientError:=Self.OnClientError;
  FServer.OnAccept:=Self.OnServerAccept;
  FServer.OnClientDisconnect:=Self.OnClientDisconnect;
  FServer.Port:=80;
  FServer.ServerType:=stNonBlocking;
  FServer.OnClientRead:= Self.OnClientRead;
  FTypeList:=TStringList.Create;

  NewOpenType := SO_SYNCHRONOUS_NONALERT;
  nLen:= SizeOf(NewOpenType);
  WinSock.setsockopt(
    FServer.Socket.SocketHandle,
    IPPROTO_TCP,
    TCP_NODELAY,
    PChar(@NewOpenType), nLen
  );
end;

destructor TMacron.Destroy;
begin
  FHash.Clear;
  FServer.Close;

  FHash.Free;
  FServer.Free;
  inherited;
end;

procedure TMacron.DoGet(Socket: TCustomWinSocket; Request: TRequest);
var
  nPosition:longInt;
  sCommand:string;
begin

  nPosition:=Self.PosEx(Request.Path,'/',2);
  if nPosition=0 then nPosition:=MaxInt else nPosition:=nPosition-1;
  sCommand:=System.Copy(Request.Path,1,nPosition);
  try
    if sCommand='/' then Self.LoadDefault(Socket);
    if sCommand='/bim' then Self.ShowServerError(Socket,400);
    if sCommand='/code' then Self.ShowCode(Socket,Self.RndNumString(4));
    if sCommand='/index' then ;
    if sCommand='/image' then ;
    if sCommand='/help' then Self.ShowServerError(Socket,404);
    if sCommand='/about' then ;
    if sCommand='/root' then Self.ShowRootFile(Socket, Request);
    if sCommand='/virtual' then Self.ShowServerError(Socket, 500);


  except
    Self.DoServerInfo('[Server_Debug] Path:' + Request.Path);
  end;
end;

procedure TMacron.DoRequest(Socket: TCustomWinSocket; Request: TRequest);
begin
  case Request.CommandMode of
    cmGet: Self.DoGet(Socket, Request) ;
    cmPost: ;
    cmHead: ;
    cmError: ;
  end;
end;

procedure TMacron.DoServerInfo(AValue: string);
begin
  if Assigned(FOnServerInfo) then FOnServerInfo(Self, AValue);

end;

function TMacron.GetActive: Boolean;
begin
  Result:=FServer.Active;
end;

function TMacron.GetNameValue(ALine: string): TNameValue;
var
  nPos:longInt;
begin
  Result.Name:='';
  Result.Value:='';
  nPos:=System.Pos(':', ALine);
  if nPos=0 then exit;
  Result.Name:=SysUtils.Trim(System.Copy(ALine,1,nPos-1));
  Result.Value:=SysUtils.Trim(System.Copy(ALine,nPos +1 ,MaxInt));
end;

procedure TMacron.LoadDefault(Socket: TCustomWinSocket);
//var
//  nContentLength:Int64;
begin
//  nContentLength:=Length(FDefaultDocument);
  Socket.SendText('HTTP/1.1 200 OK'+#10);
  Socket.SendText('Date:'+FormatDateTime('YYYY-MM-DD HH:mm:ss',Now)+#10);
  Socket.SendText('Server: Bamboo WebServer 1.0'+#10);
  Socket.SendText('Content-Length: '+ IntToStr(FDocument.Size) +#10);
  Socket.SendText('Content-Type: text/html'+#10);
  Socket.SendText('Set-Cookie: BIM=' + Self.RndString(64) + ';'+#10);
  Socket.SendText('Connectlon: close'+#10);
  Socket.SendText(#10);
  Socket.SendBuf(Pointer(FDocument.Buffer)^,FDocument.Size);
  Socket.Close;
end;

//function TMacron.GetValue(ALine, AKey: string): string;
//var
//  nPos:longInt;
//begin
//  Result:='';
//  nPos:=System.Pos(AKey,ALine);
//  if nPos=0 then exit;
//  nPos:=System.Pos(':', ALine);
//  if nPos=0 then exit;
//  Result:=System.Copy(ALine,nPos +1 ,MaxInt);
//end;

procedure TMacron.OnClientDisconnect(Sender: TObject; Socket: TCustomWinSocket);
begin
  FHash.Remove(Socket.Handle);
end;

procedure TMacron.OnClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
  var ErrorCode: Integer);
begin
  Self.DoServerInfo('[Client_Error] ErrorCode: ' + IntToStr(ErrorCode));
  FHash.Remove(Socket.Handle);
  ErrorCode:=0;
end;

procedure TMacron.OnClientRead(Sender: TObject; Socket: TCustomWinSocket);
var
  iReceive:longInt;
  iReceived:longInt;
//  btBuffer:array of Byte;
  btBuffer:array [0..8192] of Byte;
  wsLine:string;
  RMacronItem:TMacronItem;
begin
  RMacronItem:=FHash.GetItem(Socket.Handle);
  if RMacronItem.Handle=0 then exit;
  if (not RMacronItem.Head) then begin
    repeat
      wsLine:=Self.Receiveln(Socket);
      RMacronItem.HeadString:=RMacronItem.HeadString + wsLine + CRLF;
    until (wsLine='') or (wsLine=CRLF);
    RMacronItem.Request:= Self.ParseHead(RMacronItem.HeadString);
    RMacronItem.BodyLength:=SysUtils.StrToInt64Def(RMacronItem.Request.ContentLength, 0);
    if RMacronItem.Request.CommandMode=cmPost then RMacronItem.Stream:=TMemoryStream.Create;

    RMacronItem.Head:=true;
    FHash.Update(Socket.Handle,RMacronItem);
  end;

  iReceive := WinSock.recv(Socket.SocketHandle, btBuffer, sizeof(btBuffer), MSG_PEEK);
  if iReceive > 0 then
  begin
    iReceived:=Socket.ReceiveBuf(btBuffer, iReceive);
    if Assigned(RMacronItem.Stream) then try
      RMacronItem.Stream.Write(btBuffer, iReceived);
    except
    end;
    RMacronItem.BodyReceived:=RMacronItem.BodyReceived + iReceived;
  end;
//  until (iReceive <= 0);

  FHash.Update(Socket.Handle, RMacronItem);//״̬ѽֽڣHeadѹ

  if (RMacronItem.BodyReceived>=RMacronItem.BodyLength) then begin
    Self.DoRequest(Socket, RMacronItem.Request);
//    Socket.Close;
    if Assigned(RMacronItem.Stream) then
    try
//      RMacronItem.Stream.SaveToFile('Debug\Post.txt');
      RMacronItem.Stream.Free;
    except

    end;

//    FHash.Remove(Socket.Handle);

    Self.DoServerInfo('Cookie: ' + RMacronItem.Request.Cookie);
    Self.DoServerInfo('-----------------------------------------------------');
//    Self.DoServerInfo(RMacronItem.HeadString);
  end;


end;

procedure TMacron.OnMacronThreadEvent(Sender: TObject; Socket: TCustomWinSocket);
begin
  if Assigned(Socket) then begin
    Socket.Close;
    FHash.Remove(Socket.Handle);
    Self.DoServerInfo('[ServerThread] CLOSE.');
  end
  else Self.DoServerInfo('[ServerThread] DESTROY.');

end;

procedure TMacron.OnServerAccept(Sender: TObject; Socket: TCustomWinSocket);
var
  RMacronItem:TMacronItem;
begin
  Self.DoServerInfo('[Server_Info] Accept: ' + Socket.LocalHost);
  RMacronItem.Handle :=Socket.Handle;
  RMacronItem.Head:=false;
  RMacronItem.BodyLength:=0;
  RMacronItem.BodyReceived:=0;
  RMacronItem.Stream:=nil;
  FHash.Add(RMacronItem);
end;

procedure TMacron.OnServerListen(Sender: TObject; Socket: TCustomWinSocket);
begin
  Self.DoServerInfo('[Server_Info] Server Starting...'+#13#10+'[Server_Info] Port: ' + IntToStr(FServer.Port));
end;

procedure TMacron.Open(APort: Integer);
begin
  FHash.Clear;
  FServer.Close;
  FServer.Port:=APort;
  try
    FServer.Open;
//    if FServer.Active then FLocalHost:=FServer.Socket.LocalHost;
  except
    FServer.Active:=false;
    Self.DoServerInfo('[Server_Error] Port 80 has been taken.');
  end;
end;

function TMacron.ParseHead(AHeadString: string): TRequest;
var
  nPosition:longInt;
  nPos:longInt;
  wsLine:string;
  wsTemp:string;
begin
  Result.CommandMode:=cmError;
  nPos:=Self.PosEx(AHeadString,#10,1);
  if nPos=0 then exit;
  wsLine:=System.Copy(AHeadString,1,nPos);
  nPosition:=nPos + 1;

  nPos:=System.Pos(' ',wsLine);
  if nPos=0 then exit;
  wsTemp:=System.Copy(wsLine,1,nPos-1);
  if wsTemp<>'' then begin
    if wsTemp='GET' then Result.CommandMode:=cmGet;
    if wsTemp='POST' then Result.CommandMode:=cmPost;
    if wsTemp='HEAD' then Result.CommandMode:=cmHead;
    Self.DoServerInfo('[Server_Work] Action: ' + wsTemp);
  end;

  if Result.CommandMode=cmError then exit;
  wsTemp:=System.Copy(wsLine,nPos + 1,MaxInt);
  nPos:=System.Pos(' ',wsTemp);
  if nPos=0 then Result.CommandMode:=cmError;

  Result.Path:=System.Copy(wsTemp,1,nPos-1);
  Result.Parameters:='';
  Result.Version:=System.Copy(wsTemp,nPos+1,MaxInt);

  nPos:=System.Pos('?',Result.Path);
  if nPos>0 then begin
    wsTemp:=Result.Path;
    Result.Path:=System.Copy(wsTemp,1,nPos-1);
    Result.Parameters:=System.Copy(wsTemp,nPos+1,MaxInt);
  end;


  Self.DoServerInfo('[Server_Work] Path: ' + Result.Path);
  Self.DoServerInfo('[Server_Work] Parameters: ' + Result.Parameters);
  Self.DoServerInfo('[Server_Work] Version: ' + Result.Version);


  while True do begin
    nPos:=Self.PosEx(AHeadString,#10,nPosition);
    if nPos=0 then break;
    wsLine:=System.Copy(AHeadString,nPosition,nPos-nPosition);
    Self.BuildReuqest(Self.GetNameValue(wsLine),Result);
    nPosition:=nPos+1;
  end;

end;

function TMacron.PosEx(AString, ASub: string; AStartIndex: Integer): longInt;
var
  sTemp:string;
  nPosition:longInt;
begin
  if AStartIndex<1 then AStartIndex:=1;
  sTemp:=System.Copy(AString,AStartIndex,Length(AString)-AStartIndex+1);
  nPosition:=System.Pos(ASub,sTemp);
  if nPosition=0 then Result:=0 else Result:=AStartIndex+nPosition-1;
end;

function TMacron.Receiveln(Socket:TCustomWinSocket): string;
var
  len: Integer;
  buf: array [0..1023] of char;
  eolptr: pchar;
  eol:string;
begin
  Result := '';
  eol:=#13#10;
  eolptr := nil;
  repeat
    len := WinSock.recv(Socket.SocketHandle, buf, sizeof(buf) - 1, MSG_PEEK);
    if len > 0 then
    begin
      buf[len] := #0;
      eolptr := StrPos(buf, PChar(eol));
      if eolptr <> nil then
        len := eolptr - buf + Length(eol);
      Socket.ReceiveBuf(buf, len);
      if eolptr <> nil then
        len := len - Length(eol);
      buf[len] := #0;
      Result := Result + buf;
    end;
  until (len < 1) or (eolptr <> nil);
end;

function TMacron.Replace(ASource, AOld, ANew: string): string;
var
  nPosition: longInt;
begin
  nPosition:=1;
  while Self.PosEx(ASource, AOld, nPosition)>0 do begin
    nPosition:=PosEx(ASource, AOld, nPosition);
    System.Delete(ASource, nPosition, Length(AOld));
    System.Insert(ANew, ASource, nPosition);
    nPosition:=nPosition+Length(ANew);
  end;
  Result:=ASource;
end;

function TMacron.RndNumString(iLength: Integer): string;
var
  iCount:longInt;
begin
  Randomize();
  Result:='';
  for iCount := 1 to iLength do begin
    Result:=Result + IntToStr(Random(10));
  end;
end;

function TMacron.RndString(iLength: Integer): string;
var
  iCount:longInt;
begin
  Result:='';
  for iCount := 1 to iLength do begin
    Result:=Result+Chr(Random(26)+65);
  end;
  Result:=Result + #0;
end;

procedure TMacron.SetActive(const Value: Boolean);
begin
  FHash.Clear;
  FServer.Active:= Value;
  if Value then Self.DoServerInfo('[Server_Info] Server is Listing...')
  else Self.DoServerInfo('[Server_Info] Server has stoped.');

end;

procedure TMacron.SetDefaultPage(const Value: string);
var
  iStream:TMemoryStream;
begin
  FDefaultPage := Value;
  iStream:=TMemoryStream.Create;
  try
    iStream.LoadFromFile(FDefaultPage);
    iStream.Position:=0;
    FDocument.Size:=iStream.Size;
    SetLength(FDocument.Buffer,FDocument.Size);
    iStream.Read(Pointer(FDocument.Buffer)^,FDocument.Size);
  except
  end;
  iStream.Free;
end;

function TMacron.AddressDecode(AValue: string): string;
var
  iValue:longInt;
  iBuffer:longInt;
  btBuffer:array of Char;
  c:Char;
begin
  SetLength(btBuffer,Length(AValue));
  iValue:=1;
  iBuffer:=0;
  while(iValue<=length(AValue)) do begin
    c:=AValue[iValue];
    if c='+' then c:=' ';
    if c='%' then begin
      btBuffer[iBuffer]:=Char(SysUtils.StrToIntDef('$'+AValue[iValue+1]+AValue[iValue+2],0));
      inc(iBuffer);
      inc(iValue,3);
    end
    else begin
      btBuffer[iBuffer]:=c;
      inc(iBuffer);
      inc(iValue);
    end;
  end;
  SetLength(btBuffer,iBuffer+1);
  Result:=String(btBuffer);
end;

function TMacron.AddressEncode(const S: string; const InQueryString: Boolean): string;
var
  nIndex: Integer; // loops thru characters in string
begin
  Result := '';
  for nIndex := 1 to Length(S) do
  begin
    case S[nIndex] of
      'A'..'Z', 'a'..'z', '0'..'9', '-', '_', '.':
        Result := Result + S[nIndex];
      ' ':
        if InQueryString then
          Result := Result + '+'
        else
          Result := Result + '%20';
      else
        Result := Result + '%' + SysUtils.IntToHex(Ord(S[nIndex]), 2);
    end;
  end;
end;

procedure TMacron.BuildFileType;
begin
  FTypeList.Clear;
  FTypeList.Add('.htm=text/html');
  FTypeList.Add('.html=text/html');
  FTypeList.Add('.jpg=image/jpeg');
  FTypeList.Add('.jpeg=image/jpeg');
  FTypeList.Add('.gif=image/gif');
  FTypeList.Add('.swf=application/x-shockwave-flash');
  FTypeList.Add('.bmp=image/x-xbitmap');
  FTypeList.Add('.wav=audio/wav');
  FTypeList.Add('.txt=text/plain');
  FTypeList.Add('.js=text/plain');
  FTypeList.Add('.*=application/octet-stream');
  FTypeList.Add('.=*/*');
end;

function TMacron.BuildHead(AResult: string; ASize: int64; AType: string; ACookie:string): string;
begin
  Result:='';
  Result:=Result + ('HTTP/1.1 ' + AResult + ' 0K')+#10;
  Result:=Result + ('Connectlon:close')+#10;
  Result:=Result + ('Date:'+FormatDateTime('YYYY-MM-DD HH:mm:ss',Now)+' (GMT+8:00)')+#10;
  Result:=Result + ('Server: Bamboo WebServer 1.0')+#10;
  Result:=Result + ('Content-Length:'+IntToStr(ASize))+#10;
  Result:=Result + ('Content-Type:'+AType)+#10;
  Result:=Result + ('Set-Cookie: ' + ACookie)+ #10;
  Result:=Result + #10;
end;

function TMacron.BuildReuqest(ANameValue: TNameValue; var ARequest: TRequest): Boolean;
begin
  Result:=(ANameValue.Name<>'');
  if ANameValue.Name='Accept' then ARequest.Accept:=ANameValue.Value;
  if ANameValue.Name='Referer' then ARequest.Referer:=ANameValue.Value;
  if ANameValue.Name='Host' then ARequest.Host:=ANameValue.Value;
  if ANameValue.Name='Accept-Language' then ARequest.AcceptLanguage:=ANameValue.Value;
  if ANameValue.Name='Content-Type' then ARequest.ContentType:=ANameValue.Value;
  if ANameValue.Name='Accept-Encoding' then ARequest.AcceptEncoding:=ANameValue.Value;
  if ANameValue.Name='Cache-Control' then ARequest.CacheControl:=ANameValue.Value;
  if ANameValue.Name='Connection' then ARequest.Connection:=ANameValue.Value;
  if ANameValue.Name='User-Agent' then ARequest.UserAgent:=ANameValue.Value;
  if ANameValue.Name='Content-Length' then ARequest.ContentLength:=ANameValue.Value;
  if ANameValue.Name='Cookie' then ARequest.Cookie:=ANameValue.Value;

end;

procedure TMacron.Close;
begin
  FHash.Clear;
  FServer.Close;
  Self.DoServerInfo('[Server_Info] Server has stoped.');
end;


procedure TMacron.SetOnServerInfo(const Value: TServerInfo);
begin
  FOnServerInfo := Value;
end;


procedure TMacron.SetRoot(const Value: string);
begin
  FRoot := Value;
end;

procedure TMacron.ShowCode(Socket: TCustomWinSocket; ACode: string);
var
  iBuffer:TStream;
  oImage:TJpegImage;
  iBitmap:TBitmap;
begin
  iBuffer:=TMemoryStream.Create;
  iBitmap:=TBitmap.Create;
  oImage:=TJpegImage.Create;

  iBitmap.Canvas.Font.Name:='Arial Black';
  iBitmap.Canvas.Font.Size:=12;
  iBitmap.Width:=50;
  iBitmap.Height:=24;

  iBitmap.Canvas.Pen.Width:=1;

  iBitmap.Canvas.TextOut(3,0,ACode);
  iBitmap.Canvas.MoveTo(0,0);
  iBitmap.Canvas.LineTo(49,0);
  iBitmap.Canvas.LineTo(49,23);
  iBitmap.Canvas.LineTo(0,23);
  iBitmap.Canvas.LineTo(0,0);


  oImage.Assign(iBitmap);
  oImage.SaveToStream(iBuffer);


  Socket.SendText(Self.BuildHead('200',iBuffer.Size,'image/jpeg','SKIRTNO=' + ACode + ';'));
  iBuffer.Position:=0;
  Socket.SendStream(iBuffer); //SendStreamԶͷ iBuffer

  oImage.Free;
  iBitmap.Free;
//  iBuffer.Free; //SendStream ѾiBufferͷţͷŻЧָ쳣ã
  iBuffer:=nil;
  iBuffer.Free;
  Socket.Close;
end;

procedure TMacron.ShowRootFile(Socket: TCustomWinSocket; Request: TRequest);
var
  nPosition:longInt;
  wsFilePath:string;
  wsExt:string;
  wsType:string;
  wsRequestFile:string;
  iStream:TMemoryStream;
  btBuffer:array [0..511] of byte;
  nBufferSize:longInt;
  nResult:longInt;
  iThread:TMacronSendThread;
begin
  wsRequestFile:= Request.Path;
  nPosition:=Self.PosEx(wsRequestFile,'/',2);
  if nPosition=0 then begin
    Self.ShowServerError(Socket,403);
  end
  else begin
    iStream:=TMemoryStream.Create;
    wsRequestFile:=System.Copy(wsRequestFile, nPosition, MaxInt);
    wsRequestFile:=Self.Replace(wsRequestFile,'../','');
    wsRequestFile:=Self.Replace(wsRequestFile,'..\','');
    wsRequestFile:=Self.Replace(wsRequestFile,'/','\');
    wsFilePath:=Self.FRoot + Self.AddressDecode(wsRequestFile);
    if SysUtils.FileExists(wsFilePath) then begin
      try
        iStream.LoadFromFile(wsFilePath);
        wsExt:=LowerCase(SysUtils.ExtractFileExt(wsFilePath));
        wsType:=FTypeList.Values[wsExt];
        if wsType='' then wsType:='application/octet-stream';
        iStream.Position:=0;

//        Socket.SendText(Self.BuildHead('200', iStream.Size, wsType, ''));

        iThread:=TMacronSendThread.Create(Socket,200,iStream, OnMacronThreadEvent);
//        iThread.Execute;

//        repeat
//          nBufferSize := iStream.Read(btBuffer, SizeOf(btBuffer));
//          nResult:= send(Socket.SocketHandle, btBuffer, nBufferSize, 0);
//          sleep(1);
//        until (nBufferSize = 0) or (nResult = SOCKET_ERROR);
//        iStream.Free;

      except
        Socket.Close;
        //Self.ShowServerError(Socket, 404);
      end;
    end
    else begin
      Self.ShowServerError(Socket,404);
    end;

  end;

end;

procedure TMacron.ShowServerError(Socket: TCustomWinSocket; ACode: Integer);
begin
  Socket.SendText('HTTP/1.1 ' + IntToStr(ACode) + ' ' + Self.StatusExt(ACode) + #10);
  Socket.SendText('Server: Bamboo WebServer 1.0' + #10);
  Socket.SendText('Date:'+FormatDateTime('YYYY-MM-DD HH:mm:ss',Now)+' (GMT+8:00)' + #10);
  Socket.SendText('Connectlon:close' + #10);
  Socket.SendText(#10);
end;

function TMacron.StatusExt(StatusCode: Integer): string;
begin
  case StatusCode of
    100: Result := 'Continue';                                 {do not localize}
    101: Result := 'Switching Protocols';                      {do not localize}
    200: Result := 'OK';                                       {do not localize}
    201: Result := 'Created';                                  {do not localize}
    202: Result := 'Accepted';                                 {do not localize}
    203: Result := 'Non-Authoritative Information';            {do not localize}
    204: Result := 'No Content';                               {do not localize}
    205: Result := 'Reset Content';                            {do not localize}
    206: Result := 'Partial Content';                          {do not localize}
    300: Result := 'Multiple Choices';                         {do not localize}
    301: Result := 'Moved Permanently';                        {do not localize}
    302: Result := 'Moved Temporarily';                        {do not localize}
    303: Result := 'See Other';                                {do not localize}
    304: Result := 'Not Modified';                             {do not localize}
    305: Result := 'Use Proxy';                                {do not localize}
    400: Result := 'Bad Request';                              {do not localize}
    401: Result := 'Unauthorized';                             {do not localize}
    402: Result := 'Payment Required';                         {do not localize}
    403: Result := 'Forbidden';                                {do not localize}
    404: Result := 'Not Found';                                {do not localize}
    405: Result := 'Method Not Allowed';                       {do not localize}
    406: Result := 'None Acceptable';                          {do not localize}
    407: Result := 'Proxy Authentication Required';            {do not localize}
    408: Result := 'Request Timeout';                          {do not localize}
    409: Result := 'Conflict';                                 {do not localize}
    410: Result := 'Gone';                                     {do not localize}
    411: Result := 'Length Required';                          {do not localize}
    412: Result := 'Unless True';                              {do not localize}
    500: Result := 'Internal Server Error';                    {do not localize}
    501: Result := 'Not Implemented';                          {do not localize}
    502: Result := 'Bad Gateway';                              {do not localize}
    503: Result := 'Service Unavailable';                      {do not localize}
    504: Result := 'Gateway Timeout';                          {do not localize}
  else
    Result := '';
  end
end;

{ THash }

procedure THash.Add(AItem: TMacronItem);
var
  nIndex: Integer;
  PBucket: PHashItem;
  oItem:THashItem;
begin
  if (AItem.Handle=0) then exit;
  
  nIndex := Self.HashOf(AItem.Handle) mod Cardinal(Length(FBuckets));
  oItem:=FBuckets[nIndex];
  New(PBucket);
  PBucket.Handle := AItem.Handle;
  PBucket.Item := AItem;
  PBucket.Next := oItem.Next;
  oItem.Next:=PBucket;
  FBuckets[nIndex] := oItem;

  FList.Add(PBucket);
end;

procedure THash.Clear;
var
  I: Integer;
  oItem:THashItem;
  P, N: PHashItem;
begin
  FList.Clear;
  for I := 0 to Length(FBuckets) - 1 do
  begin
    oItem:=FBuckets[I];
    P := oItem.Next;
    while P <> nil do begin
      N := P.Next;
//      Self.DoEvent('RemoveKey: ' + P.Key);
      Dispose(P);
      P := N;
    end;
    FBuckets[I].Next := nil;
  end;
end;

constructor THash.Create;
begin
  SetLength(FBuckets,HASH_MAX);
  FList:=TList.Create;
end;

function THash.Debug: WideString;
begin
  //
end;

destructor THash.Destroy;
begin
  Self.Clear;
  FList.Free;
  inherited;
end;

function THash.Find(const Socket: THandle): PHashItem;
var
  nIndex: Integer;
  oItem:THashItem;
begin
  nIndex := HashOf(Socket) mod Cardinal(Length(FBuckets));
  oItem:=FBuckets[nIndex];
  Result := oItem.Next;
  while Result <> nil do
  begin
    if Result.Handle = Socket then Exit
    else Result := Result.Next;
  end;
end;

function THash.GetCount: longInt;
begin
  Result:=FList.Count;
end;

function THash.GetItem(AIndex: Integer; Head:Boolean): TMacronItem;
var
  PItem:PHashItem;
begin
  Result.Handle:=0;
  if (AIndex>-1) and (AIndex<FList.Count) then begin
    PItem:=FList.Items[AIndex];
    Result:=PItem.Item;
  end;
end;

function THash.HashOf(const Socket: THandle): Cardinal;
begin
  Result:=Cardinal(Socket);
end;

function THash.GetItem(Socket: THandle): TMacronItem;
var
  PItem:PHashItem;
begin
  PItem:=Self.Find(Socket);
  if PItem=nil then begin
    Result.Handle:=0;
  end
  else Result:=PItem.Item;
end;

procedure THash.Remove(Socket: THandle);
var
  nIndex: Integer;
  oItem:THashItem;
  P: PHashItem;
  PPrevious: PHashItem;
begin
  nIndex := HashOf(Socket) mod Cardinal(Length(FBuckets));
  oItem:=FBuckets[nIndex];
  P:=oItem.Next;
  PPrevious:=nil;
  while True do begin
    if P=nil then break;
    if (P.Handle = Socket) then begin
      if (PPrevious=nil) then oItem.Next:=P.Next else PPrevious.Next:=P.Next;
//      Self.DoEvent('RemoveSocket: ' + IntToStr(P.Handle));
      FList.Remove(P);
      System.Dispose(P);
      break;
    end
    else begin
      PPrevious:=P;
      P:=P.Next;
    end;
  end;
  FBuckets[nIndex]:=oItem;
end;

procedure THash.Update(Socket: THandle; AItem: TmacronItem);
var
  P: PHashItem;
begin
  P:=Self.Find(Socket);
  if P<> nil then P.Item:=AItem;
  
end;

{ TMacronReceiveThread }

constructor TMacronReceiveThread.Create(Socket: TCustomWinSocket; Status: Integer; Stream: TMemoryStream);
begin
  inherited Create(True);
  FreeOnTerminate := True;
  FSocket:=Socket;
  FStatus:=Status;
  FStream:=Stream;
end;

destructor TMacronReceiveThread.Destroy;
begin

  inherited;
end;

procedure TMacronReceiveThread.Execute;
begin
  inherited;

end;

{ TMacronSendThread }

constructor TMacronSendThread.Create(Socket: TCustomWinSocket; Status: Integer; Stream: TMemoryStream; Event: TMacronThreadEvent);
begin
  inherited Create(false);
  FreeOnTerminate := True;
  FSocket:=Socket;
  FStatus:=Status;
  FStream:=Stream;
  FOnThreadEvent:=Event;
end;

destructor TMacronSendThread.Destroy;
begin
  if Assigned(Self.FOnThreadEvent) then FOnThreadEvent(Self, nil);
  inherited;
end;

procedure TMacronSendThread.Execute;
var
  nResult:LongInt;
  nBufferSize:longInt;
  btBuffer:array [0..511] of Byte;
begin
  inherited;
  FSocket.SendText('HTTP/1.1 200 OK'+#10);
  FSocket.SendText('Date:'+FormatDateTime('YYYY-MM-DD HH:mm:ss',Now)+#10);
  FSocket.SendText('Server: Bamboo WebServer 1.0'+#10);
  FSocket.SendText('Content-Length: '+ IntToStr(FStream.Size) +#10);
  FSocket.SendText('Content-Type: text/html'+#10);
  FSocket.SendText('Connectlon: close'+#10);
  FSocket.SendText(#10);
  FStream.Position:=0;
  repeat
    nBufferSize := FStream.Read(btBuffer, SizeOf(btBuffer));
    nResult:= WinSock.send(FSocket.SocketHandle, btBuffer, nBufferSize, 0);
    sleep(10);
  until (nBufferSize = 0) or (nResult = SOCKET_ERROR);
  FStream.Free;
  if Assigned(Self.FOnThreadEvent) then FOnThreadEvent(Self, FSocket);

end;

end.