Sign in to follow this  
Followers 0
FireFox

Winpcap filter and TCP/UDP packet splitter

5 posts in this topic

#1 ·  Posted (edited)

Hi,

I have worked on a project for a friend and it needed to retreive some data in UDP packets, it was a challenge because I didn't know anything about that packets, and after few days of work I have managed to do what I wanted.

The hardest part was to set a very strict filter for the cpu usage and for the script optimisation, so here is one :

;use filters with _PcapStartCapture
;retreive only tcp packets containing AABBCCDD, at the start of 8 and with a length of 4; like the StringMid func.
tcp[8:4] == 0xAABBCCDD ;8th byte from the beginning of the tcp DATA, 4bytes length; always include the 0x to specify you are dealing with hex.

And some funcs to split the different data from packets :

;$hCapture is the handle returned by _PcapStartCapture
; #FUNCTION# ====================================================================================================================
; Name...........: _TCP_Recv
; Description ...: Retreives a TCP Packet and returns its data splitted
; Syntax.........: _TCP_Recv($hCapture, $iInstance = 0, $iTimeOut = 3000)
; Parameters ....: $hCapture    - Capture handle
;                   $iInstance    - Instance of the packet to retreive
;                   $iTimeOut    - Timeout
; Return values .: Success    - Array containing the packet data
;                   Failure    - -1 (timedout)
; Author ........: FireFox (d3mon)
; Modified.......:
; Remarks .......:
; Related .......: _UDP_Recv
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _TCP_Recv($hCapture, $iInstance = 0, $iTimeOut = 3000)
    Local $blPacketCaptured = False, $iTimer_Capture, $aPacket, $iPacket

    $iTimer_Capture = TimerInit()

    While (TimerDiff($iTimer_Capture) < $iTimeOut Or $iTimeOut = -1)
        $aPacket = _PcapGetPacket($hCapture)

        If IsArray($aPacket) Then
            If $iPacket = $iInstance Then
                Local $aTCPPacket[21]

                $aTCPPacket[0] = StringMid($aPacket[3], 3, 12) ;Destination Mac Address
                $aTCPPacket[1] = StringMid($aPacket[3], 15, 12) ;Source Mac Address
                $aTCPPacket[2] = StringMid($aPacket[3], 27, 4) ;Type
                $aTCPPacket[3] = StringMid($aPacket[3], 31, 2) ;Version & Header length
                $aTCPPacket[4] = StringMid($aPacket[3], 33, 2) ;Differientiated Services Field
                $aTCPPacket[5] = StringMid($aPacket[3], 35, 4) ;Total Length
                $aTCPPacket[6] = StringMid($aPacket[3], 39, 4) ;Identification
                $aTCPPacket[7] = StringMid($aPacket[3], 43, 4) ;Fragment offset
                $aTCPPacket[8] = StringMid($aPacket[3], 47, 2) ;Time to live
                $aTCPPacket[9] = StringMid($aPacket[3], 49, 2) ;Protocol
                $aTCPPacket[10] = StringMid($aPacket[3], 51, 4) ;Header checksum
                $aTCPPacket[11] = StringMid($aPacket[3], 55, 8) ;Source IP Address
                $aTCPPacket[12] = StringMid($aPacket[3], 63, 8) ;Destination IP Address
                $aTCPPacket[13] = StringMid($aPacket[3], 71, 4) ;Source port
                $aTCPPacket[14] = StringMid($aPacket[3], 75, 4) ;Destination port
                $aTCPPacket[15] = StringMid($aPacket[3], 79, 8) ;Sequence number
                $aTCPPacket[16] = StringMid($aPacket[3], 87, 8) ;Acknowledgment number
                $aTCPPacket[17] = StringMid($aPacket[3], 95, 4) ;Flags
                $aTCPPacket[18] = StringMid($aPacket[3], 99, 4) ;Window size value
                $aTCPPacket[19] = StringMid($aPacket[3], 103, 4) ;Checksum
                ;107 to 110 = NULL data
                $aTCPPacket[20] = StringTrimLeft($aPacket[3], 110) ;Data

                Return $aTCPPacket
            EndIf
            $iPacket += 1
        EndIf

        Sleep(50)
    WEnd

    Return -1
EndFunc   ;==>_TCP_Recv

