Enum Named Pipes

Code to enumerate Windows Named Pipes in C and Basic. (Compiled application at btm of page)



C/C++:
// Enumerate named Pipes (Windows NT/2000) 
// pipelist.cpp  


#include <windows.h>  
#include <stdio.h>  

#define FileDirectoryInformation 1  
#define STATUS_NO_MORE_FILES 0x80000006L  

typedef struct  
{  
    USHORT
Length;  
    USHORT
MaximumLength;  
    PWSTR  
Buffer;  
} UNICODE_STRING, *PUNICODE_STRING;  

typedef struct  
{  
    LONG
Status;  
    ULONG
Information;  
} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;  

typedef struct {  
    ULONG
NextEntryOffset;  
    ULONG
FileIndex;  
    LARGE_INTEGER
CreationTime;  
    LARGE_INTEGER
LastAccessTime;  
    LARGE_INTEGER
LastWriteTime;  
    LARGE_INTEGER
ChangeTime;  
    LARGE_INTEGER
EndOfFile;  
    LARGE_INTEGER
AllocationSize;  
    ULONG
FileAttributes;  
    ULONG
FileNameLength;  
   
union {  
       
struct {  
            WCHAR
FileName[1];  
       
} FileDirectoryInformationClass;  

       
struct {  
            DWORD dwUknown1
;  
            WCHAR
FileName[1];  
       
} FileFullDirectoryInformationClass;  

       
struct {  
            DWORD dwUknown2
;  
            USHORT
AltFileNameLen;  
            WCHAR
AltFileName[12];  
            WCHAR
FileName[1];  
   
} FileBothDirectoryInformationClass;  
   
};  
} FILE_QUERY_DIRECTORY, *PFILE_QUERY_DIRECTORY;  


// ntdll!NtQueryDirectoryFile (NT specific!)  
//  
// The function searches a directory for a file whose name and attributes  
// match those specified in the function call.  
//  
// NTSYSAPI  
// NTSTATUS  
// NTAPI  
// NtQueryDirectoryFile(  
//    IN HANDLE FileHandle,                      // handle to the file  
//    IN HANDLE EventHandle OPTIONAL,  
//    IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,  
//    IN PVOID ApcContext OPTIONAL,  
//    OUT PIO_STATUS_BLOCK IoStatusBlock,  
//    OUT PVOID Buffer,                          // pointer to the buffer to receive the result  
//    IN ULONG BufferLength,                     // length of Buffer  
//    IN FILE_INFORMATION_CLASS InformationClass,// information type  
//    IN BOOLEAN ReturnByOne,                    // each call returns info for only one file  
//    IN PUNICODE_STRING FileTemplate OPTIONAL,  // template for search  
//    IN BOOLEAN Reset                           // restart search  
// );  
typedef LONG (WINAPI *PROCNTQDF)( HANDLE,HANDLE,PVOID,PVOID,PIO_STATUS_BLOCK,PVOID,ULONG,  
                                  UINT
,BOOL,PUNICODE_STRING,BOOL );  

PROCNTQDF
NtQueryDirectoryFile;  

void main(void)  
{  
    LONG ntStatus
;  
    IO_STATUS_BLOCK
IoStatus;  
    HANDLE hPipe
;  
    BOOL bReset
= TRUE;  
    PFILE_QUERY_DIRECTORY
DirInfo,  
                         
TmpInfo;  


   
NtQueryDirectoryFile = (PROCNTQDF)GetProcAddress(  
                                     
GetModuleHandle("ntdll"),  
                                     
"NtQueryDirectoryFile"  
                                     
);  

   
if (!NtQueryDirectoryFile)  
       
return;  

    hPipe
= CreateFile("\\\\.\\Pipe\\",GENERIC_READ,  
                       FILE_SHARE_READ
|FILE_SHARE_WRITE|FILE_SHARE_DELETE,  
                       NULL
,OPEN_EXISTING,0,NULL);  

   
if(hPipe == INVALID_HANDLE_VALUE)  
     
return;  

   
DirInfo = (PFILE_QUERY_DIRECTORY) new BYTE[1024];  

   printf
("Pipe name (Number of instances, Maximum instances)\n\n");  
   
while(1)  
   
{  
       ntStatus
= NtQueryDirectoryFile(hPipe,NULL,NULL,NULL,&IoStatus,DirInfo,1024,  
                                       
FileDirectoryInformation,FALSE,NULL,bReset);  

       
if (ntStatus!=NO_ERROR)  
       
{  
         
if (ntStatus == STATUS_NO_MORE_FILES)  
             
break;  

         
return;  
       
}  

       
TmpInfo = DirInfo;  
       
while(1)  
       
{
         
// Store old values before we mangle the buffer
         
const int endStringAt = TmpInfo->FileNameLength/sizeof(WCHAR);
         
const WCHAR oldValue = TmpInfo->FileDirectoryInformationClass.FileName[endStringAt];

         
// Place a null character at the end of the string so wprintf doesn't read past the end
         
TmpInfo->FileDirectoryInformationClass.FileName[endStringAt] = NULL;  

          wprintf
(L"%s (%d, %d)\n",TmpInfo->FileDirectoryInformationClass.FileName,  
                                   
TmpInfo->EndOfFile.LowPart,  
                                   
TmpInfo->AllocationSize.LowPart );  

         
// Restore the buffer to its correct state
         
TmpInfo->FileDirectoryInformationClass.FileName[endStringAt] = oldValue;

         
if(TmpInfo->NextEntryOffset==0)  
           
break;  

         
TmpInfo = (PFILE_QUERY_DIRECTORY)((DWORD)TmpInfo+TmpInfo->NextEntryOffset);  
       
}  

       bReset
= FALSE;  
   
}  

   
delete DirInfo;  
   
CloseHandle(hPipe);  
}  






