Jump to content
Sign in to follow this  
MachinistProgrammer

traysetonevent not working

Recommended Posts

MachinistProgrammer

hello again it is i and im still working on my HTTP server I got cgi working (not properly) and i was working on the tray, but it seems traysetonevent isn't working have i missed somthing ?

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Version=Beta
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_requestedExecutionLevel=asInvoker
#AutoIt3Wrapper_Run_AU3Check=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
;#Netux_scriptable_webserver.au3#==================================
;File Name.......:Netux_scriptable_webserver.au3
;Creator.........:sean.campbell7
;Created with....:Created with ISN AutoIt Studio
;Version.........:0.91 BETA
;=============================================
Opt("TrayOnEventMode", 1)
Opt("TrayMenuMode", 1)

#include <Misc.au3> ; Only used for _Iif
#include <file.au3>
#include <Array.au3>
Local $Dlog = @ScriptDir & "\Logs\NetuX_log_" & @MDAY & "_" & @MON & "_" & @YEAR & ".log"
Local $autoit = @AutoItExe
OnAutoItExitRegister("_exit")

; // OPTIONS HERE //
Local $intcfg = @ScriptDir & "\CFG\init.ini"
Local $CGIcfg = @ScriptDir & "\CFG\CGI.ini"

Local $sRootDir = @ScriptDir & "\" & IniRead($intcfg, "Main", "MD", "Webroot")
Local $sIP = @IPAddress1
if IniRead($intcfg, "Main", "Uselocal", "false") = "true" Then
    $sIP = "127.0.0.1"
EndIf
Local $iPort = 80 ; the listening port
Local $sServerAddress = "http://" & $sIP & "/"
Local $sServerName = "NetuX/1.3 (" & @OSVersion & ") AutoIt " & @AutoItVersion
; // END OF OPTIONS //

Local $aSocket[1] ; Creates an array to store all the possible users
Local $sBuffer[1] ; All these users have buffers when sending/receiving, so we need a place to store those

TCPStartup() ; AutoIt needs to initialize the TCP functions

$iMainSocket = TCPListen($sIP, $iPort) ;create main listening socket
If @error Then ; if you fail creating a socket, exit the application
    MsgBox(266256, "NetuX 1.3", "Error : NetuX cannot establish a listening port check to see of any other" & @CRLF & "server software is running", 0)
    _log("Error : Unknown Host Exeption, Exiting")
    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.
EndIf