; #FUNCTION# ====================================================================================================================
; Name...........: _UDP_Recv
; Description ...: Retreives an UDP Packet and returns its data splitted
; Syntax.........: _UDP_Recv($hCapture, $iInstance = 0, $iTimeOut = 3000)
; Parameters ....: $hCapture    - Capture handle
;                   $iInstance    - Instance of the packet to retreive
;                   $iTimeOut    - Timeout
; Return values .: Success    - Array containing the packet data
;                   Failure    - -1 (timedout)
; Author ........: FireFox (d3mon)
; Modified.......:
; Remarks .......:
; Related .......: _TCP_Recv
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _UDP_Recv($hCapture, $iInstance = 0, $iTimeOut = 3000)
    Local $blPacketCaptured = False, $iTimer_Capture, $aPacket, $iPacket

    $iTimer_Capture = TimerInit()

    While (TimerDiff($iTimer_Capture) < $iTimeOut Or $iTimeOut = -1)
        $aPacket = _PcapGetPacket($hCapture)

        If IsArray($aPacket) Then
            If $iPacket = $iInstance Then
                Local $aUDPPacket[18]

                $aUDPPacket[0] = StringMid($aPacket[3], 3, 12) ;Source Mac Address
                $aUDPPacket[1] = StringMid($aPacket[3], 15, 12) ;Destination Mac Address
                $aUDPPacket[2] = StringMid($aPacket[3], 27, 4) ;Type
                $aUDPPacket[3] = StringMid($aPacket[3], 31, 2) ;Version & Header length
                $aUDPPacket[4] = StringMid($aPacket[3], 33, 2) ;Differientiated Services Field
                $aUDPPacket[5] = StringMid($aPacket[3], 35, 4) ;Total Length
                $aUDPPacket[6] = StringMid($aPacket[3], 39, 4) ;Identification
                $aUDPPacket[7] = StringMid($aPacket[3], 43, 4) ;Fragment offset
                $aUDPPacket[8] = StringMid($aPacket[3], 47, 2) ;Time to live
                $aUDPPacket[9] = StringMid($aPacket[3], 49, 2) ;Protocol
                $aUDPPacket[10] = StringMid($aPacket[3], 51, 4) ;Header checksum
                $aUDPPacket[11] = StringMid($aPacket[3], 55, 8) ;Source IP Address
                $aUDPPacket[12] = StringMid($aPacket[3], 63, 8) ;Destination IP Address
                $aUDPPacket[13] = StringMid($aPacket[3], 71, 4) ;Source port
                $aUDPPacket[14] = StringMid($aPacket[3], 75, 4) ;Destination port
                $aUDPPacket[15] = StringMid($aPacket[3], 79, 4) ;Length
                $aUDPPacket[16] = StringMid($aPacket[3], 83, 4) ;Checksum
                $aUDPPacket[17] = StringTrimLeft($aPacket[3], 86) ;Data

                Return $aUDPPacket
            EndIf
            $iPacket += 1
        EndIf

        Sleep(50)
    WEnd

    Return -1
EndFunc   ;==>_UDP_Recv

;for example convert the packet's source/dest IP Address to text
; #FUNCTION# ====================================================================================================================
; Name...........: _HexIPAddressToText
; Description ...: Converts Hex IP Adress to text
; Syntax.........: _HexIPAddressToText($vhexIPAddress)
; Parameters ....: $vIPAddress    - IP Address v4 (string, int)
; Return values .: Success    - Converted IP Address
; Author ........: FireFox (d3mon)
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _HexIPAddressToText($vhexIPAddress)
    Local $sIPAddress

    For $iOffset = 1 To 8 Step 2
        $sIPAddress &= Dec(StringMid($vhexIPAddress, $iOffset, 2)) & "."
    Next

    Return StringTrimRight($sIPAddress, 1)
EndFunc   ;==>_UDP_DecodeIPAddress

Ops, almost forgot the Winpcap UDF available here : http://opensource.grisambre.net/pcapau3/

PS : If you find this helpful, please "like"/rate this post.

Enjoy :guitar:

Edited by FireFox
3 people like this

 

OS : Win XP SP2 (32 bits) / Win 7 SP1 (64 bits) / Win 8 (64 bits) | Autoit version: latest stable / beta.
Hardware : Intel(R) Core(TM) i5-2400 CPU @ 3.10Ghz / 8 GiB RAM DDR3.

My UDFs : Skype UDF | TrayIconEx UDF | GUI Panel UDF | Excel XML UDF | Is_Pressed_UDF

My Projects : YouTube Multi-downloader | FTP Easy-UP | Lock'n | WinKill | AVICapture | Skype TM | Tap Maker | ShellNew | Scriptner | Const Replacer | FT_Pocket | Chrome theme maker

My Examples : Capture toolIP Camera | Crosshair | Draw Captured Region | Picture Screensaver | Jscreenfix | Drivetemp | Picture viewer

My Snippets : Basic TCP | Systray_GetIconIndex | Intercept End task | Winpcap various | Advanced HotKeySet | Transparent Edit control

 

Share this post


Link to post
Share on other sites