Basic:

'--------------------------------------------------------------------------
' Enumerate active pipes in system
' Converted/Updated Mike Trader 02/09

' ZWQueryDirectoryFile()
' http://msdn.microsoft.com/en-us/library/ms801001.aspx
'--------------------------------------------------------------------------
#COMPILE EXE "EnumPipes.EXE"
#DIM ALL
#INCLUDE "WIN32API.INC"

'GLOBAL hDbg AS LONG

%STATUS_NO_MORE_FILES               = &H80000006
%STATUS_BUFFER_OVERFLOW             = &H80000005
%STATUS_INVALID_PARAMETER           = &HC000000D
%STATUS_OBJECT_TYPE_MISMATCH        = &HC0000024
               
%INVALID_HANDLE_VALUE               = &HFFFFFFFF???

%STATUS_SUCCESS                     = 0
                                                
%FileDirectoryInformation           = 1
%FileFullDirectoryInformation       = 2
%FileBothDirectoryInformation       = 3
%FileBasicInformation               = 4
%FileStandardInformation            = 5
%FileInternalInformation            = 6
%FileEaInformation                  = 7
%FileAccessInformation              = 8
%FileNameInformation                = 9
%FileRenameInformation              = 10
%FileLinkInformation                = 11
%FileNamesInformation               = 12
%FileDispositionInformation         = 13
%FilePositionInformation            = 14
%FileFullEaInformation              = 15
%FileModeInformation                = 16
%FileAlignmentInformation           = 17
%FileAllInformation                 = 18
%FileAllocationInformation          = 19
%FileEndOfFileInformation           = 20
%FileAlternateNameInformation       = 21
%FileStreamInformation              = 22
%FilePipeInformation                = 23
%FilePipeLocalInformation           = 24
%FilePipeRemoteInformation          = 25
%FileMailslotQueryInformation       = 26
%FileMailslotSetInformation         = 27
%FileCompressionInformation         = 28
%FileCopyOnWriteInformation         = 29
%FileCompletionInformation          = 30
%FileMoveClusterInformation         = 31
%FileQuotaInformation               = 32
%FileReparsePointInformation        = 33
%FileNetworkOpenInformation         = 34
%FileObjectIdInformation            = 35
%FileTrackingInformation            = 36
%FileOleDirectoryInformation        = 37
%FileContentIndexInformation        = 38
%FileInheritContentIndexInformation = 39
%FileOleInformation                 = 40
%FileMaximumInformation             = 41
                                   
%FileIdBothDirectoryInformation     = 37
%FileIdFullDirectoryInformation     = 38



'TYPE UNICODE_STRING
'    length                AS WORD
'    maxLen                AS WORD
'    buffer                AS ASCIIZ * 1024
'END TYPE

'TYPE FILETIME
'    dwLowDateTime         AS DWORD
'    dwHighDateTime        AS DWORD
'END TYPE

'TYPE FILE_INFORMATION
'    dwFileAttributes      AS LONG
'    ftCreationTime        AS FILETIME
'    ftLastAccessTime      AS FILETIME
'    ftLastWriteTime       AS FILETIME
'    dwVolumeSerialNumber  AS LONG
'    nFileSizeHigh         AS LONG
'    nFileSizeLow          AS LONG
'    nNumberOfLinks        AS LONG
'    nFileIndexHigh        AS LONG
'    nFileIndexLow         AS LONG
'END TYPE

