Juno_okyo

Basic web server

Dec 16th, 2014
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
AutoIt 8.20 KB | None | 0 0
  1. #cs
  2. Resources:
  3.     Internet Assigned Number Authority - all Content-Types: http://www.iana.org/assignments/media-types/
  4.     World Wide Web Consortium - An overview of the HTTP protocol: http://www.w3.org/Protocols/
  5.  
  6. Credits:
  7.     Manadar for starting on the webserver.
  8.     Alek for adding POST and some fixes
  9.     Creator for providing the "application/octet-stream" MIME type.
  10. #ce
  11.  
  12. #region
  13. #AutoIt3Wrapper_Compression=4
  14. #AutoIt3Wrapper_Icon=E:\Program Files\AutoIt3\install\Aut2Exe\Icons\favicon.ico
  15. #AutoIt3Wrapper_UseUpx=Y
  16. #AutoIt3Wrapper_Res_Comment=Code by Juno_okyo
  17. #AutoIt3Wrapper_Res_Description=Code by Juno_okyo
  18. #AutoIt3Wrapper_Res_Fileversion=1.0.0.0
  19. #AutoIt3Wrapper_Res_ProductVersion=1.0.0.0
  20. #AutoIt3Wrapper_Res_LegalCopyright=(c) 2013 by Juno_okyo's Blog
  21. #AutoIt3Wrapper_Res_Field=ProductName|Shutdown GUI
  22. #AutoIt3Wrapper_Res_Field=ProductVersion|1.0.0.0
  23. #AutoIt3Wrapper_Res_SaveSource=N
  24. #endregion
  25.  
  26. #include <Misc.au3>
  27.  
  28. #NoTrayIcon
  29.  
  30. ;=> Kiem tra index.html
  31. If Not FileExists(@ScriptDir & '\index.html') Then
  32.     FileInstall('.\index.html', @ScriptDir & '\index.html')
  33. EndIf
  34.  
  35. ; // OPTIONS HERE //
  36. Local $sRootDir = @ScriptDir ; The absolute path to the root directory of the server.
  37. Local $sIP = '127.0.1.1';@IPAddress1 ; ip address as defined by AutoIt
  38. Local $iPort = 80 ; the listening port
  39. Local $sServerAddress = "http://" & $sIP & ":" & $iPort & "/"
  40. Local $iMaxUsers = 15 ; Maximum number of users who can simultaneously get/post
  41. Local $sServerName = "J2TeaM/1.1 (" & @OSVersion & ") - GhostClub"
  42. ; // END OF OPTIONS //
  43.  
  44. Local $aSocket[$iMaxUsers] ; Creates an array to store all the possible users
  45. Local $sBuffer[$iMaxUsers] ; All these users have buffers when sending/receiving, so we need a place to store those
  46.  
  47. For $x = 0 to UBound($aSocket)-1 ; Fills the entire socket array with -1 integers, so that the server knows they are empty.
  48.    $aSocket[$x] = -1
  49. Next
  50.  
  51. TCPStartup() ; AutoIt needs to initialize the TCP functions
  52.  
  53. $iMainSocket = TCPListen($sIP,$iPort) ;create main listening socket
  54. If @error Then ; if you fail creating a socket, exit the application
  55.    MsgBox(0x20, "AutoIt Webserver", "Unable to create a socket on port " & $iPort & ".") ; notifies the user that the HTTP server will not run
  56.    Exit ; if your server is part of a GUI that has nothing to do with the server, you'll need to remove the Exit keyword and notify the user that the HTTP server will not work.
  57. EndIf
  58.  
  59. ConsoleWrite( "Server created on " & $sServerAddress & @CRLF) ; If you're in SciTE,
  60.  
  61. While 1
  62.     $iNewSocket = TCPAccept($iMainSocket) ; Tries to accept incoming connections
  63.  
  64.     If $iNewSocket >= 0 Then ; Verifies that there actually is an incoming connection
  65.         For $x = 0 to UBound($aSocket)-1 ; Attempts to store the incoming connection
  66.             If $aSocket[$x] = -1 Then
  67.                 $aSocket[$x] = $iNewSocket ;store the new socket
  68.                 ExitLoop
  69.             EndIf
  70.         Next
  71.     EndIf
  72.  
  73.     For $x = 0 to UBound($aSocket)-1 ; A big loop to receive data from everyone connected
  74.         If $aSocket[$x] = -1 Then ContinueLoop ; if the socket is empty, it will continue to the next iteration, doing nothing
  75.         $sNewData = TCPRecv($aSocket[$x],1024) ; Receives a whole lot of data if possible
  76.         If @error Then ; Client has disconnected
  77.             $aSocket[$x] = -1 ; Socket is freed so that a new user may join
  78.             ContinueLoop ; Go to the next iteration of the loop, not really needed but looks oh so good
  79.         ElseIf $sNewData Then ; data received
  80.             $sBuffer[$x] &= $sNewData ;store it in the buffer
  81.             If StringInStr(StringStripCR($sBuffer[$x]),@LF&@LF) Then ; if the request has ended ..
  82.                 $sFirstLine = StringLeft($sBuffer[$x],StringInStr($sBuffer[$x],@LF)) ; helps to get the type of the request
  83.                 $sRequestType = StringLeft($sFirstLine,StringInStr($sFirstLine," ")-1) ; gets the type of the request
  84.                 If $sRequestType = "GET" Then ; user wants to download a file or whatever ..
  85.                     $sRequest = StringTrimRight(StringTrimLeft($sFirstLine,4),11) ; let's see what file he actually wants
  86.                     If StringInStr(StringReplace($sRequest,"\","/"), "/.") Then ; Disallow any attempts to go back a folder
  87.                         _HTTP_SendError($aSocket[$x]) ; sends back an error
  88.                     Else
  89.                         If $sRequest = "/" Then ; user has requested the root
  90.                             $sRequest = "/index.html" ; instead of root we'll give him the index page
  91.                         EndIf
  92.                         $sRequest = StringReplace($sRequest,"/","\") ; convert HTTP slashes to windows slashes, not really required because windows accepts both
  93.                         If FileExists($sRootDir & "\" & $sRequest) Then ; makes sure the file that the user wants exists
  94.                             $sFileType = StringRight($sRequest,4) ; determines the file type, so that we may choose what mine type to use
  95.                             Switch $sFileType
  96.                                 Case "html", ".htm" ; in case of normal HTML files
  97.                                     _HTTP_SendFile($aSocket[$x], $sRootDir & $sRequest, "text/html")
  98.                                 Case ".css" ; in case of style sheets
  99.                                     _HTTP_SendFile($aSocket[$x], $sRootDir & $sRequest, "text/css")
  100.                                 Case ".jpg", "jpeg" ; for common images
  101.                                     _HTTP_SendFile($aSocket[$x], $sRootDir & $sRequest, "image/jpeg")
  102.                                 Case ".png" ; another common image format
  103.                                     _HTTP_SendFile($aSocket[$x], $sRootDir & $sRequest, "image/png")
  104.                                 Case Else ; this is for .exe, .zip, or anything else that is not supported is downloaded to the client using a application/octet-stream
  105.                                     _HTTP_SendFile($aSocket[$x], $sRootDir & $sRequest, "application/octet-stream")
  106.                             EndSwitch
  107.                         Else
  108.                             _HTTP_SendFileNotFoundError($aSocket[$x]) ; File does not exist, so we'll send back an error..
  109.                         EndIf
  110.                     EndIf
  111.                 EndIf
  112.  
  113.                 $sBuffer[$x] = "" ; clears the buffer because we just used to buffer and did some actions based on them
  114.                 $aSocket[$x] = -1 ; the socket is automatically closed so we reset the socket so that we may accept new clients
  115.  
  116.             EndIf
  117.         EndIf
  118.     Next
  119.  
  120.     Sleep(10)
  121. WEnd
  122.  
  123. Func _HTTP_ConvertString(ByRef $sInput) ; converts any characters like %20 into space 8)
  124.     $sInput = StringReplace($sInput, '+', ' ')
  125.     StringReplace($sInput, '%', '')
  126.     For $t = 0 To @extended
  127.         $Find_Char = StringLeft( StringTrimLeft($sInput, StringInStr($sInput, '%')) ,2)
  128.         $sInput = StringReplace($sInput, '%' & $Find_Char, Chr(Dec($Find_Char)))
  129.     Next
  130. EndFunc
  131.  
  132. Func _HTTP_SendHTML($hSocket, $sHTML, $sReply = "200 OK") ; sends HTML data on X socket
  133.     _HTTP_SendData($hSocket, Binary($sHTML), "text/html", $sReply)
  134. EndFunc
  135.  
  136. Func _HTTP_SendFile($hSocket, $sFileLoc, $sMimeType, $sReply = "200 OK") ; Sends a file back to the client on X socket, with X mime-type
  137.     Local $hFile, $sImgBuffer, $sPacket, $a
  138.  
  139.     ConsoleWrite("Sending " & $sFileLoc & @CRLF)
  140.  
  141.     $hFile = FileOpen($sFileLoc,16)
  142.     $bFileData = FileRead($hFile)
  143.     FileClose($hFile)
  144.  
  145.     _HTTP_SendData($hSocket, $bFileData, $sMimeType, $sReply)
  146. EndFunc
  147.  
  148. Func _HTTP_SendError($sSocket) ;; Sends back a basic 404 error
  149.     _HTTP_SendHTML("404 Error: " & @CRLF & @CRLF & "The file you requested could not be found.", $sSocket)
  150. EndFunc
  151.  
  152. Func _HTTP_SendData($hSocket, $bData, $sMimeType, $sReply = "200 OK")
  153.     $sPacket = Binary("HTTP/1.1 " & $sReply & @CRLF & _
  154.     "Server: " & $sServerName & @CRLF & _
  155.     "Connection: close" & @CRLF & _
  156.     "Content-Lenght: " & BinaryLen($bData) & @CRLF & _
  157.     "Content-Type: " & $sMimeType & @CRLF & _
  158.     @CRLF)
  159.     TCPSend($hSocket,$sPacket) ; Send start of packet
  160.  
  161.     While BinaryLen($bData) ; Send data in chunks (most code by Larry)
  162.         $a = TCPSend($hSocket, $bData) ; TCPSend returns the number of bytes sent
  163.         $bData = BinaryMid($bData, $a+1, BinaryLen($bData)-$a)
  164.     WEnd
  165.  
  166.     $sPacket = Binary(@CRLF & @CRLF) ; Finish the packet
  167.     TCPSend($hSocket,$sPacket)
  168.  
  169.     TCPCloseSocket($hSocket)
  170. EndFunc
  171.  
  172. Func _HTTP_SendFileNotFoundError($hSocket) ; Sends back a basic 404 error
  173.     Local $s404Loc = $sRootDir & "\index.html"
  174.     If (FileExists($s404Loc)) Then
  175.         _HTTP_SendFile($hSocket, $s404Loc, "text/html")
  176.     Else
  177.         _HTTP_SendHTML($hSocket, "404 Error: " & @CRLF & @CRLF & "The file you requested could not be found.")
  178.     EndIf
  179. EndFunc
Add Comment
Please, Sign In to add comment