How do I get uri of HTTP packet with winpcap?

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

@Ontosy

Here you go :

#include <String.au3>
...
Global $aPacket = _TCP_Recv(...)

If Dec($aPacket[13]) = 80 Then ;Source port = 80
$sPacketText = _HexToString($aTCPPacket[20])

... ;process
EndIf

In the $sPacketText you will have the request header where you will be able to retreive the URI.

Br, FireFox.

Edited by FireFox
1 person likes this

 

OS : Win XP SP2 (32 bits) / Win 7 SP1 (64 bits) / Win 8 (64 bits) | Autoit version: latest stable / beta.
Hardware : Intel(R) Core(TM) i5-2400 CPU @ 3.10Ghz / 8 GiB RAM DDR3.

My UDFs : Skype UDF | TrayIconEx UDF | GUI Panel UDF | Excel XML UDF | Is_Pressed_UDF

My Projects : YouTube Multi-downloader | FTP Easy-UP | Lock'n | WinKill | AVICapture | Skype TM | Tap Maker | ShellNew | Scriptner | Const Replacer | FT_Pocket | Chrome theme maker

My Examples : Capture toolIP Camera | Crosshair | Draw Captured Region | Picture Screensaver | Jscreenfix | Drivetemp | Picture viewer

My Snippets : Basic TCP | Systray_GetIconIndex | Intercept End task | Winpcap various | Advanced HotKeySet | Transparent Edit control

 

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

ty