'TYPE tFileDirectoryInformationClass
'    FileName              AS STRING * 1024            
'END TYPE
'
'TYPE tFileFullDirectoryInformationClass
'    dwUknown1             AS DWORD
'    FileName              AS STRING * 1024            
'END TYPE
'
'TYPE tFileBothDirectoryInformationClass
'    dwUknown2             AS DWORD
'    AltFileNameLen        AS WORD
'    AltFileName           AS STRING * 12           
'    FileName              AS STRING * 1024            
'END TYPE

'UNION uFileDirectoryInformation
'    FileDirectoryInformationClass     AS tFileDirectoryInformationClass
'    FileFullDirectoryInformationClass AS tFileFullDirectoryInformationClass
'    FileBothDirectoryInformationClass AS tFileBothDirectoryInformationClass
'END UNION
       


TYPE IO_STATUS_BLOCK
    ioSTATUS              AS LONG
    Information           AS DWORD
END TYPE

TYPE LARGE_INTEGER
    LowPart               AS DWORD
    HighPart              AS LONG
END TYPE

TYPE FILE_QUERY_DIRECTORY ' http://msdn.microsoft.com/en-us/library/cc232097.aspx
    NextEntryOffset       AS DWORD
    FileIndex             AS DWORD
    CreationTime          AS LARGE_INTEGER
    LastAccessTime        AS LARGE_INTEGER
    LastWriteTime         AS LARGE_INTEGER
    ChangeTime            AS LARGE_INTEGER
    EndOfFile             AS LARGE_INTEGER
    AllocationSize        AS LARGE_INTEGER
    FileAttributes        AS DWORD
    FileNameLength        AS DWORD ' the length, in bytes, of the FileName
'   FileName              AS uFileDirectoryInformation ' A sequence of Unicode characters containing the file name
END TYPE
                  
TYPE FILE_NAMES_INFORMATION ' http://msdn.microsoft.com/en-us/library/cc232097.aspx
    NextEntryOffset       AS DWORD ' offset from current record to start of next record (zero at last record)
    FileIndex             AS DWORD ' index
    FileNameLength        AS DWORD ' the length, in bytes, of the FileName 
'   FileName              AS uFileDirectoryInformation ' A sequence of Unicode characters containing the file name
END TYPE


             
             
' http://msdn.microsoft.com/en-us/library/ms801001.aspx
DECLARE FUNCTION ZwQueryDirectoryFile LIB "NTDLL.DLL" ALIAS "ZwQueryDirectoryFile" ( _  ' Returns STATUS_SUCCESS or error code
                BYVAL hFile AS DWORD,_                    ' handle to the file
                BYVAL hEvent AS DWORD,_                   ' EventHandle OPTIONAL
                BYVAL pAPCroutine AS DWORD,_              ' ApcRoutine OPTIONAL
                BYVAL pAPCcontext AS DWORD,_              ' ApcContext OPTIONAL
                BYVAL pIOStatus AS DWORD,_                ' IoStatusBlock
                BYVAL fileInfo AS DWORD,_                 ' pointer to the buffer to receive the result    
                BYVAL length AS DWORD,_                   ' The size, in bytes, of the buffer pointed to by FileInformation                             
                BYVAL FileInformationClass AS DWORD,_     ' The type of information to be returned about files in the directory                             
                BYVAL ReturnSingleEntry AS BYTE,_         ' Set to TRUE if only a single entry should be returned, FALSE otherwise.     
                BYVAL pFileMask AS DWORD,_                ' OPTIONAL Unicode Filename template for search                             
                BYVAL RestartScan AS BYTE) AS LONG        ' Set to TRUE if the scan is to start at the first entry in the directory                              

              

          

'¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤
FUNCTION DtaStrWinErrorText( BYVAL ErrCode AS DWORD ) AS STRING

  LOCAL pBuffer   AS ASCIIZ PTR
  LOCAL ncbBuffer AS DWORD

    ncbBuffer = FormatMessage( %FORMAT_MESSAGE_ALLOCATE_BUFFER _
                            OR %FORMAT_MESSAGE_FROM_SYSTEM     _
                            OR %FORMAT_MESSAGE_IGNORE_INSERTS  _
                            OR %FORMAT_MESSAGE_MAX_WIDTH_MASK, _
                               BYVAL 0, _  ' %NULL
                               ErrCode, _
                               BYVAL MAKELANGID(%LANG_NEUTRAL, %SUBLANG_DEFAULT), _
                               BYVAL VARPTR(pBuffer), _
                               0, _
                               BYVAL 0 ) ' %NULL 

    IF ncbBuffer THEN
        FUNCTION = PEEK$(pBuffer, ncbBuffer)
        LocalFree pBuffer
    ELSE
        FUNCTION = "Unknown error, code = &H" + HEX$(ErrCode, 8)
    END IF  