ConsoleWrite("Server established on : " & $sServerAddress & @CRLF) ; If you're in SciTE,
_log("established server : " & $sServerAddress)
$exit = TrayCreateItem("Exit NetuX Server")
TraySetOnEvent($exit,"_exit")
TraySetState()
While 1
    $iNewSocket = TCPAccept($iMainSocket) ; Tries to accept incoming connections
    
    If $iNewSocket >= 0 Then ; Verifies that there actually is an incoming connection
        Local $user = UBound($aSocket) ; some code to allow infinate users
        ReDim $aSocket[$user + 1]
        ReDim $sBuffer[$user + 1]
        $aSocket[$user] = $iNewSocket
        ConsoleWrite("New Client : " & TCPSocketToIP($iNewSocket) & @CRLF)
        _log("Client connected on : " & TCPSocketToIP($iNewSocket))
    EndIf
    For $x = 0 to UBound($aSocket) - 1 ; A big loop to receive data from everyone connected
        $sNewData = TCPRecv($aSocket[$x], 1024) ; Receives a whole lot of data if possible
        If $sNewData Then ; data received
            $sBuffer[$x] &= $sNewData ;store it in the buffer
            If StringInStr(StringStripCR($sBuffer[$x]), @LF & @LF) Then ; if the request has ended ..
                $sFirstLine = StringLeft($sBuffer[$x], StringInStr($sBuffer[$x], @LF)) ; helps to get the type of the request
                $sRequestType = StringLeft($sFirstLine, StringInStr($sFirstLine, " ") - 1) ; gets the type of the request
                If $sRequestType = "GET" Then ; user wants to download a file or whatever ..
                    $sRequest = StringTrimRight(StringTrimLeft($sFirstLine, 4), 11) ; let's see what file he actually wants
                    If StringInStr(StringReplace($sRequest, "\", "/"), "/.") Then ; Disallow any attempts to go back a folder
                        _HTTP_Send400($aSocket[$x]) ; sends back an error
                        ConsoleWrite("Client requested bad address" & @CRLF)
                        _log("Error : code 400 requested bad address")
                    Else
                        If $sRequest = "/" Then ; user has requested the root
                            if FileExists($sRootDir & "\index.htm") Then
                                $sRequest = "/index.htm"
                            ElseIf FileExists($sRootDir & "\index.htm") Then
                                $sRequest = "/index.html"
                            ElseIf FileExists($sRootDir & "\index.au3") Then
                                $sRequest = "/index.au3"
                            EndIf
                        EndIf
                        
                        $sRequest = StringReplace($sRequest, "/", "\") ; convert HTTP slashes to windows slashes, not really required because windows accepts both
                        If FileExists($sRootDir & "\" & $sRequest) Then ; makes sure the file that the user wants exists
                            $sFileType = StringRight($sRequest, 4) ; determines the file type, so that we may choose what mine type to use
                            Switch $sFileType
                                Case "html", ".htm" ; in case of normal HTML files
                                    _HTTP_SendFile($aSocket[$x], $sRootDir & $sRequest, "text/html")
                                Case ".css" ; in case of style sheets
                                    _HTTP_SendFile($aSocket[$x], $sRootDir & $sRequest, "text/css")
                                Case ".jpg", "jpeg" ; for common images
                                    _HTTP_SendFile($aSocket[$x], $sRootDir & $sRequest, "image/jpeg")
                                Case ".png" ; another common image format
                                    _HTTP_SendFile($aSocket[$x], $sRootDir & $sRequest, "image/png")
                                Case Else ; this is for .exe, .zip, or anything else that is not supported is downloaded to the client using a application/octet-stream
                                    if _isCGIscript($sFileType) Then
                                        _autodetectscript($sRequest, $aSocket[$x])
                                    Else
                                        _HTTP_SendFile($aSocket[$x], $sRootDir & $sRequest, "application/octet-stream")
                                    EndIf
                            EndSwitch
                        Else
                            _autodetectscript($sRequest, $aSocket[$x])
                        EndIf
                    EndIf
                ElseIf $sRequestType = "POST" Then ; user has come to us with data, we need to parse that data and based on that do something special
                    
                    $aPOST = _HTTP_GetPost($sBuffer[$x]) ; parses the post data
                    
                    $sComment = _HTTP_POST("wintext", $aPOST) ; Like PHPs _POST, but it requires the second parameter to be the return value from _Get_Post
                    
                    _HTTP_ConvertString($sComment) ; Needs to convert the POST HTTP string into a normal string
                    
                    ConsoleWrite($sComment)
                    
                    $data = FileRead($sRootDir & "\template.html")
                    $data = StringReplace($data, "<?au3 Replace me ?>", $sComment)
                    
                    $h = FileOpen($sRootDir & "\index.html", 2)
                    FileWrite($h, $data)
                    FileClose($h)
                    
                    $h = FileOpen($sRootDir & "\clean.html", 2)
                    FileWrite($h, $sComment)
                    FileClose($h)
                    
                    _HTTP_SendFile($aSocket[$x], $sRootDir & "\index.html", "text/html") ; Sends back the new file we just created
                EndIf
                
                $sBuffer[$x] = "" ; clears the buffer because we just used to buffer and did some actions based on them
                $aSocket[$x] = -1 ; the socket is automatically closed so we reset the socket so that we may accept new clients
                
            EndIf
        EndIf
    Next
    
    Sleep(10)
WEnd

Func _HTTP_ConvertString(ByRef $sInput) ; converts any characters like %20 into space 8)
    $sInput = StringReplace($sInput, '+', ' ')
    StringReplace($sInput, '%', '')
    For $t = 0 To @extended
        $Find_Char = StringLeft(StringTrimLeft($sInput, StringInStr($sInput, '%')), 2)
        $sInput = StringReplace($sInput, '%' & $Find_Char, Chr(Dec($Find_Char)))
    Next
EndFunc

Func _HTTP_SendHTML($hSocket, $sHTML, $sReply = "200 OK") ; sends HTML data on X socket
    _HTTP_SendData($hSocket, Binary($sHTML), "text/html", $sReply)
EndFunc

Func _HTTP_SendFile($hSocket, $sFileLoc, $sMimeType, $sReply = "200 OK") ; Sends a file back to the client on X socket, with X mime-type
    Local $hFile, $sImgBuffer, $sPacket, $a
    
    ConsoleWrite("Sending " & $sFileLoc & @CRLF)
    
    $hFile = FileOpen($sFileLoc, 16)
    $bFileData = FileRead($hFile)
    FileClose($hFile)
    
    _HTTP_SendData($hSocket, $bFileData, $sMimeType, $sReply)
EndFunc

Func _HTTP_SendData($hSocket, $bData, $sMimeType, $sReply = "200 OK")
    $sPacket = Binary("HTTP/1.1 " & $sReply & @CRLF & _
            "Server: " & $sServerName & @CRLF & _
            "Connection: close" & @CRLF & _
            "Content-Lenght: " & BinaryLen($bData) & @CRLF & _
            "Content-Type: " & $sMimeType & @CRLF & _
            @CRLF)
    TCPSend($hSocket, $sPacket) ; Send start of packet
    
    While BinaryLen($bData) ; Send data in chunks (most code by Larry)
        $a = TCPSend($hSocket, $bData) ; TCPSend returns the number of bytes sent
        $bData = BinaryMid($bData, $a + 1, BinaryLen($bData) - $a)
    WEnd
    
    $sPacket = Binary(@CRLF & @CRLF) ; Finish the packet
    TCPSend($hSocket, $sPacket)
    
    TCPCloseSocket($hSocket)
EndFunc

Func _HTTP_Send404($hSocket) ; Sends back a basic 404 error
    Local $s404Loc = $sRootDir & "\404.html"
    If FileExists($s404Loc) Then
        _HTTP_SendFile($hSocket, $s404Loc, "text/html")
    Else
        _HTTP_SendHTML($hSocket, "<h1>404 Error:</h1><br/>The file you requested could not be found.<br/><br/><i>Netux SND HTTP Server version 1.3</i>", "404 not found")
    EndIf
EndFunc

Func _HTTP_Send400($hSocket) ; Sends back a basic 400 error
    Local $s400Loc = $sRootDir & "\400.html"
    If FileExists($s400Loc) Then
        _HTTP_SendFile($hSocket, $s400Loc, "text/html")
    Else
        _HTTP_SendHTML($hSocket, "<h1>400 Error:</h1><br/>bad or incorrect syntax in address.<br/><br/><i>Netux SND HTTP Server version 1.3</i>", "400 bad")
    EndIf
EndFunc

Func _HTTP_GetPost($s_Buffer) ; parses incoming POST data
    Local $sTempPost, $sLen, $sPostData, $sTemp
    
    ; Get the lenght of the data in the POST
    $sTempPost = StringTrimLeft($s_Buffer, StringInStr($s_Buffer, "Content-Length:"))
    $sLen = StringTrimLeft($sTempPost, StringInStr($sTempPost, ": "))
    
    ; Create the base struck
    $sPostData = StringSplit(StringRight($s_Buffer, $sLen), "&")
    
    Local $sReturn[$sPostData[0] + 1][2]
    
    For $t = 1 To $sPostData[0]
        $sTemp = StringSplit($sPostData[$t], "=")
        If $sTemp[0] >= 2 Then
            $sReturn[$t][0] = $sTemp[1]
            $sReturn[$t][1] = $sTemp[2]
        EndIf
    Next
    
    Return $sReturn
EndFunc

Func _HTTP_Post($sName, $sArray) ; Returns a POST variable like a associative array.
    For $i = 1 to UBound($sArray) - 1
        If $sArray[$i][0] = $sName Then
            Return $sArray[$i][1]
        EndIf
    Next
    Return ""
EndFunc

Func _log($text) ; its just for logging
    if IniRead($intcfg, "Main", "log", "true") = "true" Then
        local $ilog = FileOpen($Dlog, 1)
        FileWrite($ilog, @HOUR & ":" & @MIN & ":" & @SEC & ":" & $text & @CRLF)
    EndIf
EndFunc

Func TCPSocketToIP($SHOCKET) ;from the helpfile
    Local $sockaddr, $aRet
    
    $sockaddr = DllStructCreate("short;ushort;uint;char[8]")
    
    $aRet = DllCall("Ws2_32.dll", "int", "getpeername", "int", $SHOCKET, _
            "ptr", DllStructGetPtr($sockaddr), "int*", DllStructGetSize($sockaddr))
    If Not @error And $aRet[0] = 0 Then
        $aRet = DllCall("Ws2_32.dll", "str", "inet_ntoa", "int", DllStructGetData($sockaddr, 3))
        If Not @error Then $aRet = $aRet[0]
    Else
        $aRet = 0
    EndIf
    
    $sockaddr = 0
    
    Return $aRet
EndFunc ;==>SocketToIP

Func _autodetectscript($request, $hSocket)
    $snp = StringSplit($request, "?")
    If FileExists($sRootDir & $snp[1]) Then
        $ipid = Run(_CGIgetexe($snp[1]) & ' "' & $sRootDir & $snp[1] & '"', '', '', 0x8)
        Local $data
        while ProcessExists($ipid)
            Sleep(100)
        wend
        $data = StdoutRead($ipid)
        Sleep(100) ;dont know why it needs to sleep it just dose
        _HTTP_SendHtml($hSocket, $data)
    Else
        _HTTP_Send404($hSocket)
    EndIf
EndFunc

Func _exit()
    _log("Server Closed")
    Exit
EndFunc

Func _isCGIscript($file)
    $cgidet = IniRead($CGIcfg,"Main","CGI.bindExt","")
    $aCFG = StringSplit($cgidet,",")
    for $i = 1 to $aCFG[0]
        $str = StringSplit($aCFG[$i],">")
        if _filegetext($file) = $str[1] Then
            Return True
        EndIf
    Next
    Return False
EndFunc

Func _CGIgetexe($file)
    $cgidet = IniRead($CGIcfg,"Main","CGI.bindExt","")
    $aCFG = StringSplit($cgidet,",")
    for $i = 1 to $aCFG[0]
        $str = StringSplit($aCFG[$i],">")
        if _filegetext($file) = $str[1] Then
            _ArrayAdd($str,"")
            Return  $str[2]
        EndIf
    Next
EndFunc
Func _filegetext($sString)
    $aString = StringSplit($sString,".")
    Return $aString[$aString[0]]
EndFunc

All my projects live on github

Share this post


Link to post
Share on other sites
BrewManNH

Yes, the explanation of what isn't working with your tray events. Other than the fact you have nearly created an endless loop by having the OnAutoItExitRegister("_exit") function calling itself as soon as you try to exit the script.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×