Edited by Ontosy

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  
Followers 0

  • Similar Content

    • tarretarretarre
      By tarretarretarre
      AutoIt-SocketIo
      Yep yep, this is pretty much an attempt to port the existing project's concept https://socket.io/ to AutoIt's Codebase. So i will not go in to so much detail.
      This is how the communication is done http://i.imgur.com/0mMfsBD.png Each client is isolated to the server http://i.imgur.com/rVO2LFb.png Features
      Easy API VarType Translation (Example: If the server sends an int, the client will receive an int and vice versa) Fully featured examples Data encryption (Using Autoit's UDF Crypt.au3) Limitations / Drawbacks
      Every Broadcast/Emit is limited to a maximum of 16 parameters Every Callback Function has to have the same number of parameters as the Broadcasted/Emited event It is not possible to Broadcast/Emit objects Only 1D-arrays are allowed to be Broadcasted/Emitted (2D arrays will probably never be supported) Changelog
      Version 1.4.0 (This update DOES NOT break scripts)
      Added a new server method: _Io_getSockets which will return an array of all sockets. See more in the doc Added a banning-system, see more at: _Io_getBanlist, _Io_Ban, _Io_Sanction, _Io_IsBanned Added a new default event for clients banned. See more at default events Added two new client and server methods _Io_setEventPreScript And _Io_setEventPostScript. The intent for these is to not DRY when doing debug \ tasks that requires to be ran before or after events. Added a new client and server method _Io_ClearEvents. Added a third optional parameter to _Io_On called $socket, you may only pass the socket returned from _Io_Listen or _Io_Connect. The intent for this change is to allow for server + client in the same envoirment. Added a second parameter to _Io_Loop called $WhoAmI which should used with the new enums $_IO_SERVER and $_IO_CLIENT. The intent for this change is to allow for server + client in the same envoirment. Added a new client method _Io_TransferSocket. Added a new server method _Io_getActiveSocketCount. Optimations, avoiding Redims and unnecessary nested arrays as good as possible etc. Version 1.3.0 (This update DOES NOT break scripts)
      Got rid of unnecessary Redims with sockets and subscriptions in the main loop (This increased write performence greatly) Changed $iMaxDeadSocketsBeforeTidy from 100 to 1000 Changed _Io_setRecvPackageSize($nPackageSize = 2048) to _Io_setRecvPackageSize($nPackageSize = 4096) because 2017. Added Tests for both subscriptions and the automatic TidyUp Added a new server method: _Io_getMaxConnections Added a new server method: _Io_getMaxDeadSocketsCount Added a fifth parameter to the _Io_Listen method called $iMaxConnections which defaults to 100000. If the iMaxConnection + 1 user connects, they will be instantly disconnected. Added a parameter to _Io_Disconnect called $socket which defaults to null. If the iMaxConnections + 1 client connects, they will be instantly disconnected. Version 1.2.0 (This update DOES NOT break scripts)
      Added an option to set the packet-size of TCP-transports, see _Io_setRecvPackageSize Got rid of unnecessary StringLen's in _Io_loop Changed __Io_TidyUp to _Io_TidyUp and added it to the public Api reference list. Changed $iMaxDeadSocketsBeforeTidy default value from 1000 to 100 and added an option to disable it, read more at _Io_Listen Changed $bAutoReconnect from False to True. Fixed gitignore epicZ fail Improvemend Documentation Version 1.1.0 (This update DOES NOT break scripts)
      Fixed bug when Emitting / Broadcasting without any parameters causing a $fCallback crash Optimized Package-handling once again. Added 1D-Array support (Endless nestning). Added Subscriptions (See _Io_Subscribe _Io_Unsubscribe and _Io_BroadcastToRoom). Added new example for subscriptions (Be sure to use different room names when joining with clients) Added Unit testing (See Tests\Runner.au3 and Tests\Tests.au3, to run tests you need a udf found here: https://github.com/tarreislam/Autoit-Unit-Tester) Version 1.0.0
      (This update DOES NOT break scripts) Added data encryption (Using Autoit's UDF Crypt.au3) See more at _Io_EnableEncryption Added new method _Io_Disconnect which can be used with both servers and clients Improved package-handling to increase performance Increased the limit of Broadcasted/Emit parameters from 10 to 16 Api methods
      Server methods
      _Io_Listen($iPort, $iAddress = @IPAddress1, $iMaxPendingConnections = Default, $iMaxDeadSocketsBeforeTidy = 1000, $iMaxConnections = 100000) _Io_Subscribe(ByRef $socket, $sRoomName) _Io_Unsubscribe(ByRef $socket, $sRoomName = null) _Io_Broadcast(ByRef $socket, $sEventName, $p1, $p2, ...$p16)  
      _Io_BroadcastToAll(ByRef $socket, $sEventName, $p1, $p2, ...$p16) _Io_BroadcastToRoom(ByRef $socket, $sDesiredRoomName, $sEventName, $p1, $p2, ...$p16) _Io_socketGetProperty(ByRef $socket, $sProp = Default) _Io_getSockets($bForceUpdate = False, $socket = $__g_io_mySocket, $whoAmI = $__g_io_whoami) _Io_getDeadSocketCount() _Io_getSocketsCount() _Io_getActiveSocketCount() _Io_getMaxConnections() _Io_getMaxDeadSocketsCount() _Io_getBanlist($iEntry = Default) _Io_Ban($socketOrIp, $nTime = 3600, $sReason = "Banned", $sIssuedBy = "system") _Io_Sanction($socketOrIp) _Io_IsBanned($socketOrIp) _Io_TidyUp() Client methods
      _Io_Connect($iAddress, $iPort, $bAutoReconnect = True) _Io_Reconnect(ByRef $socket) Server and Client methods
      _Io_setEventPreScript($fCallback) _Io_setEventPostScript($fCallback) _Io_getVer() _Io_On(Const $sEventName, Const $fCallback, $socket = $__g_io_mySocket) _Io_Emit(ByRef $socket, $sEventName, $p1, $p2, ...$p16) _Io_Loop(ByRef $socket, $whoAmI = $__g_io_whoami) _Io_LoopFacade() _Io_EnableEncryption($sFileOrKey, $CryptAlgId = $CALG_AES_256) _Io_Disconnect($socket = null) _Io_setRecvPackageSize($nPackageSize = 4096) _Io_ClearEvents() _Io_TransferSocket(ByRef $from, ByRef $to) Default events
      Server events
      connection Client events
      banned Server and Client events
      disconnect View source on github
       
      Autoit-Socket-IO-1.0.0.zip (OLD!)
      Autoit-Socket-IO-1.1.0.zip (OLD)
      Autoit-Socket-IO-1.3.0.zip (OLD)
      Autoit-Socket-IO-1.4.0.zip (NEWEST 2017-08-11)
    • timmalos
      By timmalos
      Hello all.
      In case this is interesting few of you, I share my AMCP 2.1 protocol UDF in AutoIT. This protocol is used by CasparCG server, which is a Windows and Linux software used to play out professional graphics, audio and video to multiple outputs as a layerbased real-time compositor. It has been in 24/7 broadcast production since 2006. It's free and opensource.
      The UDF I share allows communication between an AutoIt based client and the CasparCG, based on following documentation : http://casparcg.com/wiki/CasparCG_2.1_AMCP_Protocol
      If you want more details on CasparCG :  official WebSite or have a look to this video
      I'm currently building a full Client based on AutoIt, with many features like drag-and-drop layers, but sadly I can't share it right now, might come later. Don't hesitate to ask questions if you have any or need a basic example.
      The only requirement for this UDF is the other Event-driven TCP UDF by Kip
       
       

      AMCP_shared.au3
      TCP.au3
    • kingjacob90
      By kingjacob90
      Hi
      I am trying to send a file over TCP from a TCP client to server. If I run the server and client on the same computer the file is send fine, but if the server is on one computer on the network and the client on another the file is sent in what looks like more than one packet. In other words the server receives 4 msg from the client.
      Why is this, how do I make it send in one go, or what is a way around it?
      Side Note: TCP server has a max of 999999999
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good morning community!
      I am working on a script which read from a text file ( .txt ) and should import all the content in a SQLite3 DB, in order to execute some queries that should be difficult to execute on a text file.
      So, I was looking for something very very fast, because the file could be very large ( I don't know exaclty how much can became big, but I know a lot of rows, it's a log file ... )
      I found the "Import method", but I don't know If I can implement it in a query ( @jchd, it's your turn!  )
      Do you know some methods that I can implement in my script to have a very very fast import of thousands and thousands rows in a SQLite3 DB?
      Thanks a lot
      Francesco
    • AlexFing17
      By AlexFing17
      i am trying to figure out how a server can connect to a client Over the internet. 
      In this is script. The client connects to the server on the same machine (localhost) and executes the commands from the client.
      How can I change that instead communicating over localhost to communicate over the internet with tcp ipaddress and a port.
       
      What i actually need help of is
      1. The server will open a port and  listen to communication from a No-ip address
      2. I input the no-ip address and correct port in the client side, and when i click on connect, it connects to the server if its online
       
       
      This is the client
      #include <GuiConstantsEx.au3> THIS IS THE CLIENT #include <NamedPipes.au3> #include <StaticConstants.au3> #include <WinAPI.au3> #include <WindowsConstants.au3> ; =============================================================================================================================== ; Description ...: This is the client side of the pipe demo ; Author ........: Paul Campbell (PaulIA) ; Notes .........: ; =============================================================================================================================== ; =============================================================================================================================== ; Global constants ; =============================================================================================================================== Global Const $BUFSIZE = 4096 Global Const $DEFCMD = "cmd.exe /c dir c:\" Global Const $PIPE_NAME = "\\$\\pipe\\AutoIt3" Global Const $ERROR_MORE_DATA = 234 ; =============================================================================================================================== ; Global variables ; =============================================================================================================================== Global $g_idEdit, $g_idMemo, $g_idSend, $g_idServer, $g_hPipe ; =============================================================================================================================== ; Main ; =============================================================================================================================== CreateGUI() MsgLoop() ; =============================================================================================================================== ; Creates a GUI for the client ; =============================================================================================================================== Func CreateGUI() Local $hGUI = GUICreate("FarC0nn3c7", 500, 400, -1, -1, $WS_SIZEBOX) GUICtrlCreateLabel("Server:", 2, 14, 52, 20, $SS_RIGHT) $g_idServer = GUICtrlCreateEdit("<local>", 56, 10, 200, 20, $SS_LEFT) GUICtrlCreateLabel("Command:", 2, 36, 52, 20, $SS_RIGHT) $g_idEdit = GUICtrlCreateEdit($DEFCMD, 56, 32, 370, 20, $SS_LEFT) $g_idSend = GUICtrlCreateButton("Pawn Dem", 430, 32, 60, 20) $g_idMemo = GUICtrlCreateEdit("", 0, 62, _WinAPI_GetClientWidth($hGUI), 332) GUICtrlSetFont($g_idMemo, 9, 400, 0, "Courier New") GUISetState() EndFunc ;==>CreateGUI ; =============================================================================================================================== ; Logs an error message to the display ; =============================================================================================================================== Func LogError($sMessage) $sMessage &= " (" & _WinAPI_GetLastErrorMessage() & ")" GUICtrlSetData($g_idMemo, GUICtrlRead($g_idMemo) & $sMessage & @CRLF) EndFunc ;==>LogError ; =============================================================================================================================== ; Logs a message to the display ; =============================================================================================================================== Func LogMsg($sMessage) GUICtrlSetData($g_idMemo, GUICtrlRead($g_idMemo) & $sMessage & @CRLF) EndFunc ;==>LogMsg ; =============================================================================================================================== ; MsgLoop ; =============================================================================================================================== Func MsgLoop() While True Switch GUIGetMsg() Case $g_idSend SendCmd() Case $GUI_EVENT_CLOSE Exit EndSwitch WEnd EndFunc ;==>MsgLoop ; =============================================================================================================================== ; This function opens a pipe to the server ; =============================================================================================================================== Func OpenPipe() Local $sName, $sPipe ; Get pipe handle $sName = GUICtrlRead($g_idServer) If $sName = "<local>" Then $sName = "." $sPipe = StringReplace($PIPE_NAME, "$", $sName) $g_hPipe = _WinAPI_CreateFile($sPipe, 2, 6) If $g_hPipe <> -1 Then Return True LogError("OpenPipe failed") Return False EndFunc ;==>OpenPipe ; =============================================================================================================================== ; This function reads a message from the pipe ; =============================================================================================================================== Func ReadMsg() Local $bSuccess, $iRead, $pBuffer, $tBuffer $tBuffer = DllStructCreate("char Text[4096]") $pBuffer = DllStructGetPtr($tBuffer) GUICtrlSetData($g_idMemo, "") While 1 $bSuccess = _WinAPI_ReadFile($g_hPipe, $pBuffer, $BUFSIZE, $iRead, 0) If $iRead = 0 Then ExitLoop If Not $bSuccess Or (_WinAPI_GetLastError() = $ERROR_MORE_DATA) Then ExitLoop GUICtrlSetData($g_idMemo, StringLeft(DllStructGetData($tBuffer, "Text"), $iRead), 1) WEnd EndFunc ;==>ReadMsg ; =============================================================================================================================== ; This function sends a command to the server ; =============================================================================================================================== Func SendCmd() If OpenPipe() Then SetReadMode() WriteMsg(GUICtrlRead($g_idEdit)) ReadMsg() _WinAPI_CloseHandle($g_hPipe) EndIf EndFunc ;==>SendCmd ; =============================================================================================================================== ; This function sets the pipe read mode ; =============================================================================================================================== Func SetReadMode() If Not _NamedPipes_SetNamedPipeHandleState($g_hPipe, 1, 0, 0, 0) Then LogError("SetReadMode: _NamedPipes_SetNamedPipeHandleState failed") EndIf EndFunc ;==>SetReadMode ; =============================================================================================================================== ; This function writes a message to the pipe ; =============================================================================================================================== Func WriteMsg($sMessage) Local $iWritten, $iBuffer, $pBuffer, $tBuffer $iBuffer = StringLen($sMessage) + 1 $tBuffer = DllStructCreate("char Text[" & $iBuffer & "]") $pBuffer = DllStructGetPtr($tBuffer) DllStructSetData($tBuffer, "Text", $sMessage) If Not _WinAPI_WriteFile($g_hPipe, $pBuffer, $iBuffer, $iWritten, 0) Then LogError("WriteMsg: _WinAPI_WriteFile failed") EndIf EndFunc ;==>WriteMsg  
      And this is the server
      #include <GuiConstantsEx.au3> #include <NamedPipes.au3> #include <WinAPI.au3> #include <WindowsConstants.au3> #NoTrayIcon ; =============================================================================================================================== ; Description ...: This is the server side of the pipe demo ; Author ........: Paul Campbell (PaulIA) ; Notes .........: ; =============================================================================================================================== ; =============================================================================================================================== ; Global constants ; =============================================================================================================================== Global Const $DEBUGGING = False Global Const $BUFSIZE = 4096 Global Const $PIPE_NAME = "\\.\\pipe\\AutoIt3" Global Const $TIMEOUT = 5000 Global Const $WAIT_TIMEOUT = 258 Global Const $ERROR_IO_PENDING = 997 Global Const $ERROR_PIPE_CONNECTED = 535 ; =============================================================================================================================== ; Global variables ; =============================================================================================================================== Global $g_hEvent, $g_idMemo, $g_pOverlap, $g_tOverlap, $g_hPipe, $g_hReadPipe, $g_iState, $g_iToWrite ; =============================================================================================================================== ; Main ; =============================================================================================================================== CreateGUI() InitPipe() MsgLoop() ; =============================================================================================================================== ; Creates a GUI for the server ; =============================================================================================================================== Func CreateGUI() Local $hGUI $hGUI = GUICreate("Pipe Server", 500, 400, -1, -1, $WS_SIZEBOX) $g_idMemo = GUICtrlCreateEdit("", 0, 0, _WinAPI_GetClientWidth($hGUI), _WinAPI_GetClientHeight($hGUI)) GUICtrlSetFont($g_idMemo, 9, 400, 0, "Courier New") GUISetState() EndFunc ;==>CreateGUI ; =============================================================================================================================== ; This function creates an instance of a named pipe ; =============================================================================================================================== Func InitPipe() ; Create an event object for the instance $g_tOverlap = DllStructCreate($tagOVERLAPPED) $g_pOverlap = DllStructGetPtr($g_tOverlap) $g_hEvent = _WinAPI_CreateEvent() If $g_hEvent = 0 Then LogError("InitPipe ..........: API_CreateEvent failed") Return EndIf DllStructSetData($g_tOverlap, "hEvent", $g_hEvent) ; Create a named pipe $g_hPipe = _NamedPipes_CreateNamedPipe($PIPE_NAME, _ ; Pipe name 2, _ ; The pipe is bi-directional 2, _ ; Overlapped mode is enabled 0, _ ; No security ACL flags 1, _ ; Data is written to the pipe as a stream of messages 1, _ ; Data is read from the pipe as a stream of messages 0, _ ; Blocking mode is enabled 1, _ ; Maximum number of instances $BUFSIZE, _ ; Output buffer size $BUFSIZE, _ ; Input buffer size $TIMEOUT, _ ; Client time out 0) ; Default security attributes If $g_hPipe = -1 Then LogError("InitPipe ..........: _NamedPipes_CreateNamedPipe failed") Else ; Connect pipe instance to client ConnectClient() EndIf EndFunc ;==>InitPipe ; =============================================================================================================================== ; This function loops waiting for a connection event or the GUI to close ; =============================================================================================================================== Func MsgLoop() Local $iEvent Do $iEvent = _WinAPI_WaitForSingleObject($g_hEvent, 0) If $iEvent < 0 Then LogError("MsgLoop ...........: _WinAPI_WaitForSingleObject failed") Exit EndIf If $iEvent = $WAIT_TIMEOUT Then ContinueLoop Debug("MsgLoop ...........: Instance signaled") Switch $g_iState Case 0 CheckConnect() Case 1 ReadRequest() Case 2 CheckPending() Case 3 RelayOutput() EndSwitch Until GUIGetMsg() = $GUI_EVENT_CLOSE EndFunc ;==>MsgLoop ; =============================================================================================================================== ; Checks to see if the pending client connection has finished ; =============================================================================================================================== Func CheckConnect() Local $iBytes ; Was the operation successful? If Not _WinAPI_GetOverlappedResult($g_hPipe, $g_pOverlap, $iBytes, False) Then LogError("CheckConnect ......: Connection failed") ReconnectClient() Else $g_iState = 1 EndIf EndFunc ;==>CheckConnect ; =============================================================================================================================== ; This function reads a request message from the client ; =============================================================================================================================== Func ReadRequest() Local $pBuffer, $tBuffer, $iRead, $bSuccess $tBuffer = DllStructCreate("char Text[" & $BUFSIZE & "]") $pBuffer = DllStructGetPtr($tBuffer) $bSuccess = _WinAPI_ReadFile($g_hPipe, $pBuffer, $BUFSIZE, $iRead, $g_pOverlap) If $bSuccess And ($iRead <> 0) Then ; The read operation completed successfully Debug("ReadRequest .......: Read success") Else ; Wait for read Buffer to complete If Not _WinAPI_GetOverlappedResult($g_hPipe, $g_pOverlap, $iRead, True) Then LogError("ReadRequest .......: _WinAPI_GetOverlappedResult failed") ReconnectClient() Return Else ; Read the command from the pipe $bSuccess = _WinAPI_ReadFile($g_hPipe, $pBuffer, $BUFSIZE, $iRead, $g_pOverlap) If Not $bSuccess Or ($iRead = 0) Then LogError("ReadRequest .......: _WinAPI_ReadFile failed") ReconnectClient() Return EndIf EndIf EndIf ; Execute the console command If Not ExecuteCmd(DllStructGetData($tBuffer, "Text")) Then ReconnectClient() Return EndIf ; Relay console output back to the client $g_iState = 3 EndFunc ;==>ReadRequest ; =============================================================================================================================== ; This function relays the console output back to the client ; =============================================================================================================================== Func CheckPending() Local $bSuccess, $iWritten $bSuccess = _WinAPI_GetOverlappedResult($g_hPipe, $g_pOverlap, $iWritten, False) If Not $bSuccess Or ($iWritten <> $g_iToWrite) Then Debug("CheckPending ......: Write reconnecting") ReconnectClient() Else Debug("CheckPending ......: Write complete") $g_iState = 3 EndIf EndFunc ;==>CheckPending ; =============================================================================================================================== ; This function relays the console output back to the client ; =============================================================================================================================== Func RelayOutput() Local $pBuffer, $tBuffer, $sLine, $iRead, $bSuccess, $iWritten $tBuffer = DllStructCreate("char Text[" & $BUFSIZE & "]") $pBuffer = DllStructGetPtr($tBuffer) ; Read data from console pipe _WinAPI_ReadFile($g_hReadPipe, $pBuffer, $BUFSIZE, $iRead) If $iRead = 0 Then LogMsg("RelayOutput .......: Write done") _WinAPI_CloseHandle($g_hReadPipe) _WinAPI_FlushFileBuffers($g_hPipe) ReconnectClient() Return EndIf ; Get the data and strip out the extra carriage returns $sLine = StringLeft(DllStructGetData($tBuffer, "Text"), $iRead) $sLine = StringReplace($sLine, @CR & @CR, @CR) $g_iToWrite = StringLen($sLine) DllStructSetData($tBuffer, "Text", $sLine) ; Relay the data back to the client $bSuccess = _WinAPI_WriteFile($g_hPipe, $pBuffer, $g_iToWrite, $iWritten, $g_pOverlap) If $bSuccess And ($iWritten = $g_iToWrite) Then Debug("RelayOutput .......: Write success") Else If Not $bSuccess And (_WinAPI_GetLastError() = $ERROR_IO_PENDING) Then Debug("RelayOutput .......: Write pending") $g_iState = 2 Else ; An error occurred, disconnect from the client LogError("RelayOutput .......: Write failed") ReconnectClient() EndIf EndIf EndFunc ;==>RelayOutput ; =============================================================================================================================== ; This function is called to start an overlapped connection operation ; =============================================================================================================================== Func ConnectClient() $g_iState = 0 ; Start an overlapped connection If _NamedPipes_ConnectNamedPipe($g_hPipe, $g_pOverlap) Then LogError("ConnectClient .....: ConnectNamedPipe 1 failed") Else Switch @error ; The overlapped connection is in progress Case $ERROR_IO_PENDING Debug("ConnectClient .....: Pending") ; Client is already connected, so signal an event Case $ERROR_PIPE_CONNECTED LogMsg("ConnectClient .....: Connected") $g_iState = 1 If Not _WinAPI_SetEvent(DllStructGetData($g_tOverlap, "hEvent")) Then LogError("ConnectClient .....: SetEvent failed") EndIf ; Error occurred during the connection event Case Else LogError("ConnectClient .....: ConnectNamedPipe 2 failed") EndSwitch EndIf EndFunc ;==>ConnectClient ; =============================================================================================================================== ; Dumps debug information to the screen ; =============================================================================================================================== Func Debug($sMessage) If $DEBUGGING Then LogMsg($sMessage) EndFunc ;==>Debug ; =============================================================================================================================== ; Executes a command and returns the results ; =============================================================================================================================== Func ExecuteCmd($sCmd) Local $tProcess, $tSecurity, $tStartup, $hWritePipe ; Set up security attributes $tSecurity = DllStructCreate($tagSECURITY_ATTRIBUTES) DllStructSetData($tSecurity, "Length", DllStructGetSize($tSecurity)) DllStructSetData($tSecurity, "InheritHandle", True) ; Create a pipe for the child process's STDOUT If Not _NamedPipes_CreatePipe($g_hReadPipe, $hWritePipe, $tSecurity) Then LogError("ExecuteCmd ........: _NamedPipes_CreatePipe failed") Return False EndIf ; Create child process $tProcess = DllStructCreate($tagPROCESS_INFORMATION) $tStartup = DllStructCreate($tagSTARTUPINFO) DllStructSetData($tStartup, "Size", DllStructGetSize($tStartup)) DllStructSetData($tStartup, "Flags", BitOR($STARTF_USESTDHANDLES, $STARTF_USESHOWWINDOW)) DllStructSetData($tStartup, "StdOutput", $hWritePipe) DllStructSetData($tStartup, "StdError", $hWritePipe) If Not _WinAPI_CreateProcess("", $sCmd, 0, 0, True, 0, 0, "", DllStructGetPtr($tStartup), DllStructGetPtr($tProcess)) Then LogError("ExecuteCmd ........: _WinAPI_CreateProcess failed") _WinAPI_CloseHandle($g_hReadPipe) _WinAPI_CloseHandle($hWritePipe) Return False EndIf _WinAPI_CloseHandle(DllStructGetData($tProcess, "hProcess")) _WinAPI_CloseHandle(DllStructGetData($tProcess, "hThread")) ; Close the write end of the pipe so that we can read from the read end _WinAPI_CloseHandle($hWritePipe) LogMsg("ExecuteCommand ....: " & $sCmd) Return True EndFunc ;==>ExecuteCmd ; =============================================================================================================================== ; Logs an error message to the display ; =============================================================================================================================== Func LogError($sMessage) $sMessage &= " (" & _WinAPI_GetLastErrorMessage() & ")" ConsoleWrite($sMessage & @LF) EndFunc ;==>LogError ; =============================================================================================================================== ; This function is called when an error occurs or when the client closes its handle to the pipe ; =============================================================================================================================== Func ReconnectClient() ; Disconnect the pipe instance If Not _NamedPipes_DisconnectNamedPipe($g_hPipe) Then LogError("ReconnectClient ...: DisonnectNamedPipe failed") Return EndIf ; Connect to a new client ConnectClient() EndFunc ;==>ReconnectClient