END FUNCTION

             

'¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤                                                                                              
FUNCTION BytesToHex( sSent AS STRING ) AS STRING  ' For Debugging
           
  LOCAL i, nBytes AS LONG
  LOCAL sRet AS STRING      
  LOCAL b AS BYTE PTR
  
    b = STRPTR(sSent)
    nBytes = LEN(sSent)
    FOR i = 0 TO nBytes-1
      sRet = sRet + HEX$(@b[i], 2)+" "  
    NEXT i '
        
  FUNCTION = sRet ' PRINT #hDbg, "LenStored="+STR$(DtaStrDataLen(pRes)) + ", nBytes="+STR$(nBytes) 

END FUNCTION
             

'¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤
FUNCTION EnumPipes(hDlg AS LONG) AS STRING

  LOCAL i, nPipes, BuffLen, ntStatus, Count AS LONG 
  LOCAL hPipe AS DWORD
  LOCAL bReset AS BYTE 
  LOCAL pBuff AS DWORD PTR
  LOCAL sBuff, sPipeNames AS STRING
  LOCAL zPipeName AS ASCIIZ * %MAX_PATH
  LOCAL pDirInfo  AS FILE_NAMES_INFORMATION PTR
  LOCAL IOStatus  AS IO_STATUS_BLOCK
  LOCAL pIOStatus AS IO_STATUS_BLOCK PTR
   
 

    zPipeName = "\\.\\pipe\" ' nice trick
    hPipe = CreateFile( zPipeName, _
                        %GENERIC_READ OR %GENERIC_WRITE, _
                        %FILE_SHARE_READ OR %FILE_SHARE_WRITE,_
                        BYVAL %NULL, _
                        %OPEN_EXISTING, _
                        0, _
                        %NULL)

    IF hPipe < 1 THEN ' ERROR = %INVALID_HANDLE_VALUE - DWORD 0xFFFFFFFF - LONG value < 0
      MSGBOX "Could not create pipe",48,"Error=" + STR$(GetLastError) 
      EXIT FUNCTION
    END IF ' PRINT #hDbg, "hPipe=" + HEX$(hPipe) + ", CreateNamedPipe Error= "+DtaStrWinErrorText(GetLastError)

    pIOStatus = VARPTR(IOStatus)
    BuffLen   = 1600 ' Arbitrary length big enough for at least one record
    DO    
      INCR Count
      IF Count > 99 THEN MSGBOX "Runaway loop",48,"ERROR" : EXIT DO ' Endless loop protection
      sBuff = NUL$(BuffLen) ' Buffer to hold a few FILE_NAMES_INFORMATION structures
      pBuff = STRPTR(sBuff) ' VARPTR(DirInfo) 

      ntStatus = ZwQueryDirectoryFile(  hPipe, _                      ' Handle to the file                             
                                        %NULL, _                      ' EventHandle OPTIONAL                           
                                        %NULL, _                      ' ApcRoutine OPTIONAL                            
                                        %NULL, _                      ' ApcContext OPTIONAL                            
                                        pIOStatus, _                  ' IoStatusBlock                                  
                                        pBuff, _                      ' Pointer to the buffer to receive the result    
                                        BuffLen, _                    ' Length of Buffer                               
                                        %FileNamesInformation, _      ' Information type                               
                                        %FALSE, _                     ' Each call returns info for only one file       
                                        %NULL, _                      ' Template for search                            
                                        bReset )                      ' Restart search
                                         
                               
      IF ntStatus = %STATUS_BUFFER_OVERFLOW THEN '
        MSGBOX "Error STATUS_BUFFER_OVERFLOW",48,"ERROR="+HEX$(ntStatus)
        EXIT DO
       
      ELSEIF ntStatus = %STATUS_NO_MORE_FILES THEN ' PRINT #hDbg, "STATUS_NO_MORE_FILES"
        EXIT DO

      ELSEIF ntStatus <> %STATUS_SUCCESS THEN ' PRINT #hDbg, "ntStatus="+HEX$(ntStatus)
        IF ntStatus = %STATUS_INVALID_PARAMETER THEN MSGBOX "STATUS_INVALID_PARAMETER",48,"ERROR"                 
        i = GetLastError()
        MSGBOX "ZwQueryDirectoryFile Error="+STR$(i) + " - " + DtaStrWinErrorText(i),48,"ERROR="+HEX$(ntStatus)
        EXIT FUNCTION
      END IF ' PRINT #hDbg, "Bytes of Structures="+STR$(IOStatus.information) 
                  
      pDirInfo = pBuff
      DO
        INCR nPipes
'        PRINT #hDbg, ""
'        PRINT #hDbg, "NextEntryOffset="+STR$(@pDirInfo.NextEntryOffset)
'        PRINT #hDbg, "FileIndex      ="+STR$(@pDirInfo.FileIndex      )
'        PRINT #hDbg, "FileNameLength ="+STR$(@pDirInfo.FileNameLength ) 
'        PRINT #hDbg, "Pipe#" + STR$(nPipes) +" >"+acode$( PEEK$(pDirInfo+12, @pDirInfo.FileNameLength) ) + "<" ' len of the structure

        sPipeNames = FORMAT$(nPipes, "00") +" >" + ACODE$( PEEK$(pDirInfo+12, @pDirInfo.FileNameLength) ) + "<" + $CRLF + sPipeNames
        IF @pDirInfo.NextEntryOffset = 0 THEN EXIT LOOP

        pDirInfo = pDirInfo + @pDirInfo.NextEntryOffset 
      LOOP
    LOOP 
                    
    CALL CloseHandle(hPipe)
   
  FUNCTION = sPipeNames

END FUNCTION    



'¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤'
FUNCTION MakeFont( BYVAL nFont AS STRING, BYVAL PointSize AS LONG ) AS LONG

  LOCAL hDC AS LONG, CyPixels AS LONG
 
    hDC       = GETDC(%HWND_DESKTOP)
    CyPixels  = GETDEVICECAPS(hDC, %LOGPIXELSY)
    CALL RELEASEDC(%HWND_DESKTOP, hDC)
    PointSize = (PointSize * CyPixels) \ 72
    FUNCTION  = CREATEFONT( 0 - PointSize, 0, 0, 0, %FW_NORMAL, 0, 0, 0, %ANSI_CHARSET, %OUT_TT_PRECIS, _
                %CLIP_DEFAULT_PRECIS, %DEFAULT_QUALITY, %FF_DONTCARE, BYCOPY nFont )  
END FUNCTION
           

'¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤'
CALLBACK FUNCTION MainCallback()

  LOCAL hFont AS LONG
  LOCAL sTemp AS STRING    

     SELECT CASE CBMSG
        CASE %WM_INITDIALOG 
          hFont = MakeFont("COURIER NEW", 9) ' Font Size and style
          CONTROL SEND      CBHNDL, 404, %WM_SETFONT, hFont, 1    
          FUNCTION = %TRUE   
                   

        CASE %WM_COMMAND
          SELECT CASE CBCTL 
            CASE 301 ' Run 
              sTemp = EnumPipes(CBHNDL) ' <------------------------------------
              CONTROL SET TEXT CBHNDL, 404, sTemp
          END SELECT
                  
    END SELECT 


END FUNCTION
       
   
'¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤'
FUNCTION PBMAIN ()
           
  LOCAL hDlg AS LONG

'hDbg = FREEFILE : OPEN "EnumPipes_Debug.txt"FOR OUTPUT SHARED AS hDbg ' 
'PRINT #hDbg, "--------  "+DATE$+"  "+TIME$+"  ---------"  

    DIALOG NEW 0, "Named Pipes (DESCENDING)", 30, 26, 305, 206, %WS_SYSMENU  TO hDlg
                               
    CONTROL ADD BUTTON,  hDlg, 301,   "enum", 09, 04, 040, 016, 0

    CONTROL ADD TEXTBOX, hDlg, 404,       "", 09, 22, 282, 160, %WS_CHILD OR %WS_VISIBLE OR %ES_MULTILINE OR _
                                                               %ES_WANTRETURN OR %ES_LEFT OR %ES_AUTOVSCROLL OR _
                                                               %WS_VSCROLL OR %WS_HSCROLL OR %WS_TABSTOP, %WS_EX_CLIENTEDGE
    DIALOG SHOW MODAL hDlg, CALL MainCallback
           

'PRINT #hDbg, "-------  ALL DONE --------"
'CLOSE #hDbg

END FUNCTION
'¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤'


Compiled Application (32bit Windows) - EnumPipes.zip (18k)





ċ
EnumPipes.zip
(18k)
theflyingnomad,
Apr 23, 2009, 1:51 PM
